buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class TestUtilsHashPass(SimpleTestCase): self.assertTrue(check_password('letmein', encoded, setter)) self.assertTrue(state['upgraded']) def test_load_library_no_algorithm(self): with self.assertRaises(ValueError) as e: BasePasswordHasher()._load_library()
class TestUtilsHashPass(SimpleTestCase): self.assertTrue(check_password('letmein', encoded, setter)) self.assertTrue(state['upgraded']) def test_check_password_calls_harden_runtime(self): hasher = get_hasher('default') encoded = make_password('letmein') with mock.pa...
import recurly.errors from recurly.link_header import parse_link_value from six.moves import http_client from six.moves.urllib.parse import urlencode, urljoin, urlsplit class Money(object):
import recurly.errors from recurly.link_header import parse_link_value from six.moves import http_client from six.moves.urllib.parse import urlencode, urlsplit, quote class Money(object):
def get(cls, uuid): can be directly requested with this method. """ url = urljoin(recurly.base_uri(), cls.member_path % (uuid,)) resp, elem = cls.element_for_url(url) return cls.from_element(elem)
def get(cls, uuid): can be directly requested with this method. """ uuid = quote(str(uuid)) url = recurly.base_uri() + (cls.member_path % (uuid,)) resp, elem = cls.element_for_url(url) return cls.from_element(elem)
def all(cls, **kwargs): parameters. """ url = urljoin(recurly.base_uri(), cls.collection_path) if kwargs: url = '%s?%s' % (url, urlencode(kwargs)) return Page.page_for_url(url)
def all(cls, **kwargs): parameters. """ url = recurly.base_uri() + cls.collection_path if kwargs: url = '%s?%s' % (url, urlencode(kwargs)) return Page.page_for_url(url)
def count(cls, **kwargs): """Return a count of server side resources given filtering arguments in kwargs. """ url = urljoin(recurly.base_uri(), cls.collection_path) if kwargs: url = '%s?%s' % (url, urlencode(kwargs)) return Page.count_for_url(url)
def count(cls, **kwargs): """Return a count of server side resources given filtering arguments in kwargs. """ url = recurly.base_uri() + cls.collection_path if kwargs: url = '%s?%s' % (url, urlencode(kwargs)) return Page.count_for_url(url)
def _update(self): return self.put(self._url) def _create(self): url = urljoin(recurly.base_uri(), self.collection_path) return self.post(url) def put(self, url):
def _update(self): return self.put(self._url) def _create(self): url = recurly.base_uri() + self.collection_path return self.post(url) def put(self, url):
class Driver(object): current_line = "" current_column = 0 wait_for_nl = False elif char == ' ': current_column += 1 elif char == '\t': current_column += 4 elif char == '\n': #...
class Driver(object): current_line = "" current_column = 0 wait_for_nl = False elif char in ' \t': current_column += 1 elif char == '\n': # unexpected empty line current_column = 0
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, line_length=ll) def test_report_verbose(self) -> None: report = black.Report(verbose=True) out_lines = []
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, line_length=ll) def test_comment_indentation(self) -> None: contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n" contents_spc = "if 1:\n if 2:\n ...
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...
"""rope, a python refactoring library""" INFO = __doc__ VERSION = '0.10.7' COPYRIGHT = """\ Copyright (C) 2015-2016 Nicholas Smith Copyright (C) 2014-2015 Matej Cepl Copyright (C) 2006-2012 Ali Gholami Rudi Copyright (C) 2009-2012 Anton Gritsay
"""rope, a python refactoring library""" INFO = __doc__ VERSION = '0.11.0' COPYRIGHT = """\ Copyright (C) 2015-2018 Nicholas Smith Copyright (C) 2014-2015 Matej Cepl Copyright (C) 2006-2012 Ali Gholami Rudi Copyright (C) 2009-2012 Anton Gritsay
class tqdm(Comparable): if not _is_ascii(full_bar.charset) and _is_ascii(bar_format): bar_format = _unicode(bar_format) res = bar_format.format(bar=full_bar, **format_dict) if ncols: return disp_trim(res, ncols) elif bar_format: # ...
class tqdm(Comparable): if not _is_ascii(full_bar.charset) and _is_ascii(bar_format): bar_format = _unicode(bar_format) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res elif bar_format: # user-spe...
class tqdm(Comparable): if ncols else 10, charset=Bar.BLANK) res = bar_format.format(bar=full_bar, **format_dict) if ncols: return disp_trim(res, ncols) else: # no total: no progressbar, ETA, just progress stats retu...
class tqdm(Comparable): if ncols else 10, charset=Bar.BLANK) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res else: # no total: no progressbar, ETA, just progress stats return ((pre...
def test_format_meter(): # l_bar gets chopped # no bar # no r_bar format_meter(0, 1000, 13, ncols=10, bar_width=10, bar_format="************{bar}$$$$$$$$$$"), "**********" # 10/12 stars since ncols is 10 ) eq_(
def test_format_meter(): # l_bar gets chopped # no bar # no r_bar format_meter(0, 1000, 13, ncols=10, bar_format="************{bar:10}$$$$$$$$$$"), "**********" # 10/12 stars since ncols is 10 ) eq_(
def test_format_meter(): # l_bar displays # bar gets chopped # no r_bar format_meter(0, 1000, 13, ncols=20, bar_width=10, bar_format="************{bar}$$$$$$$$$$"), "************ " # all 12 stars and 8/10 bar parts ) eq_(
def test_format_meter(): # l_bar displays # bar gets chopped # no r_bar format_meter(0, 1000, 13, ncols=20, bar_format="************{bar:10}$$$$$$$$$$"), "************ " # all 12 stars and 8/10 bar parts ) eq_(
def test_format_meter(): # l_bar displays # bar displays # r_bar gets chopped format_meter(0, 1000, 13, ncols=30, bar_width=10, bar_format="************{bar}$$$$$$$$$$"), "************ $$$$$$$$" # all 12 stars and 10 bar parts, but only 8/10 dollar signs ) eq_( ...
def test_format_meter(): # l_bar displays # bar displays # r_bar gets chopped format_meter(0, 1000, 13, ncols=30, bar_format="************{bar:10}$$$$$$$$$$"), "************ $$$$$$$$" # all 12 stars and 10 bar parts, but only 8/10 dollar signs ) eq_( # l...
def disp_trim(data, length): if len(data) == disp_len(data): return data[:length] while disp_len(data) > length: # carefully delete one char at a time data = data[:-1] if RE_ANSI.search(data): # assume ANSI reset is required return data + "\033[0m" return data
def disp_trim(data, length): if len(data) == disp_len(data): return data[:length] ansi_present = bool(RE_ANSI.search(data)) while disp_len(data) > length: # carefully delete one char at a time data = data[:-1] if ansi_present and bool(RE_ANSI.search(data)): # assume ANSI reset ...
def serialize_response( errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder( value, include=include,
def serialize_response( errors.extend(errors_) if errors: raise ValidationError(errors) if skip_defaults and isinstance(response, BaseModel): value = response.dict(skip_defaults=skip_defaults) return jsonable_encoder( value, include=inc...
from tests.utils import Command Command(script='open foo.org'), Command(script='open foo.net'), Command(script='open foo.se'), Command(script='open foo.io')]) def test_match(command): assert match(command, None)
from tests.utils import Command Command(script='open foo.org'), Command(script='open foo.net'), Command(script='open foo.se'), Command(script='open foo.io'), Command(script='xdg-open foo.com'), Command(script='gnome-open foo.com'), Command(script='kde-open foo.com')]) def test_match(command)...
def test_match(command): (Command('open foo.org'), 'open http://foo.org'), (Command('open foo.net'), 'open http://foo.net'), (Command('open foo.se'), 'open http://foo.se'), (Command('open foo.io'), 'open http://foo.io')]) def test_get_new_command(command, new_command): assert get_new_command(command...
def test_match(command): (Command('open foo.org'), 'open http://foo.org'), (Command('open foo.net'), 'open http://foo.net'), (Command('open foo.se'), 'open http://foo.se'), (Command('open foo.io'), 'open http://foo.io'), (Command('xdg-open foo.io'), 'xdg-open http://foo.io'), (Command('gnome-ope...
def match(command, settings): def get_new_command(command, settings): return 'open http://' + command.script[5:]
def match(command, settings): def get_new_command(command, settings): return command.script.replace('open ', 'open http://')
class MinimumLengthValidator: ) % {'min_length': self.min_length} class UserAttributeSimilarityValidator: """ Validate whether the password is sufficiently different from the user's
class MinimumLengthValidator: ) % {'min_length': self.min_length} def exceeds_maximum_length_ratio(password, max_similarity, value): """ Test that value is within a reasonable range of password. The following ratio calculations are based on testing SequenceMatcher like this: for i in ran...
class UserAttributeSimilarityValidator: def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes self.max_similarity = max_similarity def validate(self, password, user=None): if not user: return for att...
class UserAttributeSimilarityValidator: def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7): self.user_attributes = user_attributes if max_similarity < 0.1: raise ValueError('max_similarity must be at least 0.1') self.max_similarity = max_similarity ...
class UserAttributeSimilarityValidatorTest(TestCase): max_similarity=1, ).validate(user.first_name, user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # max_similarity=0 rejects all passwords. with self.assertRaises(ValidationError) as...
class UserAttributeSimilarityValidatorTest(TestCase): max_similarity=1, ).validate(user.first_name, user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # Very low max_similarity is rejected. msg = 'max_similarity must be at least 0.1' ...
class ImagesPipeline(FilesPipeline): # ImagesPipeline. They may be overridden by settings. MIN_WIDTH = 0 MIN_HEIGHT = 0 EXPIRES = 0 THUMBS = {} DEFAULT_IMAGES_URLS_FIELD = 'image_urls' DEFAULT_IMAGES_RESULT_FIELD = 'images'
class ImagesPipeline(FilesPipeline): # ImagesPipeline. They may be overridden by settings. MIN_WIDTH = 0 MIN_HEIGHT = 0 EXPIRES = 90 THUMBS = {} DEFAULT_IMAGES_URLS_FIELD = 'image_urls' DEFAULT_IMAGES_RESULT_FIELD = 'images'
class ImagesPipelineTestCaseCustomSettings(unittest.TestCase): default_pipeline_settings = dict( MIN_WIDTH=0, MIN_HEIGHT=0, EXPIRES=0, THUMBS={}, IMAGES_URLS_FIELD='image_urls', IMAGES_RESULT_FIELD='images'
class ImagesPipelineTestCaseCustomSettings(unittest.TestCase): default_pipeline_settings = dict( MIN_WIDTH=0, MIN_HEIGHT=0, EXPIRES=90, THUMBS={}, IMAGES_URLS_FIELD='image_urls', IMAGES_RESULT_FIELD='images'
from youtube_dl.utils import ( DateRange, encodeFilename, find_xpath_attr, get_meta_content, orderedSet, parse_duration,
from youtube_dl.utils import ( DateRange, encodeFilename, find_xpath_attr, fix_xml_ampersands, get_meta_content, orderedSet, parse_duration,
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('9:12:43'), 33163) self.assertEqual(parse_duration('x:y'), None) if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('9:12:43'), 33163) self.assertEqual(parse_duration('x:y'), None) def test_fix_xml_ampersands(self): self.assertEqual( fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a') self.assertEqual( fi...
import re from .common import InfoExtractor from ..utils import ( find_xpath_attr, fix_xml_all_ampersand, )
import re from .common import InfoExtractor from ..utils import ( find_xpath_attr, fix_xml_ampersands )
class ClipsyndicateIE(InfoExtractor): pdoc = self._download_xml( 'http://eplayer.clipsyndicate.com/osmf/playlist?%s' % flvars, video_id, u'Downloading video info', transform_source=fix_xml_all_ampersand) track_doc = pdoc.find('trackList/track') def find_para...
class ClipsyndicateIE(InfoExtractor): pdoc = self._download_xml( 'http://eplayer.clipsyndicate.com/osmf/playlist?%s' % flvars, video_id, u'Downloading video info', transform_source=fix_xml_ampersands) track_doc = pdoc.find('trackList/track') def find_param(na...
import re from .common import InfoExtractor from ..utils import ( fix_xml_all_ampersand, )
import re from .common import InfoExtractor from ..utils import ( fix_xml_ampersands, )
class MetacriticIE(InfoExtractor): webpage = self._download_webpage(url, video_id) # The xml is not well formatted, there are raw '&' info = self._download_xml('http://www.metacritic.com/video_data?video=' + video_id, video_id, 'Downloading info xml', transform_source=fix_xml_all_amp...
class MetacriticIE(InfoExtractor): webpage = self._download_webpage(url, video_id) # The xml is not well formatted, there are raw '&' info = self._download_xml('http://www.metacritic.com/video_data?video=' + video_id, video_id, 'Downloading info xml', transform_source=fix_xml_ampersa...
from .common import InfoExtractor from ..utils import ( compat_urllib_parse, ExtractorError, ) def _media_xml_tag(tag):
from .common import InfoExtractor from ..utils import ( compat_urllib_parse, ExtractorError, fix_xml_ampersands, ) def _media_xml_tag(tag):
class MTVServicesInfoExtractor(InfoExtractor): video_id = self._id_from_uri(uri) data = compat_urllib_parse.urlencode({'uri': uri}) def fix_ampersand(s): """ Fix unencoded ampersand in XML """ return s.replace(u'& ', '&amp; ') idoc = self._download_xml( ...
class MTVServicesInfoExtractor(InfoExtractor): video_id = self._id_from_uri(uri) data = compat_urllib_parse.urlencode({'uri': uri}) idoc = self._download_xml( self._FEED_URL + '?' + data, video_id, u'Downloading info', transform_source=fix_xml_ampersands) return ...
def month_by_name(name): return None def fix_xml_all_ampersand(xml_str): """Replace all the '&' by '&amp;' in XML""" return xml_str.replace(u'&', u'&amp;') def setproctitle(title):
def month_by_name(name): return None def fix_xml_ampersands(xml_str): """Replace all the '&' by '&amp;' in XML""" return re.sub( r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)', u'&amp;', xml_str) def setproctitle(title):
from ansible.release import __version__ from ansible.utils.collection_loader import set_collection_playbook_paths from ansible.utils.display import Display from ansible.utils.path import unfrackpath from ansible.vars.manager import VariableManager
from ansible.release import __version__ from ansible.utils.collection_loader import set_collection_playbook_paths from ansible.utils.display import Display from ansible.utils.path import unfrackpath from ansible.utils.unsafe_proxy import AnsibleUnsafeBytes from ansible.vars.manager import VariableManager
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 ...
from django.contrib.postgres.fields import ArrayField, JSONField from django.db.models.aggregates import Aggregate from .mixins import OrderableAggMixin
from django.contrib.postgres.fields import ArrayField, JSONField from django.db.models import Value from django.db.models.aggregates import Aggregate from .mixins import OrderableAggMixin
class JSONBAgg(Aggregate): class StringAgg(OrderableAggMixin, Aggregate): function = 'STRING_AGG' template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s'%(ordering)s)" allow_distinct = True def __init__(self, expression, delimiter, **extra): super().__init__(expression, delimiter...
class JSONBAgg(Aggregate): class StringAgg(OrderableAggMixin, Aggregate): function = 'STRING_AGG' template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)' allow_distinct = True def __init__(self, expression, delimiter, **extra): delimiter_expr = Value(str(delimiter)) super()...
from django.db.models.expressions import F, OrderBy class OrderableAggMixin: def __init__(self, expression, ordering=(), **extra): if not isinstance(ordering, (list, tuple)): ordering = [ordering] ordering = ordering or []
from django.db.models.expressions import F, OrderBy class OrderableAggMixin: def __init__(self, *expressions, ordering=(), **extra): if not isinstance(ordering, (list, tuple)): ordering = [ordering] ordering = ordering or []
class OrderableAggMixin: (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in ordering ) super().__init__(expression, **extra) self.ordering = self._parse_expressions(*ordering) def resolve_expression(self, *args, **kwargs):
class OrderableAggMixin: (OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o) for o in ordering ) super().__init__(*expressions, **extra) self.ordering = self._parse_expressions(*ordering) def resolve_expression(self, *args, **kwargs):
class TestGeneralAggregate(PostgreSQLTestCase): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field')) def test_string_agg_charfield(self): values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimiter=';'))...
class TestGeneralAggregate(PostgreSQLTestCase): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field')) def test_string_agg_delimiter_escaping(self): values = AggregateTestModel.objects.aggregate(stringagg=StringAgg('char_field', delimi...
class Tracer: self.target_codes = set() self.target_frames = set() self.thread_local = threading.local() self.custom_repr = custom_repr def __call__(self, function):
class Tracer: self.target_codes = set() self.target_frames = set() self.thread_local = threading.local() if len(custom_repr) == 2 and not all(isinstance(x, pycompat.collections_abc.Iterable) for x in custom_repr): custom_repr = (custom_repr,) sel...
def test_custom_repr(): ) ) def test_disable(): string_io = io.StringIO()
def test_custom_repr(): ) ) def test_custom_repr_single(): string_io = io.StringIO() @pysnooper.snoop(string_io, custom_repr=(list, lambda l: 'foofoo!')) def sum_to_x(x): l = list(range(x)) return 7 result = sum_to_x(10000) output = string_io.getvalue() assert_out...
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 TensorBoard(Callback): tf.summary.image(mapped_weight_name, w_img) if hasattr(layer, 'output'): tf.summary.histogram('{}_out'.format(layer.name), layer.output) self.merged = tf.summary.merge_all() ...
class TensorBoard(Callback): tf.summary.image(mapped_weight_name, w_img) if hasattr(layer, 'output'): if isinstance(layer.output, list): for i, output in enumerate(layer.output): tf.summary.histogram('{}_out...
from keras import optimizers from keras import initializers from keras import callbacks from keras.models import Sequential, Model from keras.layers import Input, Dense, Dropout, add from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPooling2D, GlobalAveragePooling2D from keras.utils.test...
from keras import optimizers from keras import initializers from keras import callbacks from keras.models import Sequential, Model from keras.layers import Input, Dense, Dropout, add, dot, Lambda from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPooling2D, GlobalAveragePooling1D, GlobalA...
def test_TensorBoard_multi_input_output(tmpdir): (X_train, y_train), (X_test, y_test) = get_test_data( num_train=train_samples, num_test=test_samples, input_shape=(input_dim,), classification=True, num_classes=num_classes) y_test = np_utils.to_categorical(y_test)
def test_TensorBoard_multi_input_output(tmpdir): (X_train, y_train), (X_test, y_test) = get_test_data( num_train=train_samples, num_test=test_samples, input_shape=(input_dim, input_dim), classification=True, num_classes=num_classes) y_test = np_utils.to_categorical(y_test...
def test_TensorBoard_multi_input_output(tmpdir): i += 1 i = i % max_batch_index inp1 = Input((input_dim,)) inp2 = Input((input_dim,)) inp = add([inp1, inp2]) hidden = Dense(num_hidden, activation='relu')(inp) hidden = Dropout(0.1)(hidden) output1 = Dense(num_classes, act...
def test_TensorBoard_multi_input_output(tmpdir): i += 1 i = i % max_batch_index inp1 = Input((input_dim, input_dim)) inp2 = Input((input_dim, input_dim)) inp_3d = add([inp1, inp2]) inp_2d = GlobalAveragePooling1D()(inp_3d) inp_pair = Lambda(lambda x: x)([inp_3d, inp_2d]) # ...
def _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding): outlen = backend._ffi.new("size_t *", buf_size) buf = backend._ffi.new("unsigned char[]", buf_size) res = crypt(pkey_ctx, buf, outlen, data, len(data)) if res <= 0: _handle_rsa_enc_dec_error(backend, key) return backend....
def _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding): outlen = backend._ffi.new("size_t *", buf_size) buf = backend._ffi.new("unsigned char[]", buf_size) # Everything from this line onwards is written with the goal of being as # constant-time as is practical given the constraints of Pyt...
def parse_uri(self, uri): ", you need to change it to use the " "swift+http:// scheme, like so: " "swift+http://user:pass@authurl.com/v1/container/obj") LOG.debug(_("Invalid store uri %(uri)s: %(reason)s") % locals()) raise exc...
def parse_uri(self, uri): ", you need to change it to use the " "swift+http:// scheme, like so: " "swift+http://user:pass@authurl.com/v1/container/obj") LOG.debug(_("Invalid store URI: %(reason)s") % locals()) raise exception.B...
def parse_uri(self, uri): if creds: cred_parts = creds.split(':') if len(cred_parts) != 2: reason = (_("Badly formed credentials '%(creds)s' in Swift " "URI") % locals()) LOG.debug(reason) raise exception.BadStor...
def parse_uri(self, uri): if creds: cred_parts = creds.split(':') if len(cred_parts) != 2: reason = (_("Badly formed credentials in Swift URI.")) LOG.debug(reason) raise exception.BadStoreUri() user, key = cred_parts
def parse_uri(self, uri): path_parts.insert(0, netloc) self.auth_or_store_url = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI: %s") % uri LOG.debug(reason) raise exception.BadStoreUri()
def parse_uri(self, uri): path_parts.insert(0, netloc) self.auth_or_store_url = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI.") LOG.debug(reason) raise exception.BadStoreUri()
def get(self, location, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % loc...
def get(self, location, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: ...
def add(self, image_id, image_file, image_size, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "location %s") % ...
def add(self, image_id, image_file, image_size, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.CONFLICT: raise exception.Duplicate(_("Swift already has an image at " "this location")) msg = ...
def delete(self, location, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % ...
def delete(self, location, connection=None): except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: ...
def set_acls(self, location, public=False, read_tenants=None, except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() raise exception.NotFound(_("Swift could not find image at " ...
def set_acls(self, location, public=False, read_tenants=None, except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) ...
class Index(IndexOpsMixin, PandasObject): self._invalid_indexer("label", key) elif kind == "loc" and is_integer(key): if not self.holds_integer(): self._invalid_indexer("label", key) return key
class Index(IndexOpsMixin, PandasObject): self._invalid_indexer("label", key) elif kind == "loc" and is_integer(key): if not (is_integer_dtype(self.dtype) or is_object_dtype(self.dtype)): self._invalid_indexer("label", key) return key
class Series(base.IndexOpsMixin, generic.NDFrame): if takeable: return self._values[label] # We assume that _convert_scalar_indexer has already been called, # with kind="loc", if necessary, by the time we get here return self.index.get_value(self, label) def __setitem_...
class Series(base.IndexOpsMixin, generic.NDFrame): if takeable: return self._values[label] # Similar to Index.get_value, but we do not fall back to positional loc = self.index.get_loc(label) # We assume that _convert_scalar_indexer has already been called, # with ki...
class TestCategoricalIndex: with pytest.raises(TypeError, match=msg): df.loc["d", "C"] = 10 msg = ( "cannot do label indexing on CategoricalIndex with these " r"indexers \[1\] of type int" ) with pytest.raises(TypeError, match=msg): df.loc...
class TestCategoricalIndex: with pytest.raises(TypeError, match=msg): df.loc["d", "C"] = 10 with pytest.raises(KeyError, match="^1$"): df.loc[1] def test_getitem_scalar(self):
class TestLoc(Base): def test_loc_getitem_int(self): # int label self.check_result("loc", 2, typs=["labels"], fails=TypeError) def test_loc_getitem_label(self):
class TestLoc(Base): def test_loc_getitem_int(self): # int label self.check_result("loc", 2, typs=["labels"], fails=KeyError) def test_loc_getitem_label(self):
class TestLoc(Base): self.check_result( "loc", 20, typs=["ints", "uints", "mixed"], fails=KeyError, ) self.check_result("loc", 20, typs=["labels"], fails=TypeError) self.check_result("loc", 20, typs=["ts"], axes=0, fails=TypeError) self.check_result("loc", 20, typs=["...
class TestLoc(Base): self.check_result( "loc", 20, typs=["ints", "uints", "mixed"], fails=KeyError, ) self.check_result("loc", 20, typs=["labels"], fails=KeyError) self.check_result("loc", 20, typs=["ts"], axes=0, fails=TypeError) self.check_result("loc", 20, typs=["f...
def test_loc_set_dataframe_multiindex(): result = expected.copy() result.loc[0, [(0, 1)]] = result.loc[0, [(0, 1)]] tm.assert_frame_equal(result, expected)
def test_loc_set_dataframe_multiindex(): result = expected.copy() result.loc[0, [(0, 1)]] = result.loc[0, [(0, 1)]] tm.assert_frame_equal(result, expected) def test_loc_mixed_int_float(): # GH#19456 ser = pd.Series(range(2), pd.Index([1, 2.0], dtype=object)) result = ser.loc[1] assert res...
class TestScalar2: result = ser.loc["a"] assert result == 1 msg = ( "cannot do label indexing on Index " r"with these indexers \[0\] of type int" ) with pytest.raises(TypeError, match=msg): ser.at[0] with pytest.raises(TypeError, match...
class TestScalar2: result = ser.loc["a"] assert result == 1 with pytest.raises(KeyError, match="^0$"): ser.at[0] with pytest.raises(KeyError, match="^0$"): ser.loc[0] def test_frame_raises_key_error(self): # GH#31724 .at should match .loc df ...
class TestScalar2: result = df.loc["a", "A"] assert result == 1 msg = ( "cannot do label indexing on Index " r"with these indexers \[0\] of type int" ) with pytest.raises(TypeError, match=msg): df.at["a", 0] with pytest.raises(TypeErro...
class TestScalar2: result = df.loc["a", "A"] assert result == 1 with pytest.raises(KeyError, match="^0$"): df.at["a", 0] with pytest.raises(KeyError, match="^0$"): df.loc["a", 0] def test_series_at_raises_key_error(self):
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_file(fname, Path to the downloaded file """ # noqa if cache_dir is None: cache_dir = os.path.join(os.path.expanduser('~'), '.keras') if md5_hash is not None and file_hash is None: file_hash = md5_hash hash_algorithm = 'md5'
def get_file(fname, Path to the downloaded file """ # noqa if cache_dir is None: if 'KERAS_HOME' in os.environ: cache_dir = os.environ.get('KERAS_HOME') else: cache_dir = os.path.join(os.path.expanduser('~'), '.keras') if md5_hash is not None and file_hash is...
import time import sys import tarfile import threading import zipfile from itertools import cycle import multiprocessing as mp
import time import sys import tarfile import threading import shutil import zipfile from itertools import cycle import multiprocessing as mp
import pytest import six from six.moves.urllib.parse import urljoin from six.moves.urllib.request import pathname2url from flaky import flaky
import pytest import six from six.moves.urllib.parse import urljoin from six.moves.urllib.request import pathname2url from six.moves import reload_module from flaky import flaky
def test_data_utils(in_tmpdir): origin = urljoin('file://', pathname2url(os.path.abspath('test.tar.gz'))) path = get_file(dirname, origin, untar=True) filepath = path + '.tar.gz' hashval_sha256 = _hash_file(filepath)
def test_data_utils(in_tmpdir): origin = urljoin('file://', pathname2url(os.path.abspath('test.tar.gz'))) path = get_file(dirname, origin, untar=True) filepath = path + '.tar.gz' data_keras_home = os.path.dirname(os.path.dirname(os.path.abspath(filepath))) assert data_keras_home == os.path.dirname...
def test_data_utils(in_tmpdir): assert validate_file(path, hashval_md5) os.remove(path) os.remove('test.txt') os.remove('test.zip')
def test_data_utils(in_tmpdir): assert validate_file(path, hashval_md5) os.remove(path) os.remove(os.path.join(os.path.dirname(path), 'test.txt')) os.remove('test.txt') os.remove('test.zip')
from RestrictedPython.Utilities import utility_builtins from zExceptions import Unauthorized from AccessControl.SecurityInfo import secureModule from AccessControl.SecurityManagement import getSecurityManager from AccessControl.SimpleObjectPolicies import ContainerAssertions
from RestrictedPython.Utilities import utility_builtins from zExceptions import Unauthorized from AccessControl.SecurityInfo import ModuleSecurityInfo from AccessControl.SecurityInfo import secureModule from AccessControl.SecurityManagement import getSecurityManager from AccessControl.SimpleObjectPolicies import Conta...
math.__allow_access_to_unprotected_subobjects__ = 1 random.__allow_access_to_unprotected_subobjects__ = 1 # AccessControl.Implementation inserts these names into this module as # module globals: aq_validate, guarded_getattr
math.__allow_access_to_unprotected_subobjects__ = 1 random.__allow_access_to_unprotected_subobjects__ = 1 # Mark some unprotected module attributes as private, these should not be # used in untrusted Python code such as Scripts (Python) string_modsec = ModuleSecurityInfo('string') for name in ('Formatter', 'Template')...
def testAccessToSimpleContainer(self): c.attr = PublicMethod() self.assertPolicyAllows(c, 'attr') def testUnicodeAttributeLookups(self): item = self.item r_item = self.a.r_item
def testAccessToSimpleContainer(self): c.attr = PublicMethod() self.assertPolicyAllows(c, 'attr') def testAccessToStringModule(self): # The string module is available to restricted code and its members are # explicitly allowed via a # ``__allow_access_to_unprotected_subobjec...
def authenticate(self, context, auth=None): if not user_ref.get('enabled', True): LOG.warning('User %s is disabled' % user_id) raise exception.Unauthorized() except AssertionError as e: raise exception.Unauthorized(e.message)
def authenticate(self, context, auth=None): if not user_ref.get('enabled', True): LOG.warning('User %s is disabled' % user_id) raise exception.Unauthorized() # If the tenant is disabled don't allow them to authenticate if tenant_re...
def authenticate(self, context, auth=None): tenant_ref = self.identity_api.get_tenant(context=context, tenant_id=tenant_id) if tenant_ref: metadata_ref = self.identity_api.get_metadata( context=context...
def authenticate(self, context, auth=None): tenant_ref = self.identity_api.get_tenant(context=context, tenant_id=tenant_id) # If the tenant is disabled don't allow them to authenticate if tenant_ref and not tenant_ref.get('enabl...
def test_authenticate_no_username(self): self.get_client, user_ref) # FIXME(ja): this test should require the "keystone:admin" roled # (probably the role set via --keystone_admin_role flag) # FIXME(ja): add a test that admin endpoint is only se...
def test_authenticate_no_username(self): self.get_client, user_ref) def test_authenticate_disabled_tenant(self): from keystoneclient import exceptions as client_exceptions admin_client = self.get_client(admin=True) tenant = { ...
def do_setup(): 'gunicorn>=19.5.0, <20.0', 'iso8601>=0.1.12', 'json-merge-patch==0.2', 'jinja2>=2.7.3, <=2.10.0', 'markdown>=2.5.2, <3.0', 'pandas>=0.17.1, <1.0.0', 'pendulum==1.4.4',
def do_setup(): 'gunicorn>=19.5.0, <20.0', 'iso8601>=0.1.12', 'json-merge-patch==0.2', 'jinja2>=2.10.1, <2.11.0', 'markdown>=2.5.2, <3.0', 'pandas>=0.17.1, <1.0.0', 'pendulum==1.4.4',
class HTTP1Connection(httputil.HTTPConnection): if content_length is not None: return self._read_fixed_body(content_length, delegate) if headers.get("Transfer-Encoding") == "chunked": return self._read_chunked_body(delegate) if self.is_client: return self._re...
class HTTP1Connection(httputil.HTTPConnection): if content_length is not None: return self._read_fixed_body(content_length, delegate) if headers.get("Transfer-Encoding", "").lower() == "chunked": return self._read_chunked_body(delegate) if self.is_client: ret...
foo= bar 0 """.replace(b"\n", b"\r\n")) read_stream_body(self.stream, self.stop) headers, response = self.wait()
foo= bar 0 """.replace(b"\n", b"\r\n")) read_stream_body(self.stream, self.stop) headers, response = self.wait() self.assertEqual(json_decode(response), {u'foo': [u'bar']}) def test_chunked_request_uppercase(self): # As per RFC 2616 section 3.6, "Transfer-Encoding" header's value i...
class Block(PandasObject): mask = missing.mask_missing(values, to_replace) if not mask.any(): if inplace: return [self] return [self.copy()] try: blocks = self.putmask(mask, value, inplace=inplace) # Note: it is _not_ the case th...
class Block(PandasObject): mask = missing.mask_missing(values, to_replace) try: blocks = self.putmask(mask, value, inplace=inplace) # Note: it is _not_ the case that self._can_hold_element(value)
class TestDataFrameReplace: ) with pytest.raises(TypeError, match=msg): df.replace(lambda x: x.strip())
class TestDataFrameReplace: ) with pytest.raises(TypeError, match=msg): df.replace(lambda x: x.strip()) @pytest.mark.parametrize("dtype", ["float", "float64", "int64", "Int64", "boolean"]) @pytest.mark.parametrize("value", [np.nan, pd.NA]) def test_replace_no_replacement_dtypes(...
class TestUtil(unittest.TestCase): self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214') self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011') self.assertEqual(unified_strdate('1968-12-10'), '19681210') def test_find_xpath_attr(self): testxml = '''<root>
class TestUtil(unittest.TestCase): self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214') self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011') self.assertEqual(unified_strdate('1968-12-10'), '19681210') self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0...
class ArteTVPlus7IE(InfoExtractor): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] info_dict = { 'id': player_info['VID'], 'title': player_info['VTI'], 'description': player_info.get('VDE'), 'upload_date': uni...
class ArteTVPlus7IE(InfoExtractor): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str = player_info.get('VDA', '').split(' ')[0] info_dict = ...
def unified_strdate(date_str): '%d/%m/%Y', '%d/%m/%y', '%Y/%m/%d %H:%M:%S', '%Y-%m-%d %H:%M:%S', '%d.%m.%Y %H:%M', '%d.%m.%Y %H.%M',
def unified_strdate(date_str): '%d/%m/%Y', '%d/%m/%y', '%Y/%m/%d %H:%M:%S', '%d/%m/%Y %H:%M:%S', '%Y-%m-%d %H:%M:%S', '%d.%m.%Y %H:%M', '%d.%m.%Y %H.%M',
class TestYoutubeDL(unittest.TestCase): 'ext': 'mp4', 'width': None, 'height': 1080, } def fname(templ):
class TestYoutubeDL(unittest.TestCase): 'ext': 'mp4', 'width': None, 'height': 1080, 'title1': '$PATH', 'title2': '%PATH%', } def fname(templ):
class TestYoutubeDL(unittest.TestCase): self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4') self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4') self.assertEqual(fname('%(height) 0 6d.%(ext)s'), ' 01080.mp4') self.assertEqual(fname('%%(height)06d.%(ext)s'), '%(...
class TestYoutubeDL(unittest.TestCase): self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4') self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4') self.assertEqual(fname('%(height) 0 6d.%(ext)s'), ' 01080.mp4') self.assertEqual(fname('%%'), '%') self.asse...
import re import shutil import subprocess import socket import sys import time import tokenize
import re import shutil import subprocess import socket import string import sys import time import tokenize