buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def getrgb(color): :param color: A color string :return: ``(red, green, blue[, alpha])`` """ color = color.lower() rgb = colormap.get(color, None)
def getrgb(color): :param color: A color string :return: ``(red, green, blue[, alpha])`` """ if len(color) > 100: raise ValueError("color specifier is too long") color = color.lower() rgb = colormap.get(color, None)
class TestUtil(unittest.TestCase): "playlist":[{"controls":{"all":null}}] }''') def test_js_to_json_edgecases(self): on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}") self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
class TestUtil(unittest.TestCase): "playlist":[{"controls":{"all":null}}] }''') inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"' json_code = js_to_json(inp) self.assertEqual(json.loads(json_code...
def js_to_json(code): return '"%s"' % v res = re.sub(r'''(?x) "(?:[^"\\]*(?:\\\\|\\")?)*"| '(?:[^'\\]*(?:\\\\|\\')?)*'| [a-zA-Z_][.a-zA-Z_0-9]* ''', fix_kv, code) res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
def js_to_json(code): return '"%s"' % v res = re.sub(r'''(?x) "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"| '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'| [a-zA-Z_][.a-zA-Z_0-9]* ''', fix_kv, code) res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
def readString(self): pass def skip(self, type): if type == TType.STOP: return elif type == TType.BOOL: self.readBool() elif type == TType.BYTE: self.readByte()
def readString(self): pass def skip(self, type): if type == TType.BOOL: self.readBool() elif type == TType.BYTE: self.readByte()
def skip(self, type): for _ in range(size): self.skip(etype) self.readListEnd() def readIntegral(self, type): if type == TType.BOOL:
def skip(self, type): for _ in range(size): self.skip(etype) self.readListEnd() else: raise TProtocolException( TProtocolException.INVALID_DATA, "Unexpected type for skipping {}".format(type) ) def readIntegral(...
class RangeIndex(Int64Index): if self.step > 0: start, stop, step = self.start, self.stop, self.step else: # Work on reversed range for simplicity: start, stop, step = (self.stop - self.step, self.start + 1, -self.step) target_array = np.asarray(target) ...
class RangeIndex(Int64Index): if self.step > 0: start, stop, step = self.start, self.stop, self.step else: # GH 28678: work on reversed range for simplicity reverse = self._range[::-1] start, stop, step = reverse.start, reverse.stop, reverse.step ...
class TestRangeIndex(Numeric): expected = np.array([0, 1, 2, 3, 3, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) def test_join_outer(self): # join with Int64Index other = Int64Index(np.arange(25, 14, -1))
class TestRangeIndex(Numeric): expected = np.array([0, 1, 2, 3, 3, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize("stop", [0, -1, -2]) def test_get_indexer_decreasing(self, stop): # GH 28678 index = RangeIndex(7, stop, -3) resu...
class scheduler(Config): # These disables last for disable_persist seconds. disable_window = parameter.IntParameter(default=3600, config_path=dict(section='scheduler', name='disable-window-seconds')) disable_failures = parameter.IntParameter(default=None, ...
class scheduler(Config): # These disables last for disable_persist seconds. disable_window = parameter.IntParameter(default=3600, config_path=dict(section='scheduler', name='disable-window-seconds')) disable_failures = parameter.IntParameter(default=999999999, ...
class Task(object): self.failures.add_failure() def has_excessive_failures(self): if (self.failures.first_failure_time is not None and self.disable_hard_timeout): if (time.time() >= self.failures.first_failure_time + self.disable_hard_timeout): ...
class Task(object): self.failures.add_failure() def has_excessive_failures(self): if self.failures.first_failure_time is not None: if (time.time() >= self.failures.first_failure_time + self.disable_hard_timeout): return True
class Task(object): return False def can_disable(self): return (self.disable_failures is not None or self.disable_hard_timeout is not None) @property def pretty_id(self): param_str = ', '.join('{}={}'.format(key, value) for key, value in self.params.items())
class Task(object): return False @property def pretty_id(self): param_str = ', '.join('{}={}'.format(key, value) for key, value in self.params.items())
class SimpleTaskState(object): elif task.scheduler_disable_time is not None and new_status != DISABLED: return if new_status == FAILED and task.can_disable() and task.status != DISABLED: task.add_failure() if task.has_excessive_failures(): tas...
class SimpleTaskState(object): elif task.scheduler_disable_time is not None and new_status != DISABLED: return if new_status == FAILED and task.status != DISABLED: task.add_failure() if task.has_excessive_failures(): task.scheduler_disable_tim...
class CentralPlannerTest(unittest.TestCase): self.assertEqual(set([]), set(self.sch.task_list(status, ''))) self.assertEqual(3, len(self.sch.task_list(None, ''))) # None == All statuses
class CentralPlannerTest(unittest.TestCase): self.assertEqual(set([]), set(self.sch.task_list(status, ''))) self.assertEqual(3, len(self.sch.task_list(None, ''))) # None == All statuses def test_no_crash_on_only_disable_hard_timeout(self): """ Scheduler shouldn't crash with on...
async def get_file( try: length = await make_deferred_yieldable( readBodyToFile(response, output_stream, max_size) ) except SynapseError: # This can happen e.g. because the body is too large. raise except Exception as e: ...
async def get_file( try: length = await make_deferred_yieldable( read_body_with_max_size(response, output_stream, max_size) ) except BodyExceededMaxSize: SynapseError( 502, "Requested file is too large > %r bytes" % (ma...
def _timeout_to_request_timed_out_error(f: Failure): return f class _ReadBodyToFileProtocol(protocol.Protocol): def __init__( self, stream: BinaryIO, deferred: defer.Deferred, max_size: Optional[int] ):
def _timeout_to_request_timed_out_error(f: Failure): return f class BodyExceededMaxSize(Exception): """The maximum allowed size of the HTTP body was exceeded.""" class _ReadBodyWithMaxSizeProtocol(protocol.Protocol): def __init__( self, stream: BinaryIO, deferred: defer.Deferred, max_size: Optio...
def dataReceived(self, data: bytes) -> None: self.stream.write(data) self.length += len(data) if self.max_size is not None and self.length >= self.max_size: self.deferred.errback( SynapseError( 502, "Requested file is too large ...
def dataReceived(self, data: bytes) -> None: self.stream.write(data) self.length += len(data) if self.max_size is not None and self.length >= self.max_size: self.deferred.errback(BodyExceededMaxSize()) self.deferred = defer.Deferred() self.transport.loseConnec...
def connectionLost(self, reason: Failure) -> None: self.deferred.errback(reason) def readBodyToFile( response: IResponse, stream: BinaryIO, max_size: Optional[int] ) -> defer.Deferred: """ Read a HTTP response body to a file-object. Optionally enforcing a maximum file size. Args: ...
def connectionLost(self, reason: Failure) -> None: self.deferred.errback(reason) def read_body_with_max_size( response: IResponse, stream: BinaryIO, max_size: Optional[int] ) -> defer.Deferred: """ Read a HTTP response body to a file-object. Optionally enforcing a maximum file size. If th...
def readBodyToFile( """ d = defer.Deferred() response.deliverBody(_ReadBodyToFileProtocol(stream, d, max_size)) return d
def readBodyToFile( """ d = defer.Deferred() response.deliverBody(_ReadBodyWithMaxSizeProtocol(stream, d, max_size)) return d
import logging import random import time from typing import Callable, Dict, Optional, Tuple import attr from twisted.internet import defer from twisted.internet.interfaces import IReactorTime from twisted.web.client import RedirectAgent, readBody from twisted.web.http import stringToDatetime from twisted.web.http_hea...
import logging import random import time from io import BytesIO from typing import Callable, Dict, Optional, Tuple import attr from twisted.internet import defer from twisted.internet.interfaces import IReactorTime from twisted.web.client import RedirectAgent from twisted.web.http import stringToDatetime from twisted...
# lower bound for .well-known cache period WELL_KNOWN_MIN_CACHE_PERIOD = 5 * 60 # Attempt to refetch a cached well-known N% of the TTL before it expires. # e.g. if set to 0.2 and we have a cached entry with a TTL of 5mins, then # we'll start trying to refetch 1 minute before it expires.
# lower bound for .well-known cache period WELL_KNOWN_MIN_CACHE_PERIOD = 5 * 60 # The maximum size (in bytes) to allow a well-known file to be. WELL_KNOWN_MAX_SIZE = 50 * 1024 # 50 KiB # Attempt to refetch a cached well-known N% of the TTL before it expires. # e.g. if set to 0.2 and we have a cached entry with a TTL...
async def _make_well_known_request( server_name: name of the server, from the requested url retry: Whether to retry the request if it fails. Returns: Returns the response object and body. Response may be a non-200 response. """
async def _make_well_known_request( server_name: name of the server, from the requested url retry: Whether to retry the request if it fails. Raises: _FetchWellKnownFailure if we fail to lookup a result Returns: Returns the response object and body. Respo...
async def _make_well_known_request( b"GET", uri, headers=Headers(headers) ) ) body = await make_deferred_yieldable(readBody(response)) if 500 <= response.code < 600: raise Exception("Non-200 response %s" % (...
async def _make_well_known_request( b"GET", uri, headers=Headers(headers) ) ) body_stream = BytesIO() await make_deferred_yieldable( read_body_with_max_size(response, body_stream, WELL_KNOWN_MAX_SIZE) ...
async def _make_well_known_request( except defer.CancelledError: # Bail if we've been cancelled raise except Exception as e: if not retry or i >= WELL_KNOWN_RETRY_ATTEMPTS: logger.info("Error fetching %s: %s", uri_str, e)
async def _make_well_known_request( except defer.CancelledError: # Bail if we've been cancelled raise except BodyExceededMaxSize: # If the well-known file was too large, do not keep attempting # to download it, but consider it a tem...
import synapse.metrics import synapse.util.retryutils from synapse.api.errors import ( FederationDeniedError, HttpResponseException, RequestSendFailed, ) from synapse.http import QuieterFileBodyProducer from synapse.http.client import ( BlacklistingAgentWrapper, BlacklistingReactorWrapper, encod...
import synapse.metrics import synapse.util.retryutils from synapse.api.errors import ( Codes, FederationDeniedError, HttpResponseException, RequestSendFailed, SynapseError, ) from synapse.http import QuieterFileBodyProducer from synapse.http.client import ( BlacklistingAgentWrapper, Blacklis...
async def get_file( headers = dict(response.headers.getAllRawHeaders()) try: d = readBodyToFile(response, output_stream, max_size) d.addTimeout(self.default_timeout, self.reactor) length = await make_deferred_yieldable(d) except Exception as e: lo...
async def get_file( headers = dict(response.headers.getAllRawHeaders()) try: d = read_body_with_max_size(response, output_stream, max_size) d.addTimeout(self.default_timeout, self.reactor) length = await make_deferred_yieldable(d) except BodyExceededMaxSize: ...
from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent from synapse.http.federation.srv_resolver import Server from synapse.http.federation.well_known_resolver import ( WellKnownResolver, _cache_period_from_headers, )
from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent from synapse.http.federation.srv_resolver import Server from synapse.http.federation.well_known_resolver import ( WELL_KNOWN_MAX_SIZE, WellKnownResolver, _cache_period_from_headers, )
def test_well_known_cache_with_temp_failure(self): r = self.successResultOf(fetch_d) self.assertEqual(r.delegated_server, None) def test_srv_fallbacks(self): """Test that other SRV results are tried if the first one fails. """
def test_well_known_cache_with_temp_failure(self): r = self.successResultOf(fetch_d) self.assertEqual(r.delegated_server, None) def test_well_known_too_large(self): """A well-known query that returns a result which is too large should be rejected.""" self.reactor.lookups["testserv"]...
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = self.regex.search(path) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = ( self.regex.fullmatch(path) if self._is_endpoint and self.regex.pattern.endswith('$') else self.regex.search(path) ) if match: # If there are any n...
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append('$') return ''.join(parts), converters
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append(r'\Z') return ''.join(parts), converters
class SimplifiedURLTests(SimpleTestCase): with self.assertRaisesMessage(ImproperlyConfigured, msg): path('space/<int: num>', empty_view) @override_settings(ROOT_URLCONF='urlpatterns.converter_urls') class ConverterTests(SimpleTestCase):
class SimplifiedURLTests(SimpleTestCase): with self.assertRaisesMessage(ImproperlyConfigured, msg): path('space/<int: num>', empty_view) def test_path_trailing_newlines(self): tests = [ '/articles/2003/\n', '/articles/2010/\n', '/en/foo/\n', ...
_simple_palette = re.compile(b'^\xff+\x00\xff*$') # -------------------------------------------------------------------- # Support classes. Suitable for PNG and related formats like MNG etc.
_simple_palette = re.compile(b'^\xff+\x00\xff*$') # Maximum decompressed size for a iTXt or zTXt chunk. # Eliminates decompression bombs where compressed chunks can expand 1000x MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK # Set the maximum total text chunk size. MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK def _safe_zlib_decompre...
def __init__(self, fp): self.im_tile = None self.im_palette = None def chunk_iCCP(self, pos, length): # ICC profile
def __init__(self, fp): self.im_tile = None self.im_palette = None self.text_memory = 0 def check_text_memory(self, chunklen): self.text_memory += chunklen if self.text_memory > MAX_TEXT_MEMORY: raise ValueError("Too much memory used in text chunks: %s>MAX_TEXT_...
def chunk_iCCP(self, pos, length): raise SyntaxError("Unknown compression method %s in iCCP chunk" % comp_method) try: icc_profile = zlib.decompress(s[i+2:]) except zlib.error: icc_profile = None # FIXME self.im_info["icc_profile...
def chunk_iCCP(self, pos, length): raise SyntaxError("Unknown compression method %s in iCCP chunk" % comp_method) try: icc_profile = _safe_zlib_decompress(s[i+2:]) except zlib.error: icc_profile = None # FIXME self.im_info["icc_p...
def chunk_tEXt(self, pos, length): v = v.decode('latin-1', 'replace') self.im_info[k] = self.im_text[k] = v return s def chunk_zTXt(self, pos, length):
def chunk_tEXt(self, pos, length): v = v.decode('latin-1', 'replace') self.im_info[k] = self.im_text[k] = v self.check_text_memory(len(v)) return s def chunk_zTXt(self, pos, length):
def chunk_zTXt(self, pos, length): raise SyntaxError("Unknown compression method %s in zTXt chunk" % comp_method) try: v = zlib.decompress(v[1:]) except zlib.error: v = b""
def chunk_zTXt(self, pos, length): raise SyntaxError("Unknown compression method %s in zTXt chunk" % comp_method) try: v = _safe_zlib_decompress(v[1:]) except zlib.error: v = b""
def chunk_zTXt(self, pos, length): v = v.decode('latin-1', 'replace') self.im_info[k] = self.im_text[k] = v return s def chunk_iTXt(self, pos, length):
def chunk_zTXt(self, pos, length): v = v.decode('latin-1', 'replace') self.im_info[k] = self.im_text[k] = v self.check_text_memory(len(v)) return s def chunk_iTXt(self, pos, length):
def chunk_iTXt(self, pos, length): if cf != 0: if cm == 0: try: v = zlib.decompress(v) except zlib.error: return s else:
def chunk_iTXt(self, pos, length): if cf != 0: if cm == 0: try: v = _safe_zlib_decompress(v) except zlib.error: return s else:
def chunk_iTXt(self, pos, length): return s self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk) return s
def chunk_iTXt(self, pos, length): return s self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk) self.check_text_memory(len(v)) return s
def test_bad_itxt(self): im = load(HEAD + chunk(b'iTXt', b'spam\0\1\0en\0Spam\0' + zlib.compress(b"egg")[:1]) + TAIL) self.assertEqual(im.info, {}) im = load(HEAD + chunk(b'iTXt', b'spam\0\1\1en\0Spam\0' + zlib.compress(b"egg")) + T...
def test_bad_itxt(self): im = load(HEAD + chunk(b'iTXt', b'spam\0\1\0en\0Spam\0' + zlib.compress(b"egg")[:1]) + TAIL) self.assertEqual(im.info, {'spam':''}) im = load(HEAD + chunk(b'iTXt', b'spam\0\1\1en\0Spam\0' + zlib.compress(b"e...
import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, HttpResponseRedirect, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.http import http_date, parse_http_date from django.utils.six.moves.urllib.parse import unquote ...
import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils._os import safe_join from django.utils.http import http_date, parse_http_date from django.utils.six.moves.urllib.parse im...
def serve(request, path, document_root=None, show_indexes=False): but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not ...
def serve(request, path, document_root=None, show_indexes=False): but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)).lstrip('/') fullpath = safe_join(document_root, path) if os.path.isdir(fullpath): ...
class StaticTests(SimpleTestCase): def test_index(self): response = self.client.get('/%s/' % self.prefix) self.assertContains(response, 'Index of /') class StaticHelperTest(StaticTests):
class StaticTests(SimpleTestCase): def test_index(self): response = self.client.get('/%s/' % self.prefix) self.assertContains(response, 'Index of ./') class StaticHelperTest(StaticTests):
class CentralPlannerScheduler(Scheduler): tasks.sort(key=self._rank(), reverse=True) for task in tasks: in_workers = assistant or worker in task.workers if task.status == 'RUNNING' and in_workers: # Return a list of currently running tasks to the client, ...
class CentralPlannerScheduler(Scheduler): tasks.sort(key=self._rank(), reverse=True) for task in tasks: in_workers = (assistant and task.workers) or worker in task.workers if task.status == 'RUNNING' and in_workers: # Return a list of currently running tasks to t...
class CentralPlannerTest(unittest.TestCase): self.assertEqual(list(running_tasks.keys()), ['A']) self.assertEqual(running_tasks['A']['worker_running'], 'Y') def test_task_fails_when_assistant_dies(self): self.setTime(0) self.sch.add_task(worker='X', task_id='A')
class CentralPlannerTest(unittest.TestCase): self.assertEqual(list(running_tasks.keys()), ['A']) self.assertEqual(running_tasks['A']['worker_running'], 'Y') def test_assistant_get_work_external_task(self): self.sch.add_task('X', task_id='A', runnable=False) self.assertTrue(self.sch....
def _can_use_numexpr(op, op_str, a, b, dtype_check): # required min elements (otherwise we are adding overhead) if np.prod(a.shape) > _MIN_ELEMENTS: # check for dtype compatibility dtypes = set() for o in [a, b]: if hasattr(o, "dtypes"): ...
def _can_use_numexpr(op, op_str, a, b, dtype_check): # required min elements (otherwise we are adding overhead) if np.prod(a.shape) > _MIN_ELEMENTS: # check for dtype compatibility dtypes = set() for o in [a, b]: # Series implements dtypes, check for ...
class TestExpressions: operator_name = "truediv" if test_flex: op = lambda x, y: getattr(df, arith)(y) op.__name__ = arith else: op = getattr(operator, operator_name)
class TestExpressions: operator_name = "truediv" if test_flex: op = lambda x, y: getattr(x, arith)(y) op.__name__ = arith else: op = getattr(operator, operator_name)
class TestExpressions: for f in [self.frame, self.frame2, self.mixed, self.mixed2]: for cond in [True, False]: c = np.empty(f.shape, dtype=np.bool_) c.fill(cond) result = expr.where(c, f.values, f.values + 1)
class TestExpressions: for f in [self.frame, self.frame2, self.mixed, self.mixed2]: for cond in [True, False]: c = np.empty(f.shape, dtype=np.bool_) c.fill(cond) result = expr.where(c, f.values, f.values + 1)
class TestExpressions: # GH 22383 - .ne fails if columns containing column name 'dtype' result = test_input.loc[:, ["a", "dtype"]].ne(test_input.loc[:, ["a", "dtype"]]) assert_frame_equal(result, expected)
class TestExpressions: # GH 22383 - .ne fails if columns containing column name 'dtype' result = test_input.loc[:, ["a", "dtype"]].ne(test_input.loc[:, ["a", "dtype"]]) assert_frame_equal(result, expected) @pytest.mark.parametrize( "arith", ("add", "sub", "mul", "mod", "truediv", "f...
def get_response(args, config_dir): """Send the request and return a `request.Response`.""" requests_session = get_requests_session() if not args.session and not args.session_read_only: kwargs = get_requests_kwargs(args)
def get_response(args, config_dir): """Send the request and return a `request.Response`.""" requests_session = get_requests_session() requests_session.max_redirects = args.max_redirects if not args.session and not args.session_read_only: kwargs = get_requests_kwargs(args)
def main(args=sys.argv[1:], env=Environment(), error=None): error('Too many redirects (--max-redirects=%s).', args.max_redirects) except Exception as e: # TODO: Better distinction between expected and unexpected errors. # Network errors vs. bugs, etc. if traceback: ...
def main(args=sys.argv[1:], env=Environment(), error=None): error('Too many redirects (--max-redirects=%s).', args.max_redirects) except Exception as e: # TODO: Better distinction between expected and unexpected errors. if traceback: raise msg = str(e)
class TestRedirects: assert HTTP_OK in r def test_max_redirects(self, httpbin): r = http('--max-redirects=2', '--follow', httpbin.url + '/redirect/3', error_exit_ok=True) assert r.exit_status == ExitStatus.ERROR_TOO_MANY_REDIRECTS
class TestRedirects: assert HTTP_OK in r def test_max_redirects(self, httpbin): r = http('--max-redirects=1', '--follow', httpbin.url + '/redirect/3', error_exit_ok=True) assert r.exit_status == ExitStatus.ERROR_TOO_MANY_REDIRECTS
def test_match(stderr): def test_get_new_command(stderr): assert get_new_command(Command('git push', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_command(Command('git push -u origin', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_com...
def test_match(stderr): def test_get_new_command(stderr): assert get_new_command(Command('git push', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_command(Command('git push -u', stderr=stderr))\ == "git push --set-upstream origin master" assert get_new_command(Co...
def get_new_command(command): pass if upstream_option_index is not -1: command.script_parts.pop(upstream_option_index) command.script_parts.pop(upstream_option_index) push_upstream = command.stderr.split('\n')[-3].strip().partition('git ')[2] return replace_argument(" ".join(command...
def get_new_command(command): pass if upstream_option_index is not -1: command.script_parts.pop(upstream_option_index) try: command.script_parts.pop(upstream_option_index) except IndexError: # This happens for `git push -u` pass push_upstream ...
def repercent_broken_unicode(path): repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ try: path.decode() except UnicodeDecodeError as e: repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") path = repercent_brok...
def repercent_broken_unicode(path): repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ while True: try: path.decode() except UnicodeDecodeError as e: # CVE-2019-14235: A recursion shouldn't be used since the exceptio...
import datetime import unittest from unittest import mock from urllib.parse import quote_plus
import datetime import sys import unittest from unittest import mock from urllib.parse import quote_plus
from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_text, get_system_encoding, iri_to_uri, smart_bytes, smart_text, uri_to_iri, ) from django.utils.functional import Simp...
from urllib.parse import quote_plus from django.test import SimpleTestCase from django.utils.encoding import ( DjangoUnicodeDecodeError, escape_uri_path, filepath_to_uri, force_bytes, force_text, get_system_encoding, iri_to_uri, repercent_broken_unicode, smart_bytes, smart_text, uri_to_iri, ) from django.ut...
class TestEncodingUtils(SimpleTestCase): with mock.patch('locale.getdefaultlocale', side_effect=Exception): self.assertEqual(get_system_encoding(), 'ascii') class TestRFC3987IEncodingUtils(unittest.TestCase):
class TestEncodingUtils(SimpleTestCase): with mock.patch('locale.getdefaultlocale', side_effect=Exception): self.assertEqual(get_system_encoding(), 'ascii') def test_repercent_broken_unicode_recursion_error(self): # Prepare a string long enough to force a recursion error if the tested ...
def setUp(self): def tearDown(self): # wait on the server thread to terminate self.evt.wait(4.0) # XXX this code does not work, and in fact stop_serving doesn't exist. if not self.evt.is_set(): self.evt.set() stop_serving() raise RuntimeError("tim...
def setUp(self): def tearDown(self): # wait on the server thread to terminate self.evt.wait() # disable traceback reporting xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False
def test_unicode_host(self): server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) self.assertEqual(server.add("a", "\xe9"), "a\xe9") class MultiPathServerTestCase(BaseServerTestCase): threadFunc = staticmethod(http_multi_server) request_count = 2
def test_unicode_host(self): server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) self.assertEqual(server.add("a", "\xe9"), "a\xe9") def test_partial_post(self): # Check that a partial POST doesn't make the server loop: issue #14001. conn = http.client.HTTPConnection(A...
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) L.append(self.rfile.read(chunk_size)) size_remaining -= len(L[-1]) data = b''.join(L)
def do_POST(self): L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]...
class AuthenticationForm(forms.Form): if username is not None and password: self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: # An authentication backend may reject inactive users. Check # if the...
class AuthenticationForm(forms.Form): if username is not None and password: self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: raise forms.ValidationError( self.error_messages['invalid_login']...
class UserCreationFormTest(TestDataMixin, TestCase): ) class AuthenticationFormTest(TestDataMixin, TestCase): def test_invalid_username(self):
class UserCreationFormTest(TestDataMixin, TestCase): ) # To verify that the login form rejects inactive users, use an authentication # backend that allows them. @override_settings(AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.AllowAllUsersModelBackend']) class AuthenticationFormTest(TestDataMixin, Te...
class AuthenticationFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), [str(form.error_messages['inactive'])]) def test_login_failed(self): signal_calls = []
class AuthenticationFormTest(TestDataMixin, TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form.non_field_errors(), [str(form.error_messages['inactive'])]) # Use an authentication backend that rejects inactive users. @override_settings(AUTHENTICATION_BACKENDS=['django.contrib.aut...
def decode_raw(input_bytes, name=None): r"""Convert raw bytes from input tensor into numeric tensors. The input tensor is interpreted as a sequence of bytes. These bytes are then decoded as numbers in the format specified by `out_type`. >>> tf.io.decode_raw(tf.constant("1"), tf.uint8) <tf.Ten...
def decode_raw(input_bytes, name=None): r"""Convert raw bytes from input tensor into numeric tensors. Every component of the input tensor is interpreted as a sequence of bytes. These bytes are then decoded as numbers in the format specified by `out_type`. >>> tf.io.decode_raw(tf.constant("1"), ...
def decode_raw(input_bytes, >>> tf.io.decode_raw(tf.constant(["1212"]), tf.uint16, fixed_length=4) <tf.Tensor: shape=(1, 2), dtype=uint16, numpy=array([[12849, 12849]], ... Note: There is currently a bug in `fixed_length` that can result in data loss: >>> # truncated to length of type as it matches fixed_leng...
def decode_raw(input_bytes, >>> tf.io.decode_raw(tf.constant(["1212"]), tf.uint16, fixed_length=4) <tf.Tensor: shape=(1, 2), dtype=uint16, numpy=array([[12849, 12849]], ... If the input value is larger than `fixed_length`, it is truncated: >>> x=''.join([chr(1), chr(2), chr(3), chr(4)]) >>> tf.io.decode_raw...
import functools import inspect import logging import ssl import warnings import requests from requests import adapters try: from requests.packages.urllib3.exceptions import InsecureRequestWarning except ImportError:
import functools import inspect import logging import os import ssl import warnings import requests from requests import adapters from requests.adapters import DEFAULT_POOLBLOCK, DEFAULT_POOLSIZE, DEFAULT_RETRIES try: from requests.packages.urllib3.exceptions import InsecureRequestWarning except ImportError:
def wrapper(self, *args, **kwargs): class SSLContextAdapter(adapters.HTTPAdapter): """Custom SSLContext Adapter for requests """ def init_poolmanager(self, connections, maxsize, block=adapters.DEFAULT_POOLBLOCK, **pool_kwargs): context = ssl.SSLContext(
def wrapper(self, *args, **kwargs): class SSLContextAdapter(adapters.HTTPAdapter): """ Custom SSLContext Adapter for requests """ def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOL...
def init_poolmanager(self, connections, maxsize, if getattr(context, "post_handshake_auth", None) is not None: context.post_handshake_auth = True pool_kwargs['ssl_context'] = context return super().init_poolmanager( connections, maxsize, block, **pool_kwargs
def init_poolmanager(self, connections, maxsize, if getattr(context, "post_handshake_auth", None) is not None: context.post_handshake_auth = True # Load from the system trust store when possible; per documentation # this call could silently fail and refuse to configure any #...
class PKIConnection: def __init__(self, protocol='http', hostname='localhost', port='8080', subsystem=None, accept='application/json', trust_env=None, verify=False): """ Set the parameters for a python-requests based connection to a Dogtag subsystem.
class PKIConnection: def __init__(self, protocol='http', hostname='localhost', port='8080', subsystem=None, accept='application/json', trust_env=None, verify=True, cert_paths=None): """ Set the parameters for a python-requests based connection to a Dogtag s...
def __init__(self, protocol='http', hostname='localhost', port='8080', :param verify: verify TLS/SSL connections and configure CA certs (default: no) :type verify: None, bool, str :return: PKIConnection object. """
def __init__(self, protocol='http', hostname='localhost', port='8080', :param verify: verify TLS/SSL connections and configure CA certs (default: no) :type verify: None, bool, str :param cert_paths: paths to CA certificates / directories in OpenSSL format. (default: None) ...
def __init__(self, protocol='http', hostname='localhost', port='8080', self.serverURI = self.rootURI self.session = requests.Session() self.session.mount("https://", SSLContextAdapter()) self.session.trust_env = trust_env self.session.verify = verify
def __init__(self, protocol='http', hostname='localhost', port='8080', self.serverURI = self.rootURI self.session = requests.Session() self.session.mount("https://", SSLContextAdapter(verify=verify, cert_paths=cert_paths)) self.session.trust_env = trust_env self.session.veri...
class LSTMCell(Layer): inputs_f = inputs inputs_c = inputs inputs_o = inputs x_i = K.dot(inputs_i, self.kernel_i) + self.bias_i x_f = K.dot(inputs_f, self.kernel_f) + self.bias_f x_c = K.dot(inputs_c, self.kernel_c) + self.bias_c ...
class LSTMCell(Layer): inputs_f = inputs inputs_c = inputs inputs_o = inputs x_i = K.dot(inputs_i, self.kernel_i) x_f = K.dot(inputs_f, self.kernel_f) x_c = K.dot(inputs_c, self.kernel_c) x_o = K.dot(inputs_o, self.kernel_o)...
def test_implementation_mode(layer_class): 'dropout': 0.1, 'recurrent_dropout': 0.1}, input_shape=(num_samples, timesteps, embedding_dim)) @rnn_test
def test_implementation_mode(layer_class): 'dropout': 0.1, 'recurrent_dropout': 0.1}, input_shape=(num_samples, timesteps, embedding_dim)) # Without bias layer_test(layer_class, kwargs={'units': units, ...
from pipenv.patched import crayons from pipenv.utils import ( cmd_list_to_shell, convert_deps_to_pip, create_spinner, download_file, find_python, get_canonical_names, get_source_list, is_pinned, is_python_command, is_required_version, is_star, is_valid_url, parse_indexes, pep423_name, prepare_pip_source...
from pipenv.patched import crayons from pipenv.utils import ( cmd_list_to_shell, convert_deps_to_pip, create_spinner, download_file, find_python, get_canonical_names, get_host_and_port, get_source_list, is_pinned, is_python_command, is_required_version, is_star, is_valid_url, parse_indexes, pep423_name,...
def import_requirements(project, r=None, dev=False): if extra_index: indexes.append(extra_index) if trusted_host: trusted_hosts.append(trusted_host) indexes = sorted(set(indexes)) trusted_hosts = sorted(set(trusted_hosts)) reqs = [install_req_from_parsed_requirement(f...
def import_requirements(project, r=None, dev=False): if extra_index: indexes.append(extra_index) if trusted_host: trusted_hosts.append(get_host_and_port(trusted_host)) indexes = sorted(set(indexes)) trusted_hosts = sorted(set(trusted_hosts)) reqs = [install_req_from_p...
def import_requirements(project, r=None, dev=False): else: project.add_package_to_pipfile(str(package.req), dev=dev) for index in indexes: trusted = index in trusted_hosts project.add_index_to_pipfile(index, verify_ssl=trusted) project.recase_pipfile()
def import_requirements(project, r=None, dev=False): else: project.add_package_to_pipfile(str(package.req), dev=dev) for index in indexes: # don't require HTTPS for trusted hosts (see: https://pip.pypa.io/en/stable/cli/pip/#cmdoption-trusted-host) host_and_port = get_host...
def get_url_name(url): return urllib3_util.parse_url(url).host def get_canonical_names(packages): """Canonicalize a list of packages and return a set of canonical names""" from .vendor.packaging.utils import canonicalize_name
def get_url_name(url): return urllib3_util.parse_url(url).host def get_host_and_port(url): """Get the host, or the host:port pair if port is explicitly included, for the given URL. Examples: >>> get_host_and_port('example.com') 'example.com' >>> get_host_and_port('example.com:443') 'examp...
def test_convert_deps_to_pip_unicode(): ("--extra-index-url=https://example.com/simple/", (None, "https://example.com/simple/", None, [])), ("--trusted-host=example.com", (None, None, "example.com", [])), ("# -i https://example.com/simple/", (None, None, None, [])), ("requests", (None, None, None, ["req...
def test_convert_deps_to_pip_unicode(): ("--extra-index-url=https://example.com/simple/", (None, "https://example.com/simple/", None, [])), ("--trusted-host=example.com", (None, None, "example.com", [])), ("# -i https://example.com/simple/", (None, None, None, [])), ("requests # -i https://example.com/s...
from collections import namedtuple import re from ..exceptions import LocationParseError url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
from collections import namedtuple import re from ..exceptions import LocationParseError from ..packages.six.moves.urllib.parse import quote url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']
def parse_url(url): # Prevent CVE-2019-9740. # adapted from https://github.com/python/cpython/pull/12755 if _contains_disallowed_url_pchar_re.search(url): raise LocationParseError("URL can't contain control characters. {!r}".format(url)) scheme = None auth = None
def parse_url(url): # Prevent CVE-2019-9740. # adapted from https://github.com/python/cpython/pull/12755 url = _contains_disallowed_url_pchar_re.sub(lambda match: quote(match.group()), url) scheme = None auth = None
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') def test_parse_url_contains_control_characters(self): # see CVE-2019-9740 with pytest.raises(LocationParseError): parse_url('http://localhost:8000/ HTTP/1.1\r\nHEADER: INJECTED\r\nIgnore:') ...
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') @pytest.mark.parametrize('url, expected_url', [ ( 'http://localhost/ HTTP/1.1\r\nHEADER: INJECTED\r\nIgnore:', Url('http', host='localhost', port=None, path='/%20HTTP/1.1%0D...
class MWorker(salt.utils.process.SignalHandlingProcess): """ log.trace("Clear payload received with command %s", load["cmd"]) cmd = load["cmd"] if cmd.startswith("__"): return False if self.opts["master_stats"]: start = time.time() self.stats[c...
class MWorker(salt.utils.process.SignalHandlingProcess): """ log.trace("Clear payload received with command %s", load["cmd"]) cmd = load["cmd"] method = self.clear_funcs.get_method(cmd) if not method: return {}, {"fun": "send_clear"} if self.opts["master_stats...
class MWorker(salt.utils.process.SignalHandlingProcess): return {} cmd = data["cmd"] log.trace("AES payload received with command %s", data["cmd"]) if cmd.startswith("__"): return False if self.opts["master_stats"]: start = time.time() self...
class MWorker(salt.utils.process.SignalHandlingProcess): return {} cmd = data["cmd"] log.trace("AES payload received with command %s", data["cmd"]) method = self.aes_funcs.get_method(cmd) if not method: return {}, {"fun": "send"} if self.opts["master_stats...
class MWorker(salt.utils.process.SignalHandlingProcess): self.__bind() # TODO: rename? No longer tied to "AES", just "encrypted" or "private" requests class AESFuncs(object): """ Set up functions that are available when the load is encrypted with AES """ # The AES Functions: # def __i...
class MWorker(salt.utils.process.SignalHandlingProcess): self.__bind() class TransportMethods(object): """ Expose methods to the transport layer, methods with their names found in the class attribute 'expose_methods' will be exposed to the transport layer via 'get_method'. """ expose_...
class AESFuncs(object): return ret, {"fun": "send"} class ClearFuncs(object): """ Set up functions that are safe to execute when commands sent to the master without encryption and authentication """ # The ClearFuncs object encapsulates the functions that can be executed in # the clear...
class AESFuncs(object): return ret, {"fun": "send"} class ClearFuncs(TransportMethods): """ Set up functions that are safe to execute when commands sent to the master without encryption and authentication """ # These methods will be exposed to the transport layer by # MWorker._handle_...
from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf class ClearFuncsTestCase(TestCase): """ TestCase for salt.master.ClearFuncs class
from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf class TransportMethodsTest(TestCase): def test_transport_methods(self): class Foo(salt.master.TransportMethods): expose_methods = ["bar"] def bar(self): pass ...
class ClearFuncsTestCase(TestCase): def tearDownClass(cls): del cls.clear_funcs # runner tests @skipIf(True, "SLOWTEST skip")
class ClearFuncsTestCase(TestCase): def tearDownClass(cls): del cls.clear_funcs def tearDown(self): del self.clear_funcs def test_get_method(self): assert getattr(self.clear_funcs, "_send_pub", None) is not None assert self.clear_funcs.get_method("_send_pub") is None #...
def strip_tags(value): value = force_text(value) while '<' in value and '>' in value: new_value = _strip_once(value) if len(new_value) >= len(value): # _strip_once was not able to detect more tags or length increased # due to http://bugs.python.org/issue20288 ...
def strip_tags(value): value = force_text(value) while '<' in value and '>' in value: new_value = _strip_once(value) if len(new_value) >= len(value) or value.count('<') == new_value.count('<'): # _strip_once wasn't able to detect more tags, or line length increased. # due...
class TestUtilsHtml(SimpleTestCase): # caused infinite loop on Pythons not patched with # http://bugs.python.org/issue20288 ('&gotcha&#;<>', '&gotcha&#;<>'), ) for value, output in items: self.check_output(f, value, output)
class TestUtilsHtml(SimpleTestCase): # caused infinite loop on Pythons not patched with # http://bugs.python.org/issue20288 ('&gotcha&#;<>', '&gotcha&#;<>'), ('><!' + ('&' * 16000) + 'D', '><!' + ('&' * 16000) + 'D'), ('X<<<<br>br>br>br>X', 'XX'), ) ...
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...
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 ...
class _AxesBase(martist.Artist): return dL = self.dataLim x0, x1 = map(x_trf.inverted().transform, dL.intervalx) y0, y1 = map(y_trf.inverted().transform, dL.intervaly) xr = 1.05 * (x1 - x0) yr = 1.05 * (y1 - y0)
class _AxesBase(martist.Artist): return dL = self.dataLim x0, x1 = map(x_trf.transform, dL.intervalx) y0, y1 = map(y_trf.transform, dL.intervaly) xr = 1.05 * (x1 - x0) yr = 1.05 * (y1 - y0)
def test_aspect_nonlinear_adjustable_datalim(): ax = fig.add_axes([.1, .1, .8, .8]) # Square. ax.plot([.4, .6], [.4, .6]) # Set minpos to keep logit happy. ax.set(xscale="log", xlim=(1, 10), yscale="logit", ylim=(1/11, 1/1001), aspect=1, adjustable="datalim") ax.margins(0) a...
def test_aspect_nonlinear_adjustable_datalim(): ax = fig.add_axes([.1, .1, .8, .8]) # Square. ax.plot([.4, .6], [.4, .6]) # Set minpos to keep logit happy. ax.set(xscale="log", xlim=(1, 100), yscale="logit", ylim=(1 / 101, 1 / 11), aspect=1, adjustable="datalim") ax.margins(0) ...
def test_29248(self): target = os.readlink(r'C:\Users\All Users') self.assertTrue(os.path.samefile(target, r'C:\ProgramData')) @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") class Win32JunctionTests(unittest.TestCase):
def test_29248(self): target = os.readlink(r'C:\Users\All Users') self.assertTrue(os.path.samefile(target, r'C:\ProgramData')) def test_buffer_overflow(self): # Older versions would have a buffer overflow when detecting # whether a link source was a directory. This test ensures we ...
class SimpleTaskState(object): def get_necessary_tasks(self): necessary_tasks = set() for task in self.get_active_tasks(): if task.status not in (DONE, DISABLED) or \ getattr(task, 'scheduler_disable_time', None) is not None: necessary_tasks.update(tas...
class SimpleTaskState(object): def get_necessary_tasks(self): necessary_tasks = set() for task in self.get_active_tasks(): if task.status not in (DONE, DISABLED, UNKNOWN) or \ task.scheduler_disable_time is not None: necessary_tasks.update(task.deps) ...
from helpers import unittest from nose.plugins.attrib import attr import luigi.notifications from luigi.scheduler import DISABLED, DONE, FAILED, PENDING, CentralPlannerScheduler luigi.notifications.DEBUG = True WORKER = 'myworker'
from helpers import unittest from nose.plugins.attrib import attr import luigi.notifications from luigi.scheduler import DISABLED, DONE, FAILED, PENDING, \ UNKNOWN, CentralPlannerScheduler luigi.notifications.DEBUG = True WORKER = 'myworker'