buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class AnsibleModule(object): print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e)) sys.exit(1) # Save parameter values that should never be logged self.no_log_values = set() self._handle_no_log_values() # check the locale as set by the curr...
class AnsibleModule(object): print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e)) sys.exit(1) self._handle_no_log_values() # check the locale as set by the current environment, and reset to
class AnsibleModule(object): param = self.params for (k, v) in spec.items(): default = v.get('default', None) if pre is True: # this prevents setting defaults on required items if default is not None and k not in param: para...
class AnsibleModule(object): param = self.params for (k, v) in spec.items(): default = v.get('default', None) # This prevents setting defaults on required items on the 1st run, # otherwise will set things without a default to None on the 2nd. if k not...
class AnsibleModule(object): else: fallback_args = item try: param[k] = fallback_strategy(*fallback_args, **fallback_kwargs) except AnsibleFallbackNotFound: continue def _load_params(self): '...
class AnsibleModule(object): else: fallback_args = item try: fallback_value = fallback_strategy(*fallback_args, **fallback_kwargs) except AnsibleFallbackNotFound: continue else: ...
def test_mapping_file(self): self._test_mapping_file_plain() def _test_mapping_file_plain(self): unichrs = lambda s: ''.join(map(chr, map(eval, s.split('+')))) urt_wa = {} with self.open_mapping_file() as f: for line in f: if not line: ...
def test_mapping_file(self): self._test_mapping_file_plain() def _test_mapping_file_plain(self): def unichrs(s): return ''.join(chr(int(x, 16)) for x in s.split('+')) urt_wa = {} with self.open_mapping_file() as f: for line in f: if not ...
def main(): 'error message') parser.add_argument('--log-file', default='/tmp/{prog_name}.log'.format( prog_name=prog_name), help='log file pathname')
def main(): 'error message') parser.add_argument('--log-file', default='{prog_name}.log'.format( prog_name=prog_name), help='log file pathname')
def _normalize(table, normalize, margins, margins_name="All"): table = table.fillna(0) elif margins is True: column_margin = table.loc[:, margins_name].drop(margins_name) index_margin = table.loc[margins_name, :].drop(margins_name) table = table.drop(margins_name, axis=1).drop(marg...
def _normalize(table, normalize, margins, margins_name="All"): table = table.fillna(0) elif margins is True: # keep index and column of pivoted table table_index = table.index table_columns = table.columns # check if margin name is in (for MI cases) or equal to last ...
def _normalize(table, normalize, margins, margins_name="All"): column_margin = column_margin / column_margin.sum() table = concat([table, column_margin], axis=1) table = table.fillna(0) elif normalize == "index": index_margin = index_margin / index_margin.sum() ...
def _normalize(table, normalize, margins, margins_name="All"): column_margin = column_margin / column_margin.sum() table = concat([table, column_margin], axis=1) table = table.fillna(0) table.columns = table_columns elif normalize == "index": index_ma...
def _normalize(table, normalize, margins, margins_name="All"): table = table.append(index_margin) table = table.fillna(0) else: raise ValueError("Not a valid normalize argument") table.index.names = table_index_names table.columns.names = table_columns_name...
def _normalize(table, normalize, margins, margins_name="All"): table = table.append(index_margin) table = table.fillna(0) table.index = table_index table.columns = table_columns else: raise ValueError("Not a valid normalize argument") else: ...
class TestCrosstab: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], index=e_idx, columns=e_columns ) tm.assert_frame_equal(result, expected)
class TestCrosstab: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], index=e_idx, columns=e_columns ) tm.assert_frame_equal(result, expected) def test_margin_normalize(self): # GH 27500 df = pd.DataFrame( { "A": ["foo", "foo", "foo", "foo", "foo", "bar", "b...
import sys # Import 3rd-party libs import jinja2 import jinja2.ext from salt.ext import six if sys.version_info[:2] >= (3, 5):
import sys # Import 3rd-party libs import jinja2 import jinja2.ext import jinja2.sandbox from salt.ext import six if sys.version_info[:2] >= (3, 5):
def render_jinja_tmpl(tmplstr, context, tmplpath=None): opt_jinja_env_helper(opt_jinja_env, 'jinja_env') if opts.get('allow_undefined', False): jinja_env = jinja2.Environment(**env_args) else: jinja_env = jinja2.Environment(undefined=jinja2.StrictUndefined, ...
def render_jinja_tmpl(tmplstr, context, tmplpath=None): opt_jinja_env_helper(opt_jinja_env, 'jinja_env') if opts.get('allow_undefined', False): jinja_env = jinja2.sandbox.SandboxedEnvironment(**env_args) else: jinja_env = jinja2.sandbox.SandboxedEnvironment(undefined=jinja2.StrictUndefi...
def render_jinja_tmpl(tmplstr, context, tmplpath=None): exc, out), buf=tmplstr) except (jinja2.exceptions.TemplateRuntimeError, jinja2.exceptions.TemplateSyntaxError) as exc: trace = traceback.extract_tb(sys.exc_info()[2]) line, out = _get_jinja_error(trace, c...
def render_jinja_tmpl(tmplstr, context, tmplpath=None): exc, out), buf=tmplstr) except (jinja2.exceptions.TemplateRuntimeError, jinja2.exceptions.TemplateSyntaxError, jinja2.exceptions.SecurityError) as exc: trace = traceback.extract_tb(sys.exc_info()[2]) ...
from __future__ import absolute_import, print_function, unicode_literals import os import sys import logging # Import Salt libs import salt.utils.templates
from __future__ import absolute_import, print_function, unicode_literals import os import sys import logging import pytest # Import Salt libs import salt.utils.templates
class RenderTestCase(TestCase): res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx) self.assertEqual(res.strip(), 'OK') class MockRender(object): def __call__(self, tplstr, context, tmplpath=None):
class RenderTestCase(TestCase): res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx) self.assertEqual(res.strip(), 'OK') def test_render_jinja_cve_2021_25283(self): tmpl = '''{{ [].__class__ }}''' ctx = dict(self.context) ctx['var'] = 'OK' with pytest.raises(sal...
else: from twisted.internet import defer, reactor, ssl logger = logging.getLogger(__name__)
else: from twisted.internet import defer, reactor, ssl from .utils.misc import arg_to_iter logger = logging.getLogger(__name__)
class MailSender(object): msg = MIMEMultipart() else: msg = MIMENonMultipart(*mimetype.split('/', 1)) msg['From'] = self.mailfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True)
class MailSender(object): msg = MIMEMultipart() else: msg = MIMENonMultipart(*mimetype.split('/', 1)) to = list(arg_to_iter(to)) cc = list(arg_to_iter(cc)) msg['From'] = self.mailfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(local...
class MailSenderTest(unittest.TestCase): def test_send(self): mailsender = MailSender(debug=True) mailsender.send(to=['test@scrapy.org'], subject='subject', body='body', _callback=self._catch_mail_sent) assert self.catched_msg
class MailSenderTest(unittest.TestCase): def test_send(self): mailsender = MailSender(debug=True) mailsender.send(to=['test@scrapy.org'], subject='subject', body='body', _callback=self._catch_mail_sent) assert self.catched_msg
class MailSenderTest(unittest.TestCase): self.assertEqual(msg.get_payload(), 'body') self.assertEqual(msg.get('Content-Type'), 'text/plain') def test_send_html(self): mailsender = MailSender(debug=True) mailsender.send(to=['test@scrapy.org'], subject='subject', body='<p>body</p>', m...
class MailSenderTest(unittest.TestCase): self.assertEqual(msg.get_payload(), 'body') self.assertEqual(msg.get('Content-Type'), 'text/plain') def test_send_single_values_to_and_cc(self): mailsender = MailSender(debug=True) mailsender.send(to='test@scrapy.org', subject='subject', body...
class MailSenderTest(unittest.TestCase): mailsender = MailSender(debug=True) mailsender.send(to=['test@scrapy.org'], subject=subject, body=body, attachs=attachs, charset='utf-8', _callback=self._catch_mail_sent) assert self.catched_msg self.assertEqual(self.catc...
class MailSenderTest(unittest.TestCase): mailsender = MailSender(debug=True) mailsender.send(to=['test@scrapy.org'], subject=subject, body=body, attachs=attachs, charset='utf-8', _callback=self._catch_mail_sent) assert self.catched_msg se...
class MailSenderTest(unittest.TestCase): msg = self.catched_msg['msg'] self.assertEqual(msg['subject'], subject) self.assertEqual(msg.get_charset(), Charset('utf-8')) self.assertEqual(msg.get('Content-Type'), 'multipart/mixed; charset="utf-8"') payload = msg.get_payload() ...
class MailSenderTest(unittest.TestCase): msg = self.catched_msg['msg'] self.assertEqual(msg['subject'], subject) self.assertEqual(msg.get_charset(), Charset('utf-8')) self.assertEqual(msg.get('Content-Type'), 'multipart/mixed; charset="utf-8"') payload =...
import time from django.conf import settings from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.utils.functional import cached_property from django.utils.six.moves import input TEST_DATABASE_PREFIX = 'test_' PASSWORD = 'Im_a_lumberjack' class Datab...
import time from django.conf import settings from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.utils.crypto import get_random_string from django.utils.functional import cached_property from django.utils.six.moves import input TEST_DATABASE_PREFIX = ...
class DatabaseCreation(BaseDatabaseCreation): ] # Ignore "user already exists" error when keepdb is on acceptable_ora_err = 'ORA-01920' if keepdb else None self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err) # Most test-suites can be...
class DatabaseCreation(BaseDatabaseCreation): ] # Ignore "user already exists" error when keepdb is on acceptable_ora_err = 'ORA-01920' if keepdb else None success = self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err) # If the passwo...
class DatabaseCreation(BaseDatabaseCreation): """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, default) if val is None: val = TEST_DATABASE_PREFIX + settings_dict[prefixed] return val
class DatabaseCreation(BaseDatabaseCreation): """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, default) if val is None and prefixed: val = TEST_DATABASE_PREFIX + settings_dict[prefixed] return val
class DatabaseCreation(BaseDatabaseCreation): return self._test_settings_get('USER', prefixed='USER') def _test_database_passwd(self): return self._test_settings_get('PASSWORD', default=PASSWORD) def _test_database_tblspace(self): return self._test_settings_get('TBLSPACE', prefixed='US...
class DatabaseCreation(BaseDatabaseCreation): return self._test_settings_get('USER', prefixed='USER') def _test_database_passwd(self): password = self._test_settings_get('PASSWORD') if password is None and self._test_user_create(): # Oracle passwords are limited to 30 chars and ...
See documentation in docs/topics/downloader-middleware.rst """ from w3lib.http import basic_auth_header from scrapy import signals class HttpAuthMiddleware(object):
See documentation in docs/topics/downloader-middleware.rst """ import warnings from w3lib.http import basic_auth_header from scrapy import signals from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.url import url_is_from_any_domain class HttpAu...
def spider_opened(self, spider): pwd = getattr(spider, 'http_pass', '') if usr or pwd: self.auth = basic_auth_header(usr, pwd) def process_request(self, request, spider): auth = getattr(self, 'auth', None) if auth and b'Authorization' not in request.headers: ...
def spider_opened(self, spider): pwd = getattr(spider, 'http_pass', '') if usr or pwd: self.auth = basic_auth_header(usr, pwd) if not hasattr(spider, 'http_auth_domain'): warnings.warn('Using HttpAuthMiddleware without http_auth_domain is deprecated and can cause ...
import unittest from scrapy.http import Request from scrapy.downloadermiddlewares.httpauth import HttpAuthMiddleware from scrapy.spiders import Spider class TestSpider(Spider): http_user = 'foo' http_pass = 'bar' class HttpAuthMiddlewareTest(unittest.TestCase):
import unittest from w3lib.http import basic_auth_header from scrapy.http import Request from scrapy.downloadermiddlewares.httpauth import HttpAuthMiddleware from scrapy.spiders import Spider class TestSpiderLegacy(Spider): http_user = 'foo' http_pass = 'bar' class TestSpider(Spider): http_user = 'foo...
def setUp(self): def tearDown(self): del self.mw def test_auth(self): req = Request('http://scrapytest.org/') assert self.mw.process_request(req, self.spider) is None self.assertEqual(req.headers['Authorization'], b'Basic Zm9vOmJhcg==') def test_auth_already_set(self): ...
def setUp(self): def tearDown(self): del self.mw def test_no_auth(self): req = Request('http://example-noauth.com/') assert self.mw.process_request(req, self.spider) is None self.assertNotIn('Authorization', req.headers) def test_auth_domain(self): req = Request('ht...
from warnings import warn from lxml import etree from lxml.etree import QName, XMLParser, XMLSyntaxError, parse from .. import Name, Stream, String from .. import __version__ as pikepdf_version if sys.version_info < (3, 9): # pragma: no cover from typing import Iterable, MutableMapping
from warnings import warn from lxml import etree from lxml.etree import QName, XMLSyntaxError from .. import Name, Stream, String from .. import __version__ as pikepdf_version from .._xml import parse_xml if sys.version_info < (3, 9): # pragma: no cover from typing import Iterable, MutableMapping
def _load_from(self, data: bytes) -> None: data = XMP_EMPTY # on some platforms lxml chokes on empty documents def basic_parser(xml): return parse(BytesIO(xml)) def strip_illegal_bytes_parser(xml): return parse(BytesIO(re_xml_illegal_bytes.sub(b'', xml))) ...
def _load_from(self, data: bytes) -> None: data = XMP_EMPTY # on some platforms lxml chokes on empty documents def basic_parser(xml): return parse_xml(BytesIO(xml)) def strip_illegal_bytes_parser(xml): return parse_xml(BytesIO(re_xml_illegal_bytes.sub(b'', xml))) ...
def test_exception_undoes_edits(graph): raise m = graph.open_metadata() assert m['dc:format'] != 'application/pdf-demo'
def test_exception_undoes_edits(graph): raise m = graph.open_metadata() assert m['dc:format'] != 'application/pdf-demo' def test_xxe(trivial, outdir): secret = outdir / 'secret.txt' secret.write_text("This is a secret") trivial.Root.Metadata = Stream( trivial, b...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S) re_chars = re.compile(r'<.*?>|(.)', re.S) re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(((?<=[a-z])[A-...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.S) re_chars = re.compile(r'<.*?>|(.)', re.S) re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(((?<=[a-z])[A-Z...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) def test_wrap(self): digits = '1234 67 9' self.assertEqual(text.wrap(digits, 100), '1234 67 9'...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) re_tag_catastrophic_test = ('</a' + '\t' * 50000) + '//>' truncator = text.Truncator(re_tag_catast...
ssl = None import sys import tempfile from nturl2path import url2pathname, pathname2url from base64 import b64encode
ssl = None import sys import tempfile import warnings from nturl2path import url2pathname, pathname2url from base64 import b64encode
def open_spam(self, url): "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") # Just commented them out. # Can't really tell why keep failing in windows and sparc. # Everywhere else they work ok, but on those machines, sometimes
def open_spam(self, url): "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"), "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/") def test_local_file_open(self): # bpo-35907, CVE-2019-9948: urllib must reject local_file:// scheme class DummyURLopener(urllib.request.URLopener): ...
def open(self, fullurl, data=None): name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name): if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else:
def open(self, fullurl, data=None): name = 'open_' + urltype self.type = urltype name = name.replace('-', '_') if not hasattr(self, name) or name == 'open_local_file': if proxy: return self.open_unknown_proxy(proxy, fullurl, data) else:
def find_hook(hook_name, hooks_dir='hooks'): logger.debug('No hooks/dir in template_dir') return None for hook_file in os.listdir(hooks_dir): if valid_hook(hook_file, hook_name): return os.path.abspath(os.path.join(hooks_dir, hook_file)) return None def run_script(script_...
def find_hook(hook_name, hooks_dir='hooks'): logger.debug('No hooks/dir in template_dir') return None scripts = [] for hook_file in os.listdir(hooks_dir): if valid_hook(hook_file, hook_name): scripts.append(os.path.abspath(os.path.join(hooks_dir, hook_file))) if len(scr...
def run_hook(hook_name, project_dir, context): :param project_dir: The directory to execute the script from. :param context: Cookiecutter project context. """ script = find_hook(hook_name) if script is None: logger.debug('No %s hook found', hook_name) return logger.debug('Running...
def run_hook(hook_name, project_dir, context): :param project_dir: The directory to execute the script from. :param context: Cookiecutter project context. """ scripts = find_hook(hook_name) if not scripts: logger.debug('No %s hook found', hook_name) return logger.debug('Running h...
import pytest from cookiecutter import hooks, utils, exceptions def make_test_repo(name): """Create test repository for test setup methods.""" hook_dir = os.path.join(name, 'hooks') template = os.path.join(name, 'input{{hooks}}')
import pytest from cookiecutter import hooks, utils, exceptions def make_test_repo(name, multiple_hooks=False): """Create test repository for test setup methods.""" hook_dir = os.path.join(name, 'hooks') template = os.path.join(name, 'input{{hooks}}')
def make_test_repo(name): # Set the execute bit os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR) return post
def make_test_repo(name): # Set the execute bit os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR) # Adding an additional pre script if multiple_hooks: if sys.platform.startswith('win'): pre = 'pre_gen_project.bat' with open(os.path.join(hook_dir, pre),...
class TestFindHooks(object): with utils.work_in(self.repo_path): expected_pre = os.path.abspath('hooks/pre_gen_project.py') actual_hook_path = hooks.find_hook('pre_gen_project') assert expected_pre == actual_hook_path expected_post = os.path.abspath('hooks/{}'.fo...
class TestFindHooks(object): with utils.work_in(self.repo_path): expected_pre = os.path.abspath('hooks/pre_gen_project.py') actual_hook_path = hooks.find_hook('pre_gen_project') assert expected_pre == actual_hook_path[0] expected_post = os.path.abspath('hooks/{}'...
class TestExternalHooks(object): def setup_method(self, method): """External hooks related tests setup fixture.""" self.post_hook = make_test_repo(self.repo_path) def teardown_method(self, method): """External hooks related tests teardown fixture."""
class TestExternalHooks(object): def setup_method(self, method): """External hooks related tests setup fixture.""" self.post_hook = make_test_repo(self.repo_path, multiple_hooks=True) def teardown_method(self, method): """External hooks related tests teardown fixture."""
class TestExternalHooks(object): os.remove('python_pre.txt') if os.path.exists('shell_post.txt'): os.remove('shell_post.txt') if os.path.exists('tests/shell_post.txt'): os.remove('tests/shell_post.txt') if os.path.exists('tests/test-hooks/input{{hooks}}/python...
class TestExternalHooks(object): os.remove('python_pre.txt') if os.path.exists('shell_post.txt'): os.remove('shell_post.txt') if os.path.exists('shell_pre.txt'): os.remove('shell_pre.txt') if os.path.exists('tests/shell_post.txt'): os.remove('tests...
class TestExternalHooks(object): with utils.work_in(self.repo_path): hooks.run_hook('pre_gen_project', tests_dir, {}) assert os.path.isfile(os.path.join(tests_dir, 'python_pre.txt')) hooks.run_hook('post_gen_project', tests_dir, {}) assert os.path.isfile(os.path....
class TestExternalHooks(object): with utils.work_in(self.repo_path): hooks.run_hook('pre_gen_project', tests_dir, {}) assert os.path.isfile(os.path.join(tests_dir, 'python_pre.txt')) assert os.path.isfile(os.path.join(tests_dir, 'shell_pre.txt')) hooks.run_hook('...
def interpolate_1d( inds = lib.maybe_convert_objects(inds) else: inds = xvalues result[invalid] = np.interp(inds[invalid], inds[valid], yvalues[valid]) result[preserve_nans] = np.nan return result
def interpolate_1d( inds = lib.maybe_convert_objects(inds) else: inds = xvalues # np.interp requires sorted X values, #21037 indexer = np.argsort(inds[valid]) result[invalid] = np.interp( inds[invalid], inds[valid][indexer], yvalues[valid][indexer]...
class TestSeriesInterpolateData: pytest.skip( "This interpolation method is not supported for Timedelta Index yet." )
class TestSeriesInterpolateData: pytest.skip( "This interpolation method is not supported for Timedelta Index yet." ) @pytest.mark.parametrize( "ascending, expected_values", [(True, [1, 2, 3, 9, 10]), (False, [10, 9, 3, 2, 1])], ) def test_interpolate...
import time from django.conf import settings from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.utils.six.moves import input TEST_DATABASE_PREFIX = 'test_' PASSWORD = 'Im_a_lumberjack' class DatabaseCreation(BaseDatabaseCreation):
import time from django.conf import settings from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.utils.crypto import get_random_string from django.utils.six.moves import input TEST_DATABASE_PREFIX = 'test_' class DatabaseCreation(BaseDatabaseCreatio...
class DatabaseCreation(BaseDatabaseCreation): ] # Ignore "user already exists" error when keepdb is on acceptable_ora_err = 'ORA-01920' if keepdb else None self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err) # Most test-suites can be...
class DatabaseCreation(BaseDatabaseCreation): ] # Ignore "user already exists" error when keepdb is on acceptable_ora_err = 'ORA-01920' if keepdb else None success = self._execute_allow_fail_statements(cursor, statements, parameters, verbosity, acceptable_ora_err) # If the passwo...
class DatabaseCreation(BaseDatabaseCreation): """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, default) if val is None: val = TEST_DATABASE_PREFIX + settings_dict[prefixed] return val
class DatabaseCreation(BaseDatabaseCreation): """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(key, default) if val is None and prefixed: val = TEST_DATABASE_PREFIX + settings_dict[prefixed] return val
class DatabaseCreation(BaseDatabaseCreation): return self._test_settings_get('USER', prefixed='USER') def _test_database_passwd(self): return self._test_settings_get('PASSWORD', default=PASSWORD) def _test_database_tblspace(self): return self._test_settings_get('TBLSPACE', prefixed='US...
class DatabaseCreation(BaseDatabaseCreation): return self._test_settings_get('USER', prefixed='USER') def _test_database_passwd(self): password = self._test_settings_get('PASSWORD') if password is None and self._test_user_create(): # Oracle passwords are limited to 30 chars and ...
def _get_empty_dtype_and_na(join_units): dtype = upcast_classes["datetimetz"] return dtype[0], tslibs.NaT elif "datetime" in upcast_classes: return np.dtype("M8[ns]"), tslibs.iNaT elif "timedelta" in upcast_classes: return np.dtype("m8[ns]"), np.timedelta64("NaT", "ns") else:...
def _get_empty_dtype_and_na(join_units): dtype = upcast_classes["datetimetz"] return dtype[0], tslibs.NaT elif "datetime" in upcast_classes: return np.dtype("M8[ns]"), np.datetime64("NaT", "ns") elif "timedelta" in upcast_classes: return np.dtype("m8[ns]"), np.timedelta64("NaT", ...
def test_merge_multiindex_columns(): expected["id"] = "" tm.assert_frame_equal(result, expected)
def test_merge_multiindex_columns(): expected["id"] = "" tm.assert_frame_equal(result, expected) def test_merge_datetime_upcast_dtype(): # https://github.com/pandas-dev/pandas/issues/31208 df1 = pd.DataFrame({"x": ["a", "b", "c"], "y": ["1", "2", "4"]}) df2 = pd.DataFrame( {"y": ["1", "2"...
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command(script='vagrant ssh', stderr='VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine.'), 'vagrant up && vagrant ssh'), (Command(script='vagrant ssh devbox', stderr='VM must be running t...
def test_not_match(command): @pytest.mark.parametrize('command, new_command', [ (Command(script='vagrant ssh', stderr='VM must be running to open SSH connection. Run `vagrant up`\nto start the virtual machine.'), 'vagrant up && vagrant ssh'), (Command(script='vagrant ssh devbox', stderr='VM must be running to...
def match(command, settings): def get_new_command(command, settings): cmds = command.script.split(' ') machine = "" if len(cmds) >= 3: machine = cmds[2] return shells.and_("vagrant up " + machine, command.script)
def match(command, settings): def get_new_command(command, settings): cmds = command.script.split(' ') machine = None if len(cmds) >= 3: machine = cmds[2] startAllInstances = shells.and_("vagrant up", command.script) if machine is None: return startAllInstances else: r...
import securesystemslib.util import six import iso8601 # The Timestamp role does not have signed metadata about it; otherwise we # would need an infinite regress of metadata. Therefore, we use some
import securesystemslib.util import six import iso8601 import requests.exceptions # The Timestamp role does not have signed metadata about it; otherwise we # would need an infinite regress of metadata. Therefore, we use some
def _update_root_metadata(self, current_root_metadata): None. """ # Retrieve the latest, remote root.json. latest_root_metadata_file = self._get_metadata_file( 'root', 'root.json', DEFAULT_ROOT_UPPERLENGTH, None) latest_root_metadata = securesystemslib.util.load_json_string( late...
def _update_root_metadata(self, current_root_metadata): None. """ def neither_403_nor_404(mirror_error): if isinstance(mirror_error, requests.exceptions.HTTPError): if mirror_error.response.status_code in {403, 404}: return False return True # Temporarily set consistent...
# to suspend execution for a specified amount of time. See # theupdateframework/tuf/issue#338. SLEEP_BEFORE_ROUND = None
# to suspend execution for a specified amount of time. See # theupdateframework/tuf/issue#338. SLEEP_BEFORE_ROUND = None # Maximum number of root metadata file rotations we should perform in order to # prevent a denial-of-service (DoS) attack. MAX_NUMBER_ROOT_ROTATIONS = 2**5
class Rhsm(RegistrationBase): for pool_id, quantity in sorted(pool_ids.items()): if pool_id in available_pool_ids: args = [SUBMAN_CMD, 'attach', '--pool', pool_id, '--quantity', quantity] rc, stderr, stdout = self.module.run_command(args, check_rc=True) e...
class Rhsm(RegistrationBase): for pool_id, quantity in sorted(pool_ids.items()): if pool_id in available_pool_ids: args = [SUBMAN_CMD, 'attach', '--pool', pool_id] if quantity is not None: args.extend(['--quantity', to_native(quantity)]) ...
def main(): module.fail_json(msg='Unable to parse pool_ids option.') pool_id, quantity = list(value.items())[0] else: pool_id, quantity = value, 1 pool_ids[pool_id] = str(quantity) consumer_type = module.params["consumer_type"] consumer_name = module.param...
def main(): module.fail_json(msg='Unable to parse pool_ids option.') pool_id, quantity = list(value.items())[0] else: pool_id, quantity = value, None pool_ids[pool_id] = quantity consumer_type = module.params["consumer_type"] consumer_name = module.params[...
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', '--quantity', '1' ], {'check_rc': True}, ...
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6' ], {'check_rc': True}, (0, '', '')
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99747107e9', '--quantity', '1' ], {'check_rc': True}, ...
Entitlement Type: Physical [ '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99747107e9' ], {'check_rc': True}, (0, '', '')
Entitlement Type: Physical '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', '--quantity', '1' ], {'check_rc': True}, (0, ...
Entitlement Type: Physical '/testbin/subscription-manager', 'attach', '--pool', 'ff8080816b8e967f016b8e99632804a6', ], {'check_rc': True}, (0, '', '')
class TestSortedCorrectedCommandsSequence(object): assert set(seq) == {CorrectedCommand('ls', priority=100), CorrectedCommand('ls', side_effect, 300)} class TestCorrectedCommand(object):
class TestSortedCorrectedCommandsSequence(object): assert set(seq) == {CorrectedCommand('ls', priority=100), CorrectedCommand('ls', side_effect, 300)} def test_with_blank(self, settings): seq = SortedCorrectedCommandsSequence(iter([]), settings) assert list(seq) ...
class SortedCorrectedCommandsSequence(object): def _realise(self): """Realises generator, removes duplicates and sorts commands.""" commands = self._remove_duplicates(self._commands) self._cached = [self._cached[0]] + sorted( commands, key=lambda corrected_command: corrected_com...
class SortedCorrectedCommandsSequence(object): def _realise(self): """Realises generator, removes duplicates and sorts commands.""" if self._cached: commands = self._remove_duplicates(self._commands) self._cached = [self._cached[0]] + sorted( commands, key=la...
from PyQt5 import QtGui from PyQt5 import QtWidgets from electrum import util if platform.system() == 'Windows':
from PyQt5 import QtGui from PyQt5 import QtWidgets from electrum import util from electrum.i18n import _ if platform.system() == 'Windows':
MONOSPACE_FONT = 'monospace' class Console(QtWidgets.QPlainTextEdit): def __init__(self, prompt='>> ', startup_message='', parent=None): QtWidgets.QPlainTextEdit.__init__(self, parent)
MONOSPACE_FONT = 'monospace' class OverlayLabel(QtWidgets.QLabel): STYLESHEET = ''' QLabel, QLabel link { color: rgb(0, 0, 0); background-color: rgb(248, 240, 200); border: 1px solid; border-color: rgb(255, 114, 47); padding: 2px; } ''' def __init__(self...
def __init__(self, prompt='>> ', startup_message='', parent=None): self.updateNamespace({'run':self.run_script}) self.set_json(False) def set_json(self, b): self.is_json = b
def __init__(self, prompt='>> ', startup_message='', parent=None): self.updateNamespace({'run':self.run_script}) self.set_json(False) warning_text = "<h1>{}</h1><br>{}<br><br>{}".format( _("Warning!"), _("Do not paste code here that you don't understand. Executing the wr...
class DatabaseOperations(BaseDatabaseOperations): return f"EXTRACT({lookup_type} FROM {sql})", params def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_field_to_tz(sql, params, tzname) fields = { "year": "%Y-01-01", "mon...
class DatabaseOperations(BaseDatabaseOperations): return f"EXTRACT({lookup_type} FROM {sql})", params def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) fields = { "year": "%Y-01-01", "month...
class DatabaseOperations(BaseDatabaseOperations): tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_field_to_tz(self, sql, params, tzname): if tzname and settings.USE_TZ and self.connection.timezone_name != tzname: retu...
class DatabaseOperations(BaseDatabaseOperations): tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_sql_to_tz(self, sql, params, tzname): if tzname and settings.USE_TZ and self.connection.timezone_name != tzname: return...
class DatabaseOperations(BaseDatabaseOperations): return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_field_to_tz(sql, params, tzname) return f"DATE({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): sql, par...
class DatabaseOperations(BaseDatabaseOperations): return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"DATE({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): sql, param...
class DatabaseOperations(BaseDatabaseOperations): return sql, params def time_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_field_to_tz(sql, params, tzname) fields = { "hour": "%H:00:00", "minute": "%H:%i:00",
class DatabaseOperations(BaseDatabaseOperations): return sql, params def time_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) fields = { "hour": "%H:00:00", "minute": "%H:%i:00",
END; return extract_sql, (*params, extract_param) def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_field_to_tz(sql, params, tzname) # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html t...
END; return extract_sql, (*params, extract_param) def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) # https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROUND-and-TRUNC-Date-Functions.html tru...
END; tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_field_to_tz(self, sql, params, tzname): if not (settings.USE_TZ and tzname): return sql, params if not self._tzname_re.match(tzname):
END; tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_sql_to_tz(self, sql, params, tzname): if not (settings.USE_TZ and tzname): return sql, params if not self._tzname_re.match(tzname):
END; return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_field_to_tz(sql, params, tzname) return f"TRUNC({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): # Since `TimeField` values are stored as TIMESTAMP c...
END; return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"TRUNC({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): # Since `TimeField` values are stored as TIMESTAMP cha...
END; ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_field_to_tz(sql, params, tzname) return self.date_extract_sql(lookup_type, sql, params) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): sql, params = self._conve...
END; ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return self.date_extract_sql(lookup_type, sql, params) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert...
END; # The implementation is similar to `datetime_trunc_sql` as both # `DateTimeField` and `TimeField` are stored as TIMESTAMP where # the date part of the later is ignored. sql, params = self._convert_field_to_tz(sql, params, tzname) trunc_param = None if lookup_type == ...
END; # The implementation is similar to `datetime_trunc_sql` as both # `DateTimeField` and `TimeField` are stored as TIMESTAMP where # the date part of the later is ignored. sql, params = self._convert_sql_to_tz(sql, params, tzname) trunc_param = None if lookup_type == "h...
def target_version_option_callback( @click.option( "--config", type=click.Path( exists=False, file_okay=True, dir_okay=False, readable=True, allow_dash=False ), is_eager=True, callback=read_pyproject_toml,
def target_version_option_callback( @click.option( "--config", type=click.Path( exists=True, file_okay=True, dir_okay=False, readable=True, allow_dash=False ), is_eager=True, callback=read_pyproject_toml,
class BlackTestCase(unittest.TestCase): raise result.exception self.assertEqual(result.exit_code, 0) class BlackDTestCase(AioHTTPTestCase): async def get_application(self) -> web.Application:
class BlackTestCase(unittest.TestCase): raise result.exception self.assertEqual(result.exit_code, 0) def test_invalid_config_return_code(self) -> None: tmp_file = Path(black.dump_to_file()) try: tmp_config = Path(black.dump_to_file()) tmp_config.u...
class TestUtil(unittest.TestCase): unified_strdate('2/2/2015 6:47:40 PM', day_first=False), '20150202') self.assertEqual(unified_strdate('25-09-2014'), '20140925') def test_find_xpath_attr(self): testxml = '''<root>
class TestUtil(unittest.TestCase): unified_strdate('2/2/2015 6:47:40 PM', day_first=False), '20150202') self.assertEqual(unified_strdate('25-09-2014'), '20140925') self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None) def test_find_xpath_attr(self): testxml ...
def unified_strdate(date_str, day_first=True): timetuple = email.utils.parsedate_tz(date_str) if timetuple: upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d') return compat_str(upload_date) def determine_ext(url, default_ext='unknown_video'):
def unified_strdate(date_str, day_first=True): timetuple = email.utils.parsedate_tz(date_str) if timetuple: upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d') if upload_date is not None: return compat_str(upload_date) def determine_ext(url, default_ext='unknown_...
def make_template_fragment_key(fragment_name: str, vary_on: List[str] = None) -> return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, "_".join(vary_on)) class Cache: """This class is used to control the cache objects."""
def make_template_fragment_key(fragment_name: str, vary_on: List[str] = None) -> return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, "_".join(vary_on)) def load_module( module: Union[str, Any], lookup_obj: Optional[Any] = None, return_back: bool = False ) -> Any: """Dynamic module loading. ...
def init_app(self, app: Flask, config=None) -> None: config.setdefault("CACHE_TYPE", "null") config.setdefault("CACHE_NO_NULL_WARNING", False) config.setdefault("CACHE_SOURCE_CHECK", False) if config["CACHE_TYPE"] == "null" and not config["CACHE_NO_NULL_WARNING"]: warnings.w...
def init_app(self, app: Flask, config=None) -> None: config.setdefault("CACHE_TYPE", "null") config.setdefault("CACHE_NO_NULL_WARNING", False) config.setdefault("CACHE_SOURCE_CHECK", False) config.setdefault("CACHE_SERIALIZER", "pickle") config.setdefault("CACHE_SERIALIZER_ERROR"...
def _set_cache(self, app: Flask, config) -> None: plain_name_used = False cache_factory = import_string(import_me) cache_args = config["CACHE_ARGS"][:] cache_options = {"default_timeout": config["CACHE_DEFAULT_TIMEOUT"]} if isinstance(cache_factory, type) and issubclass(cac...
def _set_cache(self, app: Flask, config) -> None: plain_name_used = False cache_factory = import_string(import_me) from . import serialization cache_args = config["CACHE_ARGS"][:] cache_options = { "default_timeout": config["CACHE_DEFAULT_TIMEOUT"], ...
def unlink(self, *args, **kwargs) -> bool: def cached( self, timeout: Optional[int] = None, key_prefix: str = "view/%s", unless: Optional[Callable] = None, forced_update: Optional[Callable] = None,
def unlink(self, *args, **kwargs) -> bool: def cached( self, timeout: Optional[int]=None, key_prefix: str = "view/%s", unless: Optional[Callable] = None, forced_update: Optional[Callable] = None,
def cached( cache_none: bool = False, make_cache_key: Optional[Callable] = None, source_check: Optional[bool] = None, ) -> Callable: """Decorator. Use this to cache a function. By default the cache key is `view/request.path`. You are able to use this decorator with any
def cached( cache_none: bool = False, make_cache_key: Optional[Callable] = None, source_check: Optional[bool] = None, force_tuple: bool = True, ) -> Callable: """Decorator. Use this to cache a function. By default the cache key is `view/request.path`. You are able to ...
def get_list(): formed with the function's source code hash in addition to other parameters that may be included in the formation of the key. """ def decorator(f):
def get_list(): formed with the function's source code hash in addition to other parameters that may be included in the formation of the key. :param force_tuple: Default True. Cast output from list to tuple. ...
def decorated_function(*args, **kwargs): found = False else: found = self.cache.has(cache_key) except Exception: if self.app.debug: raise
def decorated_function(*args, **kwargs): found = False else: found = self.cache.has(cache_key) elif force_tuple and isinstance(rv, list) and len(rv) == 2: # JSON compatibility ...
:copyright: (c) 2010 by Thadeus Burgess. :license: BSD, see LICENSE for more details. """ def iteritems_wrapper(mappingorseq):
:copyright: (c) 2010 by Thadeus Burgess. :license: BSD, see LICENSE for more details. """ import warnings from flask_caching.serialization import pickle, PickleError def iteritems_wrapper(mappingorseq):
def iteritems_wrapper(mappingorseq): return mappingorseq class BaseCache: """Baseclass for the cache systems. All the cache systems implement this API or a superset of it.
def iteritems_wrapper(mappingorseq): return mappingorseq def extract_serializer_args(data): result = dict() serializer_prefix = "serializer_" for key in tuple(data.keys()): if key.startswith(serializer_prefix): result[key] = data.pop(key) return result class BaseCache: ""...
class BaseCache: :param default_timeout: The default timeout (in seconds) that is used if no timeout is specified on :meth:`set`. A timeout of 0 indicates that the cache never expires. """ def __init__(self, default_timeout=300): self.default_...
class BaseCache: :param default_timeout: The default timeout (in seconds) that is used if no timeout is specified on :meth:`set`. A timeout of 0 indicates that the cache never expires. :param serializer_impl: Pickle-like serialization implementation. It sh...
import tempfile from time import time from flask_caching.backends.base import BaseCache try: import cPickle as pickle except ImportError: # pragma: no cover import pickle # type: ignore logger = logging.getLogger(__name__)
import tempfile from time import time from flask_caching.backends.base import BaseCache, extract_serializer_args logger = logging.getLogger(__name__)
def __init__( mode=0o600, hash_method=hashlib.md5, ignore_errors=False, ): super().__init__(default_timeout) self._path = cache_dir self._threshold = threshold self._mode = mode
def __init__( mode=0o600, hash_method=hashlib.md5, ignore_errors=False, **kwargs ): super().__init__( default_timeout, **extract_serializer_args(kwargs) ) self._path = cache_dir self._threshold = threshold self._mode = mode
def _prune(self): try: remove = False with open(fname, "rb") as f: expires = pickle.load(f) remove = (expires != 0 and expires <= now) or idx % 3 == 0 if remove: os.remove(fname)
def _prune(self): try: remove = False with open(fname, "rb") as f: expires, _ = self._serializer.load(f) remove = (expires != 0 and expires <= now) or idx % 3 == 0 if remove: os.remove(fname)
def get(self, key): filename = self._get_filename(key) try: with open(filename, "rb") as f: pickle_time = pickle.load(f) expired = pickle_time != 0 and pickle_time < time() if not expired: hit_or_miss = "hit" ...
def get(self, key): filename = self._get_filename(key) try: with open(filename, "rb") as f: data = self._serializer.load(f) if isinstance(data, int): # backward compatibility # should be removed in the next major release...
def set(self, key, value, timeout=None, mgmt_element=False): suffix=self._fs_transaction_suffix, dir=self._path ) with os.fdopen(fd, "wb") as f: pickle.dump(timeout, f, 1) pickle.dump(value, f, pickle.HIGHEST_PROTOCOL) # https://github...
def set(self, key, value, timeout=None, mgmt_element=False): suffix=self._fs_transaction_suffix, dir=self._path ) with os.fdopen(fd, "wb") as f: self._serializer.dump((timeout, value), f) # https://github.com/sh4nks/flask-caching/issues/238#issuecomme...
def has(self, key): filename = self._get_filename(key) try: with open(filename, "rb") as f: pickle_time = pickle.load(f) expired = pickle_time != 0 and pickle_time < time() if expired: self.delete(key)
def has(self, key): filename = self._get_filename(key) try: with open(filename, "rb") as f: pickle_time, _ = self._serializer.load(f) expired = pickle_time != 0 and pickle_time < time() if expired: self.delete(key)
def has(self, key): result = True except FileNotFoundError: pass except (OSError, pickle.PickleError) as exc: logger.error("get key %r -> %s", key, exc) expiredstr = "(expired)" if expired else "" logger.debug("has key %r -> %s %s", key, result, ex...
def has(self, key): result = True except FileNotFoundError: pass except (OSError, self._serialization_error) as exc: logger.error("get key %r -> %s", key, exc) expiredstr = "(expired)" if expired else "" logger.debug("has key %r -> %s %s", key, res...
""" from time import time from flask_caching.backends.base import BaseCache, iteritems_wrapper try: import cPickle as pickle except ImportError: # pragma: no cover import pickle # type: ignore _test_memcached_key = re.compile(r"[^\x00-\x21\xff]{1,250}$").match
""" from time import time from flask_caching.backends.base import ( BaseCache, extract_serializer_args, iteritems_wrapper, ) _test_memcached_key = re.compile(r"[^\x00-\x21\xff]{1,250}$").match
class MemcachedCache(BaseCache): different prefix. """ def __init__(self, servers=None, default_timeout=300, key_prefix=None): super().__init__(default_timeout) if servers is None or isinstance(servers, (list, tuple)): if servers is None: serve...
class MemcachedCache(BaseCache): different prefix. """ def __init__(self, servers=None, default_timeout=300, key_prefix=None, **kwargs): super().__init__( default_timeout, **extract_serializer_args(kwargs) ) if servers is None or isinstance(servers, (l...
def __init__( password=None, **kwargs, ): super().__init__(default_timeout=default_timeout) if servers is None: servers = ["127.0.0.1:11211"]
def __init__( password=None, **kwargs, ): super().__init__( default_timeout=default_timeout, **extract_serializer_args(kwargs) ) if servers is None: servers = ["127.0.0.1:11211"]