gurudesh/pytracebugs huggingface dataset:
# Buggy code
def ignore_wrapper(*args, **kwargs):
    tracer.pause()
    ret = func(*args, **kwargs)
    tracer.resume()
    return ret


# Traceback (AttributeError)
Traceback (most recent call last):
File "C:/Users/PycharmProjects/oneway_test/test.py", line 12, in <module>
f()
File "D:\virtual\Envs\venv37\lib\site-packages\viztracer\decorator.py", line 17, in ignore_wrapper
tracer.pause()
AttributeError: 'NoneType' object has no attribute 'pause'

# Fixed code
def ignore_wrapper(*args, **kwargs):
    # We need this to keep trace a local variable
    t = tracer
    if not t:
        t = get_tracer()
        if not t:
            raise NameError("ignore_function only works with global tracer")
    t.pause()
    ret = func(*args, **kwargs)
    t.resume()
    return ret
# Buggy code
def run_code(self, code, global_dict):
    options = self.options
    verbose = self.verbose
    ofile = self.ofile

    tracer = VizTracer(
        tracer_entries=options.tracer_entries,
        verbose=verbose,
        output_file=ofile,
        max_stack_depth=options.max_stack_depth,
        exclude_files=options.exclude_files,
        include_files=options.include_files,
        ignore_c_function=options.ignore_c_function,
        ignore_non_file=options.ignore_non_file,
        log_return_value=options.log_return_value,
        log_function_args=options.log_function_args,
        log_print=options.log_print,
        log_gc=options.log_gc,
        novdb=options.novdb,
        pid_suffix=options.pid_suffix,
    )

    self.tracer = tracer

    builtins.__dict__["__viz_tracer__"] = tracer

    self.parent_pid = os.getpid()
    if options.log_multiprocess:
        if get_start_method() != "fork":
            return False, "Only fork based multiprocess is supported"
        self.patch_multiprocessing(tracer)

    def term_handler(signalnum, frame):
        self.exit_routine()

    signal.signal(signal.SIGTERM, term_handler)

    atexit.register(self.exit_routine)
    if options.log_sparse:
        tracer.enable = True
    else:
        tracer.start()
    exec(code, global_dict)
    tracer.stop()

    self.exit_routine()


# Traceback (AttributeError)
Traceback (most recent call last):
File "C:/Users/PycharmProjects/oneway_test/test.py", line 12, in <module>
f()
File "D:\virtual\Envs\venv37\lib\site-packages\viztracer\decorator.py", line 17, in ignore_wrapper
tracer.pause()
AttributeError: 'NoneType' object has no attribute 'pause'

# Fixed code
def run_code(self, code, global_dict):
    options = self.options
    verbose = self.verbose
    ofile = self.ofile

    tracer = VizTracer(
        tracer_entries=options.tracer_entries,
        verbose=verbose,
        output_file=ofile,
        max_stack_depth=options.max_stack_depth,
        exclude_files=options.exclude_files,
        include_files=options.include_files,
        ignore_c_function=options.ignore_c_function,
        ignore_non_file=options.ignore_non_file,
        log_return_value=options.log_return_value,
        log_function_args=options.log_function_args,
        log_print=options.log_print,
        log_gc=options.log_gc,
        novdb=options.novdb,
        pid_suffix=options.pid_suffix,
        register_global=True,
    )

    self.tracer = tracer

    self.parent_pid = os.getpid()
    if options.log_multiprocess:
        if get_start_method() != "fork":
            return False, "Only fork based multiprocess is supported"
        self.patch_multiprocessing(tracer)

    def term_handler(signalnum, frame):
        self.exit_routine()

    signal.signal(signal.SIGTERM, term_handler)

    atexit.register(self.exit_routine)
    if options.log_sparse:
        tracer.enable = True
    else:
        tracer.start()
    exec(code, global_dict)
    tracer.stop()

    self.exit_routine()
# Buggy code
def __init__(
    self,
    tracer_entries=1000000,
    verbose=1,
    max_stack_depth=-1,
    include_files=None,
    exclude_files=None,
    ignore_c_function=False,
    ignore_non_file=False,
    log_return_value=False,
    log_function_args=False,
    log_print=False,
    log_gc=False,
    novdb=False,
    pid_suffix=False,
    file_info=False,
    output_file="result.html",
):
    super().__init__(
        tracer_entries=tracer_entries,
        max_stack_depth=max_stack_depth,
        include_files=include_files,
        exclude_files=exclude_files,
        ignore_c_function=ignore_c_function,
        ignore_non_file=ignore_non_file,
        log_return_value=log_return_value,
        log_print=log_print,
        log_gc=log_gc,
        novdb=novdb,
        log_function_args=log_function_args,
    )
    self.verbose = verbose
    self.pid_suffix = pid_suffix
    self.file_info = file_info
    self.output_file = output_file
    self.system_print = None


# Traceback (AttributeError)
Traceback (most recent call last):
File "C:/Users/PycharmProjects/oneway_test/test.py", line 12, in <module>
f()
File "D:\virtual\Envs\venv37\lib\site-packages\viztracer\decorator.py", line 17, in ignore_wrapper
tracer.pause()
AttributeError: 'NoneType' object has no attribute 'pause'

# Fixed code
def __init__(
    self,
    tracer_entries=1000000,
    verbose=1,
    max_stack_depth=-1,
    include_files=None,
    exclude_files=None,
    ignore_c_function=False,
    ignore_non_file=False,
    log_return_value=False,
    log_function_args=False,
    log_print=False,
    log_gc=False,
    novdb=False,
    pid_suffix=False,
    file_info=False,
    register_global=True,
    output_file="result.html",
):
    super().__init__(
        tracer_entries=tracer_entries,
        max_stack_depth=max_stack_depth,
        include_files=include_files,
        exclude_files=exclude_files,
        ignore_c_function=ignore_c_function,
        ignore_non_file=ignore_non_file,
        log_return_value=log_return_value,
        log_print=log_print,
        log_gc=log_gc,
        novdb=novdb,
        log_function_args=log_function_args,
    )
    self.verbose = verbose
    self.pid_suffix = pid_suffix
    self.file_info = file_info
    self.output_file = output_file
    self.system_print = None
    if register_global:
        self.register_global()
# Buggy code
def build_unit(self, unit):
    output = super().build_unit(unit)
    try:
        converted_source = xliff_string_to_rich(unit.get_source_plurals())
        converted_target = xliff_string_to_rich(unit.get_target_plurals())
    except XMLSyntaxError:
        return output
    output.rich_source = converted_source
    output.set_rich_target(converted_target, self.language.code)
    return output


# Traceback (TypeError)
Traceback (most recent call last):
File "/var/lib/weblate/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/var/lib/weblate/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/var/lib/weblate/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/trans/views/files.py", line 99, in download_translation
return download_translation_file(obj, **kwargs)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/utils/views.py", line 197, in download_translation_file
exporter.add_units(units)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/formats/exporters.py", line 120, in add_units
self.add_unit(unit)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/formats/exporters.py", line 128, in add_unit
output = self.build_unit(unit)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/formats/exporters.py", line 262, in build_unit
converted_source = xliff_string_to_rich(unit.source)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/trans/util.py", line 303, in xliff_string_to_rich
return [parse_xliff(string)]
File "/var/lib/weblate/lib/python3.7/site-packages/translate/storage/placeables/lisa.py", line 218, in parse_xliff
return xml_to_strelem(etree.fromstring('<source>%s</source>' % (pstr), parser))
File "/var/lib/weblate/lib/python3.7/site-packages/translate/storage/placeables/lisa.py", line 112, in xml_to_strelem
sub.append(make_placeable(child_dom_node, xml_space))
File "/var/lib/weblate/lib/python3.7/site-packages/translate/storage/placeables/lisa.py", line 83, in make_placeable
_namespace, tag = misc.parse_tag(node.tag)
File "/var/lib/weblate/lib/python3.7/site-packages/translate/storage/xml_extract/misc.py", line 73, in parse_tag
match = tag_pattern.match(full_tag)

Exception Type: TypeError at /weblate/download/tdevelop/tdevelop/eo/
Exception Value: expected string or bytes-like object
Request information:
USER: Anonymous

GET:
format = 'xliff'
q = 'state:<translated'

POST: No POST data

FILES: No FILES data

COOKIES: No cookie data

# Fixed code
def build_unit(self, unit):
    output = super().build_unit(unit)
    try:
        converted_source = xliff_string_to_rich(unit.get_source_plurals())
        converted_target = xliff_string_to_rich(unit.get_target_plurals())
    except (XMLSyntaxError, TypeError):
        return output
    output.rich_source = converted_source
    output.set_rich_target(converted_target, self.language.code)
    return output
# Buggy code
def build_unit(self, unit):
    try:
        converted_source = xliff_string_to_rich(unit.source)
        converted_target = xliff_string_to_rich(unit.target)
    except XMLSyntaxError:
        return super().build_unit(unit)
    output = self.storage.UnitClass("")
    output.rich_source = converted_source
    output.set_rich_target(converted_target, self.language.code)
    return output


# Traceback (TypeError)
Traceback (most recent call last):
File "/var/lib/weblate/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/var/lib/weblate/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/var/lib/weblate/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/trans/views/files.py", line 99, in download_translation
return download_translation_file(obj, **kwargs)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/utils/views.py", line 197, in download_translation_file
exporter.add_units(units)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/formats/exporters.py", line 120, in add_units
self.add_unit(unit)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/formats/exporters.py", line 128, in add_unit
output = self.build_unit(unit)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/formats/exporters.py", line 262, in build_unit
converted_source = xliff_string_to_rich(unit.source)
File "/var/lib/weblate/lib/python3.7/site-packages/weblate/trans/util.py", line 303, in xliff_string_to_rich
return [parse_xliff(string)]
File "/var/lib/weblate/lib/python3.7/site-packages/translate/storage/placeables/lisa.py", line 218, in parse_xliff
return xml_to_strelem(etree.fromstring('<source>%s</source>' % (pstr), parser))
File "/var/lib/weblate/lib/python3.7/site-packages/translate/storage/placeables/lisa.py", line 112, in xml_to_strelem
sub.append(make_placeable(child_dom_node, xml_space))
File "/var/lib/weblate/lib/python3.7/site-packages/translate/storage/placeables/lisa.py", line 83, in make_placeable
_namespace, tag = misc.parse_tag(node.tag)
File "/var/lib/weblate/lib/python3.7/site-packages/translate/storage/xml_extract/misc.py", line 73, in parse_tag
match = tag_pattern.match(full_tag)

Exception Type: TypeError at /weblate/download/tdevelop/tdevelop/eo/
Exception Value: expected string or bytes-like object
Request information:
USER: Anonymous

GET:
format = 'xliff'
q = 'state:<translated'

POST: No POST data

FILES: No FILES data

COOKIES: No cookie data

# Fixed code
def build_unit(self, unit):
    try:
        converted_source = xliff_string_to_rich(unit.get_source_plurals())
        converted_target = xliff_string_to_rich(unit.get_target_plurals())
    except XMLSyntaxError:
        return super().build_unit(unit)
    output = self.storage.UnitClass("")
    output.rich_source = converted_source
    output.set_rich_target(converted_target, self.language.code)
    return output
# Buggy code
def get_queue_length(queue="celery"):
    with celery_app.connection_or_acquire() as conn:
        return conn.default_channel.queue_declare(
            queue=queue, durable=True, auto_delete=False
        ).message_count


# Traceback (FileNotFoundError)
[ 1221s] ======================================================================
[ 1221s] ERROR: test_digest (weblate.accounts.tests.test_notifications.NotificationTest)
[ 1221s] ----------------------------------------------------------------------
[ 1221s] Traceback (most recent call last):
[ 1221s]   File "/home/abuild/rpmbuild/BUILD/Weblate-3.10.3/weblate/accounts/tests/test_notifications.py", line 327, in test_digest
[ 1221s]     notify()
[ 1221s]   File "/usr/lib/python3.7/site-packages/celery/local.py", line 191, in __call__
[ 1221s]     return self._get_current_object()(*a, **kw)
[ 1221s]   File "/usr/lib/python3.7/site-packages/celery/app/task.py", line 392, in __call__
[ 1221s]     return self.run(*args, **kwargs)
[ 1221s]   File "/home/abuild/rpmbuild/BUILD/Weblate-3.10.3/weblate/accounts/tasks.py", line 95, in notify_daily
[ 1221s]     notify_digest('notify_daily')
[ 1221s]   File "/home/abuild/rpmbuild/BUILD/Weblate-3.10.3/weblate/accounts/tasks.py", line 90, in notify_digest
[ 1221s]     send_mails.delay(outgoing)
[ 1221s]   File "/usr/lib/python3.7/site-packages/celery/app/task.py", line 425, in delay
[ 1221s]     return self.apply_async(args, kwargs)
[ 1221s]   File "/usr/lib/python3.7/site-packages/celery/app/task.py", line 562, in apply_async
[ 1221s]     link=link, link_error=link_error, **options)
[ 1221s]   File "/usr/lib/python3.7/site-packages/celery/app/task.py", line 775, in apply
[ 1221s]     ret = tracer(task_id, args, kwargs, request)
[ 1221s]   File "/usr/lib/python3.7/site-packages/celery/app/trace.py", line 399, in trace_task
[ 1221s]     I, R, state, retval = on_error(task_request, exc, uuid)
[ 1221s]   File "/usr/lib/python3.7/site-packages/celery/app/trace.py", line 385, in trace_task
[ 1221s]     R = retval = fun(*args, **kwargs)
[ 1221s]   File "/home/abuild/rpmbuild/BUILD/Weblate-3.10.3/weblate/accounts/tasks.py", line 134, in send_mails
[ 1221s]     with open(filename, 'rb') as handle:
[ 1221s] FileNotFoundError: [Errno 2] No such file or directory: '/home/abuild/rpmbuild/BUILD/Weblate-3.10.3/data-test/static/email-logo.png'

# Fixed code
def get_queue_length(queue="celery"):
    with app.connection_or_acquire() as conn:
        return conn.default_channel.queue_declare(
            queue=queue, durable=True, auto_delete=False
        ).message_count
# Buggy code
def prefetch(self):
    return self.select_related("project")


# Traceback (TypeError)
weblate@jb9:~$ ./venv/bin/weblate list_versions
* Weblate 3.6.1
* Python 3.5.3
* Django 2.2.1
* Celery 4.3.0
* celery-batches 0.2
* six 1.12.0
* social-auth-core 3.2.0
* social-auth-app-django 3.1.0
* django-appconf 1.0.3
* translate-toolkit 2.3.1
* translation-finder 1.5
* Whoosh 2.7.4
* defusedxml 0.6.0
* Git 2.11.0
* Pillow 6.0.0
* python-dateutil 2.8.0
* lxml 4.3.3
* django-crispy-forms 1.7.2
* django_compressor 2.2
* djangorestframework 3.9.4
* user-agents 2.0
* jellyfish 0.7.1
* diff-match-patch 20121119
* pytz 2019.1
* pyuca 1.2
* python-bidi 0.4.0
* PyYAML 5.1
* hub 2.3.0-pre10
* Database backends: django.db.backends.postgresql_psycopg2
* Cache backends: avatar:FileBasedCache, default:RedisCache
* Celery: redis://127.0.0.1:6379/3, redis://127.0.0.1:6379/3, regular
* Platform: Linux 4.9.0-9-amd64 (x86_64)
Exception ignored in: <function WeakValueDictionary.__init__.<locals>.remove at 0x7f0db6159950>
Traceback (most recent call last):
File "/var/www/weblate/venv/lib/python3.5/weakref.py", line 117, in remove
TypeError: 'NoneType' object is not callable
Exception ignored in: <function WeakValueDictionary.__init__.<locals>.remove at 0x7f0db6159950>
Traceback (most recent call last):
File "/var/www/weblate/venv/lib/python3.5/weakref.py", line 117, in remove
TypeError: 'NoneType' object is not callable

# Fixed code
def prefetch(self):
    return self.select_related(
        "project",
        "linked_component",
        "linked_component__project",
    ).prefetch_related("alert_set")
# Buggy code
def prefetch(self):
    return self.select_related("component", "component__project", "language")


# Traceback (TypeError)
weblate@jb9:~$ ./venv/bin/weblate list_versions
* Weblate 3.6.1
* Python 3.5.3
* Django 2.2.1
* Celery 4.3.0
* celery-batches 0.2
* six 1.12.0
* social-auth-core 3.2.0
* social-auth-app-django 3.1.0
* django-appconf 1.0.3
* translate-toolkit 2.3.1
* translation-finder 1.5
* Whoosh 2.7.4
* defusedxml 0.6.0
* Git 2.11.0
* Pillow 6.0.0
* python-dateutil 2.8.0
* lxml 4.3.3
* django-crispy-forms 1.7.2
* django_compressor 2.2
* djangorestframework 3.9.4
* user-agents 2.0
* jellyfish 0.7.1
* diff-match-patch 20121119
* pytz 2019.1
* pyuca 1.2
* python-bidi 0.4.0
* PyYAML 5.1
* hub 2.3.0-pre10
* Database backends: django.db.backends.postgresql_psycopg2
* Cache backends: avatar:FileBasedCache, default:RedisCache
* Celery: redis://127.0.0.1:6379/3, redis://127.0.0.1:6379/3, regular
* Platform: Linux 4.9.0-9-amd64 (x86_64)
Exception ignored in: <function WeakValueDictionary.__init__.<locals>.remove at 0x7f0db6159950>
Traceback (most recent call last):
File "/var/www/weblate/venv/lib/python3.5/weakref.py", line 117, in remove
TypeError: 'NoneType' object is not callable
Exception ignored in: <function WeakValueDictionary.__init__.<locals>.remove at 0x7f0db6159950>
Traceback (most recent call last):
File "/var/www/weblate/venv/lib/python3.5/weakref.py", line 117, in remove
TypeError: 'NoneType' object is not callable

# Fixed code
def prefetch(self):
    return self.select_related(
        "component", "component__project", "language"
    ).prefetch_related("component__alert_set", "language__plural_set")
# Buggy code
def handle(self, *args, **options):
    fulltext = Fulltext()
    # Optimize index
    if options["optimize"]:
        self.optimize_index(fulltext)
        return
    # Optionally rebuild indices from scratch
    if options["clean"]:
        fulltext.cleanup()

    if options["all"]:
        self.process_all(fulltext)
    else:
        self.process_filtered(fulltext, **options)


# Traceback (AttributeError)
Process Process-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/multiprocessing/process.py", line 254, in _bootstrap
self.run()
File "/usr/local/lib/python3.5/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.5/site-packages/weblate/trans/models/unit.py", line 68, in more_like_queue
result = more_like(pk, source, top)
File "/usr/local/lib/python3.5/site-packages/weblate/trans/search.py", line 304, in more_like
index = get_source_index()
File "/usr/local/lib/python3.5/site-packages/weblate/trans/search.py", line 122, in get_source_index
exists = STORAGE.index_exists('source')
File "/usr/local/lib/python3.5/site-packages/whoosh/filedb/filestore.py", line 189, in index_exists
ix = self.open_index(indexname)
File "/usr/local/lib/python3.5/site-packages/whoosh/filedb/filestore.py", line 176, in open_index
return indexclass(self, schema=schema, indexname=indexname)
File "/usr/local/lib/python3.5/site-packages/whoosh/index.py", line 421, in __init__
TOC.read(self.storage, self.indexname, schema=self._schema)
File "/usr/local/lib/python3.5/site-packages/whoosh/index.py", line 664, in read
segments = stream.read_pickle()
File "/usr/local/lib/python3.5/site-packages/whoosh/filedb/structfile.py", line 245, in read_pickle
return load_pickle(self.file)
AttributeError: Can't get attribute 'W3Segment' on <module 'whoosh.codec.whoosh3' from '/usr/local/lib/python3.5/site-packages/whoosh/codec/whoosh3.py'>
ERROR Handled exception Exception: b'Request timed out.'
ERROR Failed to fetch translations from Weblate similarity
ERROR Last fetched URL: None, params: None

# Fixed code
def handle(self, *args, **options):
    # Optimize index
    if options["optimize"]:
        optimize_fulltext()
        return
    fulltext = Fulltext()
    # Optionally rebuild indices from scratch
    if options["clean"]:
        fulltext.cleanup()

    if options["all"]:
        self.process_all(fulltext)
    else:
        self.process_filtered(fulltext, **options)
# Buggy code
def set_export_url(apps, schema_editor):
    SubProject = apps.get_model("trans", "SubProject")
    matching = SubProject.objects.filter(vcs__in=SUPPORTED_VCS).exclude(
        repo__startswith="weblate:/"
    )
    for component in matching:
        new_url = get_export_url(component)
        if component.git_export != new_url:
            component.git_export = new_url
            component.save()


# Traceback (django.db.migrations.exceptions.InconsistentMigrationHistory)
/usr/share/weblate# ./manage.py migrate
Traceback (most recent call last):
File "./manage.py", line 31, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 86, in handle
executor.loader.check_consistent_history(connection)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 298, in check_consistent_history
connection.alias,
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration trans.0131_auto_20180416_1610 is applied before its dependency gitexport.0001_initial on database 'default'.

# Fixed code
def set_export_url(apps, schema_editor):
    Component = apps.get_model("trans", "Component")
    matching = Component.objects.filter(vcs__in=SUPPORTED_VCS).exclude(
        repo__startswith="weblate:/"
    )
    for component in matching:
        new_url = get_export_url(component)
        if component.git_export != new_url:
            component.git_export = new_url
            component.save()
# Buggy code
def forwards(apps, schema_editor):
    change_foreign_keys(apps, schema_editor, "auth", "User", "weblate_auth", "User")
    change_foreign_keys(apps, schema_editor, "auth", "Group", "weblate_auth", "Group")


# Traceback (ValueError)
Operations to perform:
Apply all migrations: accounts, addons, admin, auth, authtoken, checks, contenttypes, lang, memory, permissions, screenshots, sessions, sites, social_django, trans, weblate_auth, wladmin
Running migrations:
Applying weblate_auth.0007_auto_20180509_0739...Traceback (most recent call last):
File "./manage.py", line 31, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/special.py", line 193, in database_forwards
self.code(from_state.apps, schema_editor)
File "/usr/share/weblate/weblate/auth/migrations/0007_auto_20180509_0739.py", line 14, in forwards
"weblate_auth", "Group")
File "/usr/share/weblate/weblate/auth/migrations/0007_auto_20180509_0739.py", line 83, in change_foreign_keys
schema_editor.alter_field(fk_field.model, old_field, new_field, strict=True)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 515, in alter_field
old_db_params, new_db_params, strict)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 529, in _alter_field
old_field.column,
ValueError: Found wrong number (0) of foreign key constraints for weblate_auth_autogroup.group_id

# Fixed code
def forwards(apps, schema_editor):
    change_foreign_keys(apps, schema_editor, "auth", "User", "weblate_auth", "User")
# Buggy code
def backwards(apps, schema_editor):
    change_foreign_keys(apps, schema_editor, "weblate_auth", "User", "auth", "User")
    change_foreign_keys(apps, schema_editor, "weblate_auth", "Group", "auth", "Group")


# Traceback (ValueError)
Operations to perform:
Apply all migrations: accounts, addons, admin, auth, authtoken, checks, contenttypes, lang, memory, permissions, screenshots, sessions, sites, social_django, trans, weblate_auth, wladmin
Running migrations:
Applying weblate_auth.0007_auto_20180509_0739...Traceback (most recent call last):
File "./manage.py", line 31, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/special.py", line 193, in database_forwards
self.code(from_state.apps, schema_editor)
File "/usr/share/weblate/weblate/auth/migrations/0007_auto_20180509_0739.py", line 14, in forwards
"weblate_auth", "Group")
File "/usr/share/weblate/weblate/auth/migrations/0007_auto_20180509_0739.py", line 83, in change_foreign_keys
schema_editor.alter_field(fk_field.model, old_field, new_field, strict=True)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 515, in alter_field
old_db_params, new_db_params, strict)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 529, in _alter_field
old_field.column,
ValueError: Found wrong number (0) of foreign key constraints for weblate_auth_autogroup.group_id

# Fixed code
def backwards(apps, schema_editor):
    change_foreign_keys(apps, schema_editor, "weblate_auth", "User", "auth", "User")
# Buggy code
def merge_upload(
    self,
    request,
    fileobj,
    overwrite,
    author=None,
    merge_header=True,
    method="translate",
    fuzzy="",
):
    """Top level handler for file uploads."""
    filecopy = fileobj.read()
    fileobj.close()

    # Strip possible UTF-8 BOM
    if filecopy[:3] == codecs.BOM_UTF8:
        filecopy = filecopy[3:]

    # Load backend file
    store = try_load(
        fileobj.name,
        filecopy,
        self.subproject.file_format_cls,
        self.subproject.template_store,
    )

    # Optionally set authorship
    if author is None:
        author = get_author_name(request.user)

    # Check valid plural forms
    if hasattr(store.store, "parseheader"):
        header = store.store.parseheader()
        if (
            "Plural-Forms" in header
            and self.language.get_plural_form() != header["Plural-Forms"]
        ):
            raise Exception("Plural forms do not match the language.")

    if method in ("translate", "fuzzy"):
        # Merge on units level
        with self.subproject.repository.lock:
            return self.merge_translations(
                request,
                store,
                overwrite,
                (method == "fuzzy"),
                fuzzy,
                merge_header,
            )

    # Add as sugestions
    return self.merge_suggestions(request, store, fuzzy)


# Traceback (Exception)
Traceback (most recent call last):
File "/home/nijel/weblate_hosted/weblate/trans/views/files.py", line 118, in upload_translation
fuzzy=form.cleaned_data['fuzzy'],
File "/home/nijel/weblate_hosted/weblate/trans/models/translation.py", line 1122, in merge_upload
raise Exception('Plural forms do not match the language.')
Exception: Plural forms do not match the language.

# Fixed code
def merge_upload(
    self,
    request,
    fileobj,
    overwrite,
    author=None,
    merge_header=True,
    method="translate",
    fuzzy="",
):
    """Top level handler for file uploads."""
    filecopy = fileobj.read()
    fileobj.close()

    # Strip possible UTF-8 BOM
    if filecopy[:3] == codecs.BOM_UTF8:
        filecopy = filecopy[3:]

    # Load backend file
    store = try_load(
        fileobj.name,
        filecopy,
        self.subproject.file_format_cls,
        self.subproject.template_store,
    )

    # Optionally set authorship
    if author is None:
        author = get_author_name(request.user)

    # Check valid plural forms
    if hasattr(store.store, "parseheader"):
        header = store.store.parseheader()
        if "Plural-Forms" in header and not self.language.same_plural(
            header["Plural-Forms"]
        ):
            raise Exception("Plural forms do not match the language.")

    if method in ("translate", "fuzzy"):
        # Merge on units level
        with self.subproject.repository.lock:
            return self.merge_translations(
                request,
                store,
                overwrite,
                (method == "fuzzy"),
                fuzzy,
                merge_header,
            )

    # Add as sugestions
    return self.merge_suggestions(request, store, fuzzy)
# Buggy code
def get_clean_env(extra=None):
    """
    Returns cleaned up environment for subprocess execution.
    """
    environ = {}
    if extra is not None:
        environ.update(extra)
    variables = ("HOME", "PATH", "LANG", "LD_LIBRARY_PATH")
    for var in variables:
        if var in os.environ:
            environ[var] = os.environ[var]
    return environ


# Traceback (AttributeError)
Traceback (most recent call last):
File "./manage.py", line 31, in <module>
execute_from_command_line(sys.argv)
File "/var/www/my.website.com/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/var/www/my.website.com/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 303, in execute
settings.INSTALLED_APPS
File "/var/www/my.website.com/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/var/www/my.website.com/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/var/www/my.website.com/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 92, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/var/www/my.website.com/weblate/weblate/__init__.py", line 26, in <module>
from weblate.requirements import (
File "/var/www/my.website.com/weblate/weblate/requirements.py", line 24, in <module>
from weblate.trans.vcs import GitRepository, HgRepository
File "/var/www/my.website.com/weblate/weblate/trans/vcs.py", line 632, in <module>
class HgRepository(Repository):
File "/var/www/my.website.com/weblate/weblate/trans/vcs.py", line 44, in register_vcs
if vcs.is_supported():
File "/var/www/my.website.com/weblate/weblate/trans/vcs.py", line 263, in is_supported
version = cls.get_version()
File "/var/www/my.website.com/weblate/weblate/trans/vcs.py", line 288, in get_version
cls._version = cls._get_version()
File "/var/www/my.website.com/weblate/weblate/trans/vcs.py", line 855, in _get_version
return cls.VERSION_RE.match(output).group(1)
AttributeError: 'NoneType' object has no attribute 'group'

# Fixed code
def get_clean_env(extra=None):
    """
    Returns cleaned up environment for subprocess execution.
    """
    environ = {"LANG": "en_US.UTF-8"}
    if extra is not None:
        environ.update(extra)
    variables = ("HOME", "PATH", "LD_LIBRARY_PATH")
    for var in variables:
        if var in os.environ:
            environ[var] = os.environ[var]
    return environ
# Buggy code
def _get_version(cls):
    """
    Returns VCS program version.
    """
    output = cls._popen(["version", "-q"])
    return cls.VERSION_RE.match(output).group(1)


# Traceback (AttributeError)
Traceback (most recent call last):
File "./manage.py", line 31, in <module>
execute_from_command_line(sys.argv)
File "/var/www/my.website.com/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/var/www/my.website.com/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 303, in execute
settings.INSTALLED_APPS
File "/var/www/my.website.com/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/var/www/my.website.com/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/var/www/my.website.com/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 92, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/var/www/my.website.com/weblate/weblate/__init__.py", line 26, in <module>
from weblate.requirements import (
File "/var/www/my.website.com/weblate/weblate/requirements.py", line 24, in <module>
from weblate.trans.vcs import GitRepository, HgRepository
File "/var/www/my.website.com/weblate/weblate/trans/vcs.py", line 632, in <module>
class HgRepository(Repository):
File "/var/www/my.website.com/weblate/weblate/trans/vcs.py", line 44, in register_vcs
if vcs.is_supported():
File "/var/www/my.website.com/weblate/weblate/trans/vcs.py", line 263, in is_supported
version = cls.get_version()
File "/var/www/my.website.com/weblate/weblate/trans/vcs.py", line 288, in get_version
cls._version = cls._get_version()
File "/var/www/my.website.com/weblate/weblate/trans/vcs.py", line 855, in _get_version
return cls.VERSION_RE.match(output).group(1)
AttributeError: 'NoneType' object has no attribute 'group'

# Fixed code
def _get_version(cls):
    """
    Returns VCS program version.
    """
    output = cls._popen(["version", "-q"])
    matches = cls.VERSION_RE.match(output)
    if matches is None:
        raise OSError("Failed to parse version string: {0}".format(output))
    return matches.group(1)
# Buggy code
def notify_user(self, notification, translation_obj, context=None, headers=None):
    """
    Wrapper for sending notifications to user.
    """
    if context is None:
        context = {}
    if headers is None:
        headers = {}

    # Check whether user is still allowed to access this project
    if not translation_obj.has_acl(self):
        return
    # Actually send notification
    send_notification_email(
        self.language, self.user.email, notification, translation_obj, context, headers
    )


# Traceback (AttributeError)
Traceback (most recent call last):
File "/XXXXXXXX/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)

File "/XXXXXXXX/weblate/trans/views.py", line 1370, in translate
subscription.notify_new_suggestion(obj, sug, unit)

File "/XXXXXXXX/weblate/accounts/models.py", line 300, in notify_new_suggestion
'unit': unit,

File "/XXXXXXXX/weblate/accounts/models.py", line 253, in notify_user
if not translation_obj.has_acl(self):

File "/XXXXXXXX/weblate/trans/models.py", line 1320, in has_acl
return self.subproject.project.has_acl(user)

File "/XXXXXXXX/weblate/trans/models.py", line 184, in has_acl
if user is None or not user.is_authenticated():

AttributeError: 'Profile' object has no attribute 'is_authenticated'

# Fixed code
def notify_user(self, notification, translation_obj, context=None, headers=None):
    """
    Wrapper for sending notifications to user.
    """
    if context is None:
        context = {}
    if headers is None:
        headers = {}

    # Check whether user is still allowed to access this project
    if not translation_obj.has_acl(self.user):
        return
    # Actually send notification
    send_notification_email(
        self.language, self.user.email, notification, translation_obj, context, headers
    )
# Buggy code
def update_subproject(request, project, subproject):
    """
    API hook for updating git repos.
    """
    if not settings.ENABLE_HOOKS:
        return HttpResponseNotAllowed([])
    obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
    thread = threading.Thread(target=obj.do_update)
    thread.start()
    return HttpResponse("update triggered")


# Traceback (AttributeError)
Traceback (most recent call last):

File "/srv/weblate/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/srv/weblate/src/weblate/weblate/trans/views.py", line 1395, in translate
saved = unit.save_backend(request)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 2478, in save_backend
self.translation.update_lock(request)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1463, in update_lock
self.create_lock(request.user)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1434, in create_lock
self.update_lock_time(explicit, is_new)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1443, in update_lock_time
seconds = settings.AUTO_LOCK_TIME
File "/srv/weblate/local/lib/python2.7/site-packages/django/utils/functional.py", line 185, in inner
return func(self._wrapped, *args)
AttributeError: 'Settings' object has no attribute 'AUTO_LOCK_TIME'

# Fixed code
def update_subproject(request, project, subproject):
    """
    API hook for updating git repos.
    """
    if not appsettings.ENABLE_HOOKS:
        return HttpResponseNotAllowed([])
    obj = get_object_or_404(SubProject, slug=subproject, project__slug=project)
    thread = threading.Thread(target=obj.do_update)
    thread.start()
    return HttpResponse("update triggered")
# Buggy code
def update_project(request, project):
    """
    API hook for updating git repos.
    """
    if not settings.ENABLE_HOOKS:
        return HttpResponseNotAllowed([])
    obj = get_object_or_404(Project, slug=project)
    thread = threading.Thread(target=obj.do_update)
    thread.start()
    return HttpResponse("update triggered")


# Traceback (AttributeError)
Traceback (most recent call last):

File "/srv/weblate/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/srv/weblate/src/weblate/weblate/trans/views.py", line 1395, in translate
saved = unit.save_backend(request)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 2478, in save_backend
self.translation.update_lock(request)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1463, in update_lock
self.create_lock(request.user)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1434, in create_lock
self.update_lock_time(explicit, is_new)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1443, in update_lock_time
seconds = settings.AUTO_LOCK_TIME
File "/srv/weblate/local/lib/python2.7/site-packages/django/utils/functional.py", line 185, in inner
return func(self._wrapped, *args)
AttributeError: 'Settings' object has no attribute 'AUTO_LOCK_TIME'

# Fixed code
def update_project(request, project):
    """
    API hook for updating git repos.
    """
    if not appsettings.ENABLE_HOOKS:
        return HttpResponseNotAllowed([])
    obj = get_object_or_404(Project, slug=project)
    thread = threading.Thread(target=obj.do_update)
    thread.start()
    return HttpResponse("update triggered")
# Buggy code
def github_hook(request):
    """
    API to handle commit hooks from Github.
    """
    if not settings.ENABLE_HOOKS:
        return HttpResponseNotAllowed([])
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])
    try:
        data = json.loads(request.POST["payload"])
    except (ValueError, KeyError):
        return HttpResponseBadRequest("could not parse json!")
    try:
        repo = "git://github.com/%s/%s.git" % (
            data["repository"]["owner"]["name"],
            data["repository"]["name"],
        )
        branch = data["ref"].split("/")[-1]
    except KeyError:
        return HttpResponseBadRequest("could not parse json!")
    logger.info(
        "received GitHub notification on repository %s, branch %s", repo, branch
    )
    for obj in SubProject.objects.filter(repo=repo, branch=branch):
        logger.info("GitHub notification will update %s", obj)
        thread = threading.Thread(target=obj.do_update)
        thread.start()

    return HttpResponse("update triggered")


# Traceback (AttributeError)
Traceback (most recent call last):

File "/srv/weblate/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/srv/weblate/src/weblate/weblate/trans/views.py", line 1395, in translate
saved = unit.save_backend(request)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 2478, in save_backend
self.translation.update_lock(request)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1463, in update_lock
self.create_lock(request.user)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1434, in create_lock
self.update_lock_time(explicit, is_new)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1443, in update_lock_time
seconds = settings.AUTO_LOCK_TIME
File "/srv/weblate/local/lib/python2.7/site-packages/django/utils/functional.py", line 185, in inner
return func(self._wrapped, *args)
AttributeError: 'Settings' object has no attribute 'AUTO_LOCK_TIME'

# Fixed code
def github_hook(request):
    """
    API to handle commit hooks from Github.
    """
    if not appsettings.ENABLE_HOOKS:
        return HttpResponseNotAllowed([])
    if request.method != "POST":
        return HttpResponseNotAllowed(["POST"])
    try:
        data = json.loads(request.POST["payload"])
    except (ValueError, KeyError):
        return HttpResponseBadRequest("could not parse json!")
    try:
        repo = "git://github.com/%s/%s.git" % (
            data["repository"]["owner"]["name"],
            data["repository"]["name"],
        )
        branch = data["ref"].split("/")[-1]
    except KeyError:
        return HttpResponseBadRequest("could not parse json!")
    logger.info(
        "received GitHub notification on repository %s, branch %s", repo, branch
    )
    for obj in SubProject.objects.filter(repo=repo, branch=branch):
        logger.info("GitHub notification will update %s", obj)
        thread = threading.Thread(target=obj.do_update)
        thread.start()

    return HttpResponse("update triggered")
# Buggy code
def title(request):
    return {"site_title": settings.SITE_TITLE}


# Traceback (AttributeError)
Traceback (most recent call last):

File "/srv/weblate/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/srv/weblate/src/weblate/weblate/trans/views.py", line 1395, in translate
saved = unit.save_backend(request)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 2478, in save_backend
self.translation.update_lock(request)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1463, in update_lock
self.create_lock(request.user)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1434, in create_lock
self.update_lock_time(explicit, is_new)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1443, in update_lock_time
seconds = settings.AUTO_LOCK_TIME
File "/srv/weblate/local/lib/python2.7/site-packages/django/utils/functional.py", line 185, in inner
return func(self._wrapped, *args)
AttributeError: 'Settings' object has no attribute 'AUTO_LOCK_TIME'

# Fixed code
def title(request):
    return {"site_title": appsettings.SITE_TITLE}
# Buggy code
def mt(request):
    return {
        "apertium_api_key": settings.MT_APERTIUM_KEY,
        "microsoft_api_key": settings.MT_MICROSOFT_KEY,
    }


# Traceback (AttributeError)
Traceback (most recent call last):

File "/srv/weblate/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/srv/weblate/src/weblate/weblate/trans/views.py", line 1395, in translate
saved = unit.save_backend(request)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 2478, in save_backend
self.translation.update_lock(request)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1463, in update_lock
self.create_lock(request.user)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1434, in create_lock
self.update_lock_time(explicit, is_new)
File "/srv/weblate/src/weblate/weblate/trans/models.py", line 1443, in update_lock_time
seconds = settings.AUTO_LOCK_TIME
File "/srv/weblate/local/lib/python2.7/site-packages/django/utils/functional.py", line 185, in inner
return func(self._wrapped, *args)
AttributeError: 'Settings' object has no attribute 'AUTO_LOCK_TIME'

# Fixed code
def mt(request):
    return {
        "apertium_api_key": appsettings.MT_APERTIUM_KEY,
        "microsoft_api_key": appsettings.MT_MICROSOFT_KEY,
    }