buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module module_args = "%s src=%s dest=%s original_basename=%s" % (module_args, pipes.quote(xfered), pipes.quote(dest), pipes.quote(os.path.basename(src))) if self.runner.no...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module new_module_args = dict( src=xfered, dest=dest, original_basename=os.path.basename(src), ) module_args_tmp...
class ActionModule(object): # src and dest here come after original and override them # we pass dest only to make sure it includes trailing slash in case of recursive copy module_args_tmp = "%s src=%s dest=%s original_basename=%s" % (module_args, ...
class ActionModule(object): # src and dest here come after original and override them # we pass dest only to make sure it includes trailing slash in case of recursive copy new_module_args = dict( src=tmp_src, dest=dest, ...
class ActionModule(object): tmp_src = tmp_path + source_rel # Build temporary module_args. module_args_tmp = "%s src=%s original_basename=%s" % (module_args, pipes.quote(tmp_src), pipes.quote(source_rel)) if self.runner.n...
class ActionModule(object): tmp_src = tmp_path + source_rel # Build temporary module_args. new_module_args = dict( src=tmp_src, dest=dest, ) if self.runner.noop_on_check(inject): ...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module module_args = "%s src=%s dest=%s original_basename=%s" % (module_args, pipes.quote(xfered), pipes.quote(dest), pipes.quote(os.path.basename(source))) if self.runner...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module new_module_args = dict( src=xfered, dest=dest, original_basename=os.path.basename(source), ) module_args_tmp...
VERBOSITY=0 MAX_FILE_SIZE_FOR_DIFF=1*1024*1024 try: import json except ImportError:
VERBOSITY=0 MAX_FILE_SIZE_FOR_DIFF=1*1024*1024 # caching the compilation of the regex used # to check for lookup calls within data LOOKUP_REGEX=re.compile(r'lookup\s*\(') try: import json except ImportError:
def json_loads(data): return json.loads(data) def _clean_data(orig_data): ''' remove template tags from a string ''' data = orig_data if isinstance(orig_data, basestring): for pattern,replacement in (('{{','{#'), ('}}','#}'), ('{%','{#'), ('%}','#}')): data = data.replace(pattern, ...
def json_loads(data): return json.loads(data) def _clean_data(orig_data, from_remote=False, from_inventory=False): ''' remove template tags from a string ''' data = orig_data if isinstance(orig_data, basestring): sub_list = [('{%','{#'), ('%}','#}')] if from_remote or (from_inventory a...
def parse_json(raw_data, from_remote=False): return { "failed" : True, "parsed" : False, "msg" : orig_data } if from_remote: results = _clean_data_struct(results) return results def smush_braces(data): ''' smush Jinaj2 braces so unresolved templates like {{ foo }} don't get parsed wei...
def parse_json(raw_data, from_remote=False): return { "failed" : True, "parsed" : False, "msg" : orig_data } if from_remote: results = _clean_data_struct(results, from_remote, from_inventory) return results def merge_module_args(current_args, new_args): ''' merges either a diction...
def parse_kv(args): for x in vargs: if "=" in x: k, v = x.split("=",1) options[k]=v return options def merge_hash(a, b):
def parse_kv(args): for x in vargs: if "=" in x: k, v = x.split("=",1) options[k] = v return options def merge_hash(a, b):
def list_intersection(a, b): def safe_eval(expr, locals={}, include_exceptions=False): ''' this is intended for allowing things like: with_items: a_list_variable where Jinja2 would return a string but we do not want to allow it to call functions (outside of Jinja2, where the env is constrained)...
def list_intersection(a, b): def safe_eval(expr, locals={}, include_exceptions=False): ''' This is intended for allowing things like: with_items: a_list_variable Where Jinja2 would return a string but we do not want to allow it to call functions (outside of Jinja2, where the env is constrained). I...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collection_tar, files_member_obj) ...
class CollectionRequirement: shutil.rmtree(b_collection_path) os.makedirs(b_collection_path) try: with tarfile.open(self.b_path, mode='r') as collection_tar: files_member_obj = collection_tar.getmember('FILES.json') with _tarfile_extract(collectio...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (n_filename, to_native(tar.name))) b_dest_filepath = os.path.join(b_dest, to_bytes(filename, errors='surrogate_or...
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None): raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'" % (n_filename, to_native(tar.name))) b_dest_filepath = os.path.abspath(os.path.join(b_dest, to_bytes(filename, erro...
__metaclass__ = type import json import os import pytest import tarfile import uuid
__metaclass__ = type import json import os import pytest import re import tarfile import uuid
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): collection._extract_tar_file(tfile, filename, output_dir, temp_dir, checksum) os.path.isfile(output_file)
def test_extract_tar_file_missing_parent_dir(tmp_tarfile): collection._extract_tar_file(tfile, filename, output_dir, temp_dir, checksum) os.path.isfile(output_file) def test_extract_tar_file_outside_dir(tmp_path_factory): filename = u'ÅÑŚÌβŁÈ' temp_dir = to_bytes(tmp_path_factory.mktemp('test-%s Coll...
default: :rc:`scatter.edgecolors` marker_obj.get_transform()) if not marker_obj.is_filled(): edgecolors = 'face' linewidths = rcParams['lines.linewidth'] offsets = np.ma.column_stack([x, y])
default: :rc:`scatter.edgecolors` marker_obj.get_transform()) if not marker_obj.is_filled(): edgecolors = 'face' if linewidths is None: linewidths = rcParams['lines.linewidth'] elif np.iterable(linewidths): linewidths = [ ...
class TestScatter: ax_test.scatter(np.ones(3), range(3), c=rgb) ax_test.scatter(np.ones(4)*2, range(4), c=rgba) def _params(c=None, xsize=2, *, edgecolors=None, **kwargs): return (c, edgecolors, kwargs if kwargs is not None else {}, xsize)
class TestScatter: ax_test.scatter(np.ones(3), range(3), c=rgb) ax_test.scatter(np.ones(4)*2, range(4), c=rgba) def test_scatter_linewidths(self): x = np.arange(5) fig, ax = plt.subplots() for i in range(3): pc = ax.scatter(x, np.full(5, i), c=f'C{i}', marker='x...
def load_data(path='imdb.npz', num_words=None, skip_top=0, path = get_file(path, origin='https://s3.amazonaws.com/text-datasets/imdb.npz', file_hash='599dadb1135973df5b59232a0e9a887c') with np.load(path) as f: x_train, labels_train = f['x_train'], f['y_train'] ...
def load_data(path='imdb.npz', num_words=None, skip_top=0, path = get_file(path, origin='https://s3.amazonaws.com/text-datasets/imdb.npz', file_hash='599dadb1135973df5b59232a0e9a887c') with np.load(path, allow_pickle=True) as f: x_train, labels_train = f['x_train'...
class APIRouter(routing.Router): def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable:
class APIRouter(routing.Router): def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute( path, endpoint=endpoint, name=name, dependency_overrides_provider=self.dependency_overrides_pr...
from fastapi import APIRouter, FastAPI, WebSocket from fastapi.testclient import TestClient router = APIRouter()
from fastapi import APIRouter, Depends, FastAPI, WebSocket from fastapi.testclient import TestClient router = APIRouter()
async def routerindex(websocket: WebSocket): await websocket.close() app.include_router(router) app.include_router(prefix_router, prefix="/prefix")
async def routerindex(websocket: WebSocket): await websocket.close() async def ws_dependency(): return "Socket Dependency" @router.websocket("/router-ws-depends/") async def router_ws_decorator_depends( websocket: WebSocket, data=Depends(ws_dependency) ): await websocket.accept() await websocket...
def test_router2(): with client.websocket_connect("/router2") as websocket: data = websocket.receive_text() assert data == "Hello, router!"
def test_router2(): with client.websocket_connect("/router2") as websocket: data = websocket.receive_text() assert data == "Hello, router!" def test_router_ws_depends(): client = TestClient(app) with client.websocket_connect("/router-ws-depends/") as websocket: assert websocket.rec...
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...
def test_startup_interactivehook_isolated_explicit(self): @unittest.skipUnless(sys.platform == 'win32', "only supported on Windows") class _pthFileTests(unittest.TestCase): def _create_underpth_exe(self, lines): temp_dir = tempfile.mkdtemp() self.addCleanup(test.support.rmtree, temp_dir) ex...
def test_startup_interactivehook_isolated_explicit(self): @unittest.skipUnless(sys.platform == 'win32', "only supported on Windows") class _pthFileTests(unittest.TestCase): def _create_underpth_exe(self, lines, exe_pth=True): import _winapi temp_dir = tempfile.mkdtemp() self.addCleanup(test...
def test_underpth_file(self): self.assertTrue(rc, "sys.path is incorrect") if __name__ == "__main__": unittest.main()
def test_underpth_file(self): self.assertTrue(rc, "sys.path is incorrect") def test_underpth_dll_file(self): libpath = os.path.dirname(os.path.dirname(encodings.__file__)) exe_prefix = os.path.dirname(sys.executable) exe_file = self._create_underpth_exe([ 'fake-path-nam...
https://support.sas.com/techsup/technote/ts140.pdf """ from collections import abc from datetime import datetime from io import BytesIO import struct import warnings
https://support.sas.com/techsup/technote/ts140.pdf """ from collections import abc from datetime import datetime import struct import warnings
class XportReader(abc.Iterator): if isinstance(filepath_or_buffer, (str, bytes)): self.filepath_or_buffer = open(filepath_or_buffer, "rb") else: # Copy to BytesIO, and ensure no encoding contents = filepath_or_buffer.read() try: contents = ...
class XportReader(abc.Iterator): if isinstance(filepath_or_buffer, (str, bytes)): self.filepath_or_buffer = open(filepath_or_buffer, "rb") else: # Since xport files include non-text byte sequences, xport files # should already be opened in binary mode in Python 3. ...
class TestXport: self.dirpath = datapath("io", "sas", "data") self.file01 = os.path.join(self.dirpath, "DEMO_G.xpt") self.file02 = os.path.join(self.dirpath, "SSHSV1_A.xpt") self.file03 = os.path.join(self.dirpath, "DRXFCD_G.xpt") self.file04 = os.path.join(self.dirpath, "paxraw_...
class TestXport: self.dirpath = datapath("io", "sas", "data") self.file01 = os.path.join(self.dirpath, "DEMO_G.xpt") self.file02 = os.path.join(self.dirpath, "SSHSV1_A.xpt") self.file02b = open(os.path.join(self.dirpath, "SSHSV1_A.xpt"), "rb") self.file03 = os.path.join(self.dirp...
class TestXport: data = read_sas(self.file02) tm.assert_frame_equal(data, data_csv) def test_multiple_types(self): # Test with DRXFCD_G.xpt (contains text and numeric variables)
class TestXport: data = read_sas(self.file02) tm.assert_frame_equal(data, data_csv) def test2_binary(self): # Test with SSHSV1_A.xpt, read as a binary file # Compare to this data_csv = pd.read_csv(self.file02.replace(".xpt", ".csv")) numeric_as_float(data_csv) ...
import unittest import urllib.parse
import sys import unicodedata import unittest import urllib.parse
def test_all(self): expected.append(name) self.assertCountEqual(urllib.parse.__all__, expected) class Utility_Tests(unittest.TestCase): """Testcase to test the various utility functions in the urllib."""
def test_all(self): expected.append(name) self.assertCountEqual(urllib.parse.__all__, expected) def test_urlsplit_normalization(self): # Certain characters should never occur in the netloc, # including under normalization. # Ensure that ALL of them are detected and c...
def _splitnetloc(url, start=0): delim = min(delim, wdelim) # use earliest delim position return url[start:delim], url[delim:] # return (domain, rest) def urlsplit(url, scheme='', allow_fragments=True): """Parse a URL into 5 components: <scheme>://<netloc>/<path>?<query>#<fragment>
def _splitnetloc(url, start=0): delim = min(delim, wdelim) # use earliest delim position return url[start:delim], url[delim:] # return (domain, rest) def _checknetloc(netloc): if not netloc or netloc.isascii(): return # looking for characters like \u2100 that expand to 'a/c' #...
def urlsplit(url, scheme='', allow_fragments=True): url, fragment = url.split('#', 1) if '?' in url: url, query = url.split('?', 1) v = SplitResult('http', netloc, url, query, fragment) _parse_cache[key] = v return _coerce_result(v)
def urlsplit(url, scheme='', allow_fragments=True): url, fragment = url.split('#', 1) if '?' in url: url, query = url.split('?', 1) _checknetloc(netloc) v = SplitResult('http', netloc, url, query, fragment) _parse_cache[key] = v ...
def urlsplit(url, scheme='', allow_fragments=True): url, fragment = url.split('#', 1) if '?' in url: url, query = url.split('?', 1) v = SplitResult(scheme, netloc, url, query, fragment) _parse_cache[key] = v return _coerce_result(v)
def urlsplit(url, scheme='', allow_fragments=True): url, fragment = url.split('#', 1) if '?' in url: url, query = url.split('?', 1) _checknetloc(netloc) v = SplitResult(scheme, netloc, url, query, fragment) _parse_cache[key] = v return _coerce_result(v)
def test_getproxies_environment_keep_no_proxies(self): self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_bypass_environment_host_match(self): bypass = urllib.reques...
def test_getproxies_environment_keep_no_proxies(self): self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_cgi_ignore(self): try: self.env.set('HTTP_PROXY...
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value for name, value in os.environ.items(): if name[-6:] == '_proxy': name = name.lower()
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY # (non-all-lowercase) as it may be set from the web server by a "Proxy:" # header from the clie...
def get_flat_dependant(dependant: Dependant) -> Dependant: def is_scalar_field(field: Field) -> bool: return ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(fiel...
def get_flat_dependant(dependant: Dependant) -> Dependant: def is_scalar_field(field: Field) -> bool: if not ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(fiel...
from django.utils.encoding import force_bytes, force_str, force_text from django.utils.functional import keep_lazy_text from django.utils.six.moves.urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, urlparse, ) ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"') ...
from django.utils.encoding import force_bytes, force_str, force_text from django.utils.functional import keep_lazy_text from django.utils.six.moves.urllib.parse import ( quote, quote_plus, unquote, unquote_plus, urlencode as original_urlencode, ) if six.PY2: from urlparse import ( ParseResult, SplitRes...
def is_safe_url(url, host=None): return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) def _is_safe_url(url, host): # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsafe. if url.starts...
def is_safe_url(url, host=None): return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host) # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function. def _urlparse(url, scheme='', allow_fragments=True): """Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params...
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', '\n', ) for bad_url in bad_urls:
class TestUtilsHttp(unittest.TestCase): r'http://testserver\me:pass@example.com', r'http://testserver\@example.com', r'http:\\testserver\confirm\me@example.com', 'http:999999999', 'ftp:9999999999', '\n', ) for bad_url in bad_urls:
class TestUtilsHttp(unittest.TestCase): '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', ) for good_url in good_urls: self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s should be allowed" % good_ur...
class TestUtilsHttp(unittest.TestCase): '//testserver/', 'http://testserver/confirm?email=me@example.com', '/url%20with%20spaces/', 'path/http:2222222222', ) for good_url in good_urls: self.assertTrue(http.is_safe_url(good_url, host='testserver...
def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False): stderr=subprocess.STDOUT, ) if checkout is not None: subprocess.check_output( # nosec [repo_type, 'checkout', checkout], cwd=repo_dir, ...
def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False): stderr=subprocess.STDOUT, ) if checkout is not None: checkout_params = [checkout] # Avoid Mercurial "--config" and "--debugger" injection vulnerability if repo_ty...
def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False): output = clone_error.output.decode('utf-8') if 'not found' in output.lower(): raise RepositoryNotFound( 'The repository {} could not be found, ' 'have you made a typo?'.f...
def clone(repo_url, checkout=None, clone_to_dir='.', no_input=False): output = clone_error.output.decode('utf-8') if 'not found' in output.lower(): raise RepositoryNotFound( f'The repository {repo_url} could not be found, ' 'have you made a...
def test_clone_should_invoke_vcs_command( mock_subprocess.assert_any_call( [repo_type, 'clone', repo_url], cwd=str(clone_dir), stderr=subprocess.STDOUT ) mock_subprocess.assert_any_call( [repo_type, 'checkout', branch], cwd=expected_repo_dir, stderr=subprocess.STDOUT )
def test_clone_should_invoke_vcs_command( mock_subprocess.assert_any_call( [repo_type, 'clone', repo_url], cwd=str(clone_dir), stderr=subprocess.STDOUT ) branch_info = [branch] # We sanitize branch information for Mercurial if repo_type == "hg": branch_info.insert(0, "--") mock...
def test_clone_handles_repo_typo(mocker, clone_dir, error_message): vcs.clone(repository_url, clone_to_dir=str(clone_dir), no_input=True) assert str(err.value) == ( 'The repository {} could not be found, have you made a typo?' ).format(repository_url) @pytest.mark.parametrize(
def test_clone_handles_repo_typo(mocker, clone_dir, error_message): vcs.clone(repository_url, clone_to_dir=str(clone_dir), no_input=True) assert str(err.value) == ( f'The repository {repository_url} could not be found, have you made a typo?' ) @pytest.mark.parametrize(
def test_clone_handles_branch_typo(mocker, clone_dir, error_message): assert str(err.value) == ( 'The unknown_branch branch of repository ' '{} could not found, have you made a typo?' ).format(repository_url) def test_clone_unknown_subprocess_error(mocker, clone_dir):
def test_clone_handles_branch_typo(mocker, clone_dir, error_message): assert str(err.value) == ( 'The unknown_branch branch of repository ' f'{repository_url} could not found, have you made a typo?' ) def test_clone_unknown_subprocess_error(mocker, clone_dir):
def authenticate(self, context, auth=None): self.token_api.create_token( context, token_id, dict(key=token_id, id=token_id, user=user_ref, tenant=tenant_ref, ...
def authenticate(self, context, auth=None): self.token_api.create_token( context, token_id, dict(key=token_id, id=token_id, expires=auth_token_data['expires'], user=user_re...
# License for the specific language governing permissions and limitations # under the License. import uuid import default_fixtures from keystone import exception from keystone import identity from keystone import service
# License for the specific language governing permissions and limitations # under the License. import time import uuid import default_fixtures from keystone import config from keystone import exception from keystone import identity from keystone import service
from keystone.openstack.common import timeutils def _build_user_auth(token=None, username=None, password=None, tenant_name=None): """Build auth dictionary.
from keystone.openstack.common import timeutils CONF = config.CONF def _build_user_auth(token=None, username=None, password=None, tenant_name=None): """Build auth dictionary.
def test_scoped_remote_authn_invalid_user(self): self.api.authenticate, {'REMOTE_USER': uuid.uuid4().hex}, body_dict)
def test_scoped_remote_authn_invalid_user(self): self.api.authenticate, {'REMOTE_USER': uuid.uuid4().hex}, body_dict) class TokenExpirationTest(test.TestCase): def setUp(self): super(TokenExpirationTest, self).setUp() self.identity_api = kvs_identity.Identity() ...
def diff(arr, n: int, axis: int = 0): dtype = arr.dtype is_timedelta = False if needs_i8_conversion(arr): dtype = np.float64 arr = arr.view("i8")
def diff(arr, n: int, axis: int = 0): dtype = arr.dtype is_timedelta = False is_bool = False if needs_i8_conversion(arr): dtype = np.float64 arr = arr.view("i8")
def diff(arr, n: int, axis: int = 0): elif is_bool_dtype(dtype): dtype = np.object_ elif is_integer_dtype(dtype): dtype = np.float64
def diff(arr, n: int, axis: int = 0): elif is_bool_dtype(dtype): dtype = np.object_ is_bool = True elif is_integer_dtype(dtype): dtype = np.float64
def diff(arr, n: int, axis: int = 0): result = res - lag result[mask] = na out_arr[res_indexer] = result else: out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer]
def diff(arr, n: int, axis: int = 0): result = res - lag result[mask] = na out_arr[res_indexer] = result elif is_bool: out_arr[res_indexer] = arr[res_indexer] ^ arr[lag_indexer] else: out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer]
from pandas import ( from pandas.api.types import is_scalar from pandas.core.index import MultiIndex from pandas.core.indexes.datetimes import Timestamp import pandas.util.testing as tm from pandas.util.testing import ( assert_almost_equal,
from pandas import ( from pandas.api.types import is_scalar from pandas.core.index import MultiIndex from pandas.core.indexes.datetimes import Timestamp from pandas.core.indexes.timedeltas import TimedeltaIndex import pandas.util.testing as tm from pandas.util.testing import ( assert_almost_equal,
class TestSeriesAnalytics: result = s.cummax(skipna=False) tm.assert_series_equal(expected, result) def test_npdiff(self): pytest.skip("skipping due to Series no longer being an ndarray") # no longer works as the return type of np.diff is now nd.array
class TestSeriesAnalytics: result = s.cummax(skipna=False) tm.assert_series_equal(expected, result) def test_np_diff(self): pytest.skip("skipping due to Series no longer being an ndarray") # no longer works as the return type of np.diff is now nd.array
class TestSeriesAnalytics: r = np.diff(s) assert_series_equal(Series([nan, 0, 0, 0, nan]), r) def _check_accum_op(self, name, datetime_series_, check_dtype=True): func = getattr(np, name) tm.assert_numpy_array_equal(
class TestSeriesAnalytics: r = np.diff(s) assert_series_equal(Series([nan, 0, 0, 0, nan]), r) def test_int_diff(self): # int dtype a = 10000000000000000 b = a + 1 s = Series([a, b]) result = s.diff() assert result[1] == 1 def test_tz_diff(self):...
class TestTimeSeries(TestData): ) tm.assert_index_equal(expected.index, result.index) def test_diff(self): # Just run the function self.ts.diff() # int dtype a = 10000000000000000 b = a + 1 s = Series([a, b]) rs = s.diff() assert rs[...
class TestTimeSeries(TestData): ) tm.assert_index_equal(expected.index, result.index) def test_pct_change(self): rs = self.ts.pct_change(fill_method=None) assert_series_equal(rs, self.ts / self.ts.shift(1) - 1)
def upload_scan(self, filename): if filename.endswith('.json') or filename.endswith('.jsonld'): headers['Content-Type'] = 'application/ld+json' with open(filename,"r") as f: response = requests.post(url, headers=headers, data=f, verify=False) elif filename.endswit...
def upload_scan(self, filename): if filename.endswith('.json') or filename.endswith('.jsonld'): headers['Content-Type'] = 'application/ld+json' with open(filename,"r") as f: response = requests.post(url, headers=headers, data=f, verify=not self.config['insecure']) ...
def download_project_scans(self, project_name,version_name, output_folder=None): if not os.path.exists(project_name): os.mkdir(project_name) pathname = os.path.join(project_name, filename) responce = requests.get(url, headers=self.get_heade...
def download_project_scans(self, project_name,version_name, output_folder=None): if not os.path.exists(project_name): os.mkdir(project_name) pathname = os.path.join(project_name, filename) responce = requests.get(url, headers=self.get_heade...
VERSION = (0, 0, 52) __version__ = '.'.join(map(str, VERSION))
VERSION = (0, 0, 53) __version__ = '.'.join(map(str, VERSION))
class XMLRPCHandlerTests(unittest.TestCase): self.assertEqual(request._error, 500) class TraverseTests(unittest.TestCase): def test_underscore(self): from supervisor import xmlrpc self.assertRaises(xmlrpc.RPCError, xmlrpc.traverse, None, '_', None) def test_notfound(self): from...
class XMLRPCHandlerTests(unittest.TestCase): self.assertEqual(request._error, 500) class TraverseTests(unittest.TestCase): def test_security_disallows_underscore_methods(self): from supervisor import xmlrpc class Root: pass class A: def _danger(self): ...
class supervisor_xmlrpc_handler(xmlrpc_handler): return traverse(self.rpcinterface, method, params) def traverse(ob, method, params): path = method.split('.') for name in path: if name.startswith('_'): # security (don't allow things that start with an underscore to # be ...
class supervisor_xmlrpc_handler(xmlrpc_handler): return traverse(self.rpcinterface, method, params) def traverse(ob, method, params): dotted_parts = method.split('.') # security (CVE-2017-11610, don't allow object traversal) if len(dotted_parts) != 2: raise RPCError(Faults.UNKNOWN_METHOD) ...
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 ...
part 3</font></u> self.assertEqual(get_element_by_attribute('class', 'foo', html), None) self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None) def test_get_elements_by_class(self): html = ''' <span class="foo bar">nice</span><span class="foo bar">also ni...
part 3</font></u> self.assertEqual(get_element_by_attribute('class', 'foo', html), None) self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None) html = ''' <div itemprop="author" itemscope>foo</div> ''' self.assertEqual(get_element_by_attribut...
def get_elements_by_attribute(attribute, value, html, escape_value=True): retlist = [] for m in re.finditer(r'''(?xs) <([a-zA-Z0-9:._-]+) (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'))*? \s+%s=['"]?%s['"]? (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[...
def get_elements_by_attribute(attribute, value, html, escape_value=True): retlist = [] for m in re.finditer(r'''(?xs) <([a-zA-Z0-9:._-]+) (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='[^']*'|))*? \s+%s=['"]?%s['"]? (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]*|="[^"]*"|='...
class StringMethods(NoNewAttributesMixin): if isinstance(others, ABCSeries): return [others] elif isinstance(others, ABCIndexClass): return [Series(others._values, index=others)] elif isinstance(others, ABCDataFrame): return [others[x] for x in others] ...
class StringMethods(NoNewAttributesMixin): if isinstance(others, ABCSeries): return [others] elif isinstance(others, ABCIndexClass): return [Series(others._values, index=idx)] elif isinstance(others, ABCDataFrame): return [others[x] for x in others] el...
def test_string_array_extract(): result = result.astype(object) tm.assert_equal(result, expected)
def test_string_array_extract(): result = result.astype(object) tm.assert_equal(result, expected) @pytest.mark.parametrize("klass", [tuple, list, np.array, pd.Series, pd.Index]) def test_cat_different_classes(klass): # https://github.com/pandas-dev/pandas/issues/33425 s = pd.Series(["a", "b", "c"]) ...
class HttpRequest(object): def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( 'The SECURE_PROXY_SSL_HEADER setting must be a tu...
class HttpRequest(object): def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, secure_value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( 'The SECURE_PROXY_SSL_HEADER setting must ...
class SecureProxySslHeaderTest(SimpleTestCase): req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertIs(req.is_secure(), True) class IsOverriddenTest(SimpleTestCase): def test_configure(self):
class SecureProxySslHeaderTest(SimpleTestCase): req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' self.assertIs(req.is_secure(), True) @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTOCOL', 'https')) def test_xheader_preferred_to_underlying_request(self): class ProxyRequ...
Wild 185.0 result = coerce_to_dtypes(result, self.dtypes) if constructor is not None: result = Series(result, index=labels) return result def nunique(self, axis=0, dropna=True) -> Series:
Wild 185.0 result = coerce_to_dtypes(result, self.dtypes) if constructor is not None: result = self._constructor_sliced(result, index=labels) return result def nunique(self, axis=0, dropna=True) -> Series:
class TestDataFrameSubclassing: result = df.apply(lambda x: [1, 2, 3], axis=1) assert not isinstance(result, tm.SubclassedDataFrame) tm.assert_series_equal(result, expected)
class TestDataFrameSubclassing: result = df.apply(lambda x: [1, 2, 3], axis=1) assert not isinstance(result, tm.SubclassedDataFrame) tm.assert_series_equal(result, expected) def test_subclassed_numeric_reductions(self, all_numeric_reductions): # GH 25596 df = tm.SubclassedD...
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')
def test_apply_index(cls, n): ser = pd.Series(rng) res = rng + offset res_v2 = offset.apply_index(rng) assert (res == res_v2).all() assert res[0] == rng[0] + offset
def test_apply_index(cls, n): ser = pd.Series(rng) res = rng + offset assert res.freq is None # not retained res_v2 = offset.apply_index(rng) assert (res == res_v2).all() assert res[0] == rng[0] + offset
class MonthOffset(SingleConstructorOffset): @apply_index_wraps def apply_index(self, i): shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt) # TODO: going through __new__ raises on call to _validate_frequency; # are we passing incorrect freq? return type(i)._simple_...
class MonthOffset(SingleConstructorOffset): @apply_index_wraps def apply_index(self, i): shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt) return type(i)._simple_new(shifted, dtype=i.dtype) class MonthEnd(MonthOffset):
class QuarterOffset(DateOffset): shifted = liboffsets.shift_quarters( dtindex.asi8, self.n, self.startingMonth, self._day_opt ) # TODO: going through __new__ raises on call to _validate_frequency; # are we passing incorrect freq? return type(dtindex)._simple_new( ...
class QuarterOffset(DateOffset): shifted = liboffsets.shift_quarters( dtindex.asi8, self.n, self.startingMonth, self._day_opt ) return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype) class BQuarterEnd(QuarterOffset):
class YearOffset(DateOffset): shifted = liboffsets.shift_quarters( dtindex.asi8, self.n, self.month, self._day_opt, modby=12 ) # TODO: going through __new__ raises on call to _validate_frequency; # are we passing incorrect freq? return type(dtindex)._simple_new( ...
class YearOffset(DateOffset): shifted = liboffsets.shift_quarters( dtindex.asi8, self.n, self.month, self._day_opt, modby=12 ) return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype) def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_norma...
class LinuxHardware(Hardware): # regex used against mtab content to find entries that are bind mounts MTAB_BIND_MOUNT_RE = re.compile(r'.*bind.*"') def populate(self, collected_facts=None): hardware_facts = {} self.module.run_command_environ_update = {'LANG': 'C', 'LC_ALL': 'C', 'LC_NUMERIC...
class LinuxHardware(Hardware): # regex used against mtab content to find entries that are bind mounts MTAB_BIND_MOUNT_RE = re.compile(r'.*bind.*"') # regex used for replacing octal escape sequences OCTAL_ESCAPE_RE = re.compile(r'\\[0-9]{3}') def populate(self, collected_facts=None): hardwa...
class LinuxHardware(Hardware): mtab_entries.append(fields) return mtab_entries def get_mount_info(self, mount, device, uuids): mount_size = get_mount_size(mount)
class LinuxHardware(Hardware): mtab_entries.append(fields) return mtab_entries @staticmethod def _replace_octal_escapes_helper(match): # Convert to integer using base8 and then convert to character return chr(int(match.group()[1:], 8)) def _replace_octal_escapes(self, v...
class LinuxHardware(Hardware): pool = ThreadPool(processes=min(len(mtab_entries), cpu_count())) maxtime = globals().get('GATHER_TIMEOUT') or timeout.DEFAULT_GATHER_TIMEOUT for fields in mtab_entries: device, mount, fstype, options = fields[0], fields[1], fields[2], fields[3]
class LinuxHardware(Hardware): pool = ThreadPool(processes=min(len(mtab_entries), cpu_count())) maxtime = globals().get('GATHER_TIMEOUT') or timeout.DEFAULT_GATHER_TIMEOUT for fields in mtab_entries: # Transform octal escape sequences fields = [self._replace_octal_escapes...
MTAB_ENTRIES = [ '0', '0' ], ['fusectl', '/sys/fs/fuse/connections', 'fusectl', 'rw,relatime', '0', '0']] BIND_MOUNTS = ['/not/a/real/bind_mount']
MTAB_ENTRIES = [ '0', '0' ], ['fusectl', '/sys/fs/fuse/connections', 'fusectl', 'rw,relatime', '0', '0'], # Mount path with space in the name # The space is encoded as \040 since the fields in /etc/mtab are space-delimeted ['/dev/sdz9', r'/mnt/foo\040bar', 'ext4', 'rw,relatime', '0',...
class TestFactsLinuxHardwareGetMountFacts(unittest.TestCase): self.assertIsInstance(mount_facts['mounts'], list) self.assertIsInstance(mount_facts['mounts'][0], dict) @patch('ansible.module_utils.facts.hardware.linux.get_file_content', return_value=MTAB) def test_get_mtab_entries(self, mock_get...
class TestFactsLinuxHardwareGetMountFacts(unittest.TestCase): self.assertIsInstance(mount_facts['mounts'], list) self.assertIsInstance(mount_facts['mounts'][0], dict) # Find mounts with space in the mountpoint path mounts_with_space = [x for x in mount_facts['mounts'] if ' ' in x['mount...
def parse_yaml_query(yaml_content): On success, the processed MLQuery object. """ logger.debug("Attempting to parse YAML content:\n%s" % yaml_content) return parse_query(yaml.load(yaml_content)) def parse_json_query(json_content):
def parse_yaml_query(yaml_content): On success, the processed MLQuery object. """ logger.debug("Attempting to parse YAML content:\n%s" % yaml_content) return parse_query(yaml.safe_load(yaml_content)) def parse_json_query(json_content):
def authenticate(self, context, credentials=None, ec2Credentials=None): context=context, user_id=user_ref['id'], tenant_id=tenant_ref['id']) catalog_ref = self.catalog_api.get_catalog( context=context, user_id=user_ref['id'],
def authenticate(self, context, credentials=None, ec2Credentials=None): context=context, user_id=user_ref['id'], tenant_id=tenant_ref['id']) # TODO(termie): optimize this call at some point and put it into the # the return for metadata # fill ou...
def authenticate(self, context, credentials=None, ec2Credentials=None): tenant=tenant_ref, metadata=metadata_ref)) # TODO(termie): optimize this call at some point and put it into the # the return for metadata ...
def authenticate(self, context, credentials=None, ec2Credentials=None): tenant=tenant_ref, metadata=metadata_ref)) # TODO(termie): make this a util function or something # TODO(termie): i don't think the ec2 middleware currently ex...
class IcnsFile: i = HEADERSIZE while i < filesize: sig, blocksize = nextheader(fobj) i = i + HEADERSIZE blocksize = blocksize - HEADERSIZE dct[sig] = (i, blocksize)
class IcnsFile: i = HEADERSIZE while i < filesize: sig, blocksize = nextheader(fobj) if blocksize <= 0: raise SyntaxError('invalid block header') i = i + HEADERSIZE blocksize = blocksize - HEADERSIZE dct[sig] = (i, blocksize)
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]: """ container: Optional[LN] = container_of(leaf) while container is not None and container.type != token.ENDMARKER: is_fmt_on = False for comment in list_comments(container.prefix, is_endmarker=False): if comment.value in FM...
def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]: """ container: Optional[LN] = container_of(leaf) while container is not None and container.type != token.ENDMARKER: if fmt_on(container): return # fix for fmt: on in children if contains_fmt_on_at_column(container, ...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_remove_empty_parentheses_after_class(self) -> None: source, expected = read_data("class_blank_paren...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_fmtonoff4(self) -> None: source, expected = read_data("fmtonoff4") actual = fs(source) ...
from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException from starlette.requests import Request
from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException from starlette.requests import Request
async def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": exc.errors()} )
async def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": jsonable_encoder(exc.errors())}, )
from typing import List from fastapi import FastAPI from pydantic import BaseModel from starlette.testclient import TestClient app = FastAPI()
from decimal import Decimal from typing import List from fastapi import FastAPI from pydantic import BaseModel, condecimal from starlette.testclient import TestClient app = FastAPI()
app = FastAPI() class Item(BaseModel): name: str age: int @app.post("/items/")
app = FastAPI() class Item(BaseModel): name: str age: condecimal(gt=Decimal(0.0)) @app.post("/items/")
openapi_schema = { "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "age": {"title": "Age", "type": "integer"}, }, }, "ValidationError": {
openapi_schema = { "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "age": {"title": "Age", "exclusiveMinimum": 0.0, "type": "number"}, }, }, "ValidationError": {
openapi_schema = { }, } multiple_errors = { "detail": [ {
openapi_schema = { }, } single_error = { "detail": [ { "ctx": {"limit_value": 0.0}, "loc": ["body", "item", 0, "age"], "msg": "ensure this value is greater than 0", "type": "value_error.number.not_gt", } ] } multiple_errors = { "detail": ...
multiple_errors = { }, { "loc": ["body", "item", 0, "age"], "msg": "value is not a valid integer", "type": "type_error.integer", }, { "loc": ["body", "item", 1, "name"],
multiple_errors = { }, { "loc": ["body", "item", 0, "age"], "msg": "value is not a valid decimal", "type": "type_error.decimal", }, { "loc": ["body", "item", 1, "name"],