gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_jk(
    self,
    dm,
    hermi=1,
    kpts=None,
    kpts_band=None,
    with_j=True,
    with_k=True,
    exxdiv="ewald",
):
    if kpts is None:
        if numpy.all(self.kpts == 0):
            # Gamma-point calculation by default
            kpts = numpy.zeros(3)
        else:
            kpts = self.kpts

    if kpts.shape == (3,):
        return aft_jk.get_jk(self, dm, hermi, kpts, kpts_band, with_j, with_k, exxdiv)

    vj = vk = None
    if with_k:
        vk = aft_jk.get_k_kpts(self, dm, hermi, kpts, kpts_band, exxdiv)
    if with_j:
        vj = aft_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
    return vj, vk


# Traceback (IndexError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 1476, in kernel
return self.scf(dm0, **kwargs)
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 1470, in scf
conv_check=self.conv_check, **kwargs)
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 143, in kernel
vhf = mf.get_veff(mol, dm)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/scf/krohf.py", line 335, in get_veff
vj, vk = self.get_jk(cell, dm_kpts, hermi, kpts, kpts_band)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/scf/khf.py", line 493, in get_jk
exxdiv=self.exxdiv)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/df/fft.py", line 288, in get_jk
vj = fft_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/df/fft_jk.py", line 67, in get_j_kpts
rhoR[i,p0:p1] += make_rho(i, ao_ks, mask, 'LDA')
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/dft/numint.py", line 1222, in make_rho
hermi=1)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/dft/numint.py", line 1086, in eval_rho
rhoR += eval_rho(cell, ao_kpts[k], dm_kpts[k], non0tab, xctype,
IndexError: index 2 is out of bounds for axis 0 with size 2

# Fixed code
def get_jk(
    self, dm, hermi=1, kpts=None, kpts_band=None, with_j=True, with_k=True, exxdiv=None
):
    if kpts is None:
        if numpy.all(self.kpts == 0):
            # Gamma-point calculation by default
            kpts = numpy.zeros(3)
        else:
            kpts = self.kpts

    if kpts.shape == (3,):
        return aft_jk.get_jk(self, dm, hermi, kpts, kpts_band, with_j, with_k, exxdiv)

    vj = vk = None
    if with_k:
        vk = aft_jk.get_k_kpts(self, dm, hermi, kpts, kpts_band, exxdiv)
    if with_j:
        vj = aft_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
    return vj, vk
# Buggy code
def get_jk(
    self,
    dm,
    hermi=1,
    kpts=None,
    kpts_band=None,
    with_j=True,
    with_k=True,
    exxdiv="ewald",
):
    if kpts is None:
        if numpy.all(self.kpts == 0):
            # Gamma-point calculation by default
            kpts = numpy.zeros(3)
        else:
            kpts = self.kpts
    kpts = numpy.asarray(kpts)

    if kpts.shape == (3,):
        return df_jk.get_jk(self, dm, hermi, kpts, kpts_band, with_j, with_k, exxdiv)

    vj = vk = None
    if with_k:
        vk = df_jk.get_k_kpts(self, dm, hermi, kpts, kpts_band, exxdiv)
    if with_j:
        vj = df_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
    return vj, vk


# Traceback (IndexError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 1476, in kernel
return self.scf(dm0, **kwargs)
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 1470, in scf
conv_check=self.conv_check, **kwargs)
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 143, in kernel
vhf = mf.get_veff(mol, dm)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/scf/krohf.py", line 335, in get_veff
vj, vk = self.get_jk(cell, dm_kpts, hermi, kpts, kpts_band)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/scf/khf.py", line 493, in get_jk
exxdiv=self.exxdiv)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/df/fft.py", line 288, in get_jk
vj = fft_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/df/fft_jk.py", line 67, in get_j_kpts
rhoR[i,p0:p1] += make_rho(i, ao_ks, mask, 'LDA')
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/dft/numint.py", line 1222, in make_rho
hermi=1)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/dft/numint.py", line 1086, in eval_rho
rhoR += eval_rho(cell, ao_kpts[k], dm_kpts[k], non0tab, xctype,
IndexError: index 2 is out of bounds for axis 0 with size 2

# Fixed code
def get_jk(
    self, dm, hermi=1, kpts=None, kpts_band=None, with_j=True, with_k=True, exxdiv=None
):
    if kpts is None:
        if numpy.all(self.kpts == 0):
            # Gamma-point calculation by default
            kpts = numpy.zeros(3)
        else:
            kpts = self.kpts
    kpts = numpy.asarray(kpts)

    if kpts.shape == (3,):
        return df_jk.get_jk(self, dm, hermi, kpts, kpts_band, with_j, with_k, exxdiv)

    vj = vk = None
    if with_k:
        vk = df_jk.get_k_kpts(self, dm, hermi, kpts, kpts_band, exxdiv)
    if with_j:
        vj = df_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
    return vj, vk
# Buggy code
def get_jk(
    self,
    dm,
    hermi=1,
    kpts=None,
    kpts_band=None,
    with_j=True,
    with_k=True,
    exxdiv="ewald",
):
    from pyscf.pbc.df import fft_jk

    if kpts is None:
        if numpy.all(self.kpts == 0):
            # Gamma-point calculation by default
            kpts = numpy.zeros(3)
        else:
            kpts = self.kpts
    else:
        kpts = numpy.asarray(kpts)

    vj = vk = None
    if kpts.shape == (3,):
        vj, vk = fft_jk.get_jk(self, dm, hermi, kpts, kpts_band, with_j, with_k, exxdiv)
    else:
        if with_k:
            vk = fft_jk.get_k_kpts(self, dm, hermi, kpts, kpts_band, exxdiv)
        if with_j:
            vj = fft_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
    return vj, vk


# Traceback (IndexError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 1476, in kernel
return self.scf(dm0, **kwargs)
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 1470, in scf
conv_check=self.conv_check, **kwargs)
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 143, in kernel
vhf = mf.get_veff(mol, dm)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/scf/krohf.py", line 335, in get_veff
vj, vk = self.get_jk(cell, dm_kpts, hermi, kpts, kpts_band)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/scf/khf.py", line 493, in get_jk
exxdiv=self.exxdiv)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/df/fft.py", line 288, in get_jk
vj = fft_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/df/fft_jk.py", line 67, in get_j_kpts
rhoR[i,p0:p1] += make_rho(i, ao_ks, mask, 'LDA')
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/dft/numint.py", line 1222, in make_rho
hermi=1)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/dft/numint.py", line 1086, in eval_rho
rhoR += eval_rho(cell, ao_kpts[k], dm_kpts[k], non0tab, xctype,
IndexError: index 2 is out of bounds for axis 0 with size 2

# Fixed code
def get_jk(
    self, dm, hermi=1, kpts=None, kpts_band=None, with_j=True, with_k=True, exxdiv=None
):
    from pyscf.pbc.df import fft_jk

    if kpts is None:
        if numpy.all(self.kpts == 0):
            # Gamma-point calculation by default
            kpts = numpy.zeros(3)
        else:
            kpts = self.kpts
    else:
        kpts = numpy.asarray(kpts)

    vj = vk = None
    if kpts.shape == (3,):
        vj, vk = fft_jk.get_jk(self, dm, hermi, kpts, kpts_band, with_j, with_k, exxdiv)
    else:
        if with_k:
            vk = fft_jk.get_k_kpts(self, dm, hermi, kpts, kpts_band, exxdiv)
        if with_j:
            vj = fft_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
    return vj, vk
# Buggy code
def get_jk(
    self,
    dm,
    hermi=1,
    kpts=None,
    kpts_band=None,
    with_j=True,
    with_k=True,
    exxdiv="ewald",
):
    if kpts is None:
        if numpy.all(self.kpts == 0):
            # Gamma-point calculation by default
            kpts = numpy.zeros(3)
        else:
            kpts = self.kpts
    kpts = numpy.asarray(kpts)

    if kpts.shape == (3,):
        return mdf_jk.get_jk(self, dm, hermi, kpts, kpts_band, with_j, with_k, exxdiv)

    vj = vk = None
    if with_k:
        vk = mdf_jk.get_k_kpts(self, dm, hermi, kpts, kpts_band, exxdiv)
    if with_j:
        vj = mdf_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
    return vj, vk


# Traceback (IndexError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 1476, in kernel
return self.scf(dm0, **kwargs)
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 1470, in scf
conv_check=self.conv_check, **kwargs)
File "/home/gagliard/phamx494/pyscf/pyscf/scf/hf.py", line 143, in kernel
vhf = mf.get_veff(mol, dm)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/scf/krohf.py", line 335, in get_veff
vj, vk = self.get_jk(cell, dm_kpts, hermi, kpts, kpts_band)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/scf/khf.py", line 493, in get_jk
exxdiv=self.exxdiv)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/df/fft.py", line 288, in get_jk
vj = fft_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/df/fft_jk.py", line 67, in get_j_kpts
rhoR[i,p0:p1] += make_rho(i, ao_ks, mask, 'LDA')
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/dft/numint.py", line 1222, in make_rho
hermi=1)
File "/home/gagliard/phamx494/pyscf/pyscf/pbc/dft/numint.py", line 1086, in eval_rho
rhoR += eval_rho(cell, ao_kpts[k], dm_kpts[k], non0tab, xctype,
IndexError: index 2 is out of bounds for axis 0 with size 2

# Fixed code
def get_jk(
    self, dm, hermi=1, kpts=None, kpts_band=None, with_j=True, with_k=True, exxdiv=None
):
    if kpts is None:
        if numpy.all(self.kpts == 0):
            # Gamma-point calculation by default
            kpts = numpy.zeros(3)
        else:
            kpts = self.kpts
    kpts = numpy.asarray(kpts)

    if kpts.shape == (3,):
        return mdf_jk.get_jk(self, dm, hermi, kpts, kpts_band, with_j, with_k, exxdiv)

    vj = vk = None
    if with_k:
        vk = mdf_jk.get_k_kpts(self, dm, hermi, kpts, kpts_band, exxdiv)
    if with_j:
        vj = mdf_jk.get_j_kpts(self, dm, hermi, kpts, kpts_band)
    return vj, vk
# Buggy code
def create_thumbnail(fname, file_ext):
    thumb_size = (255, 160)
    thumb = Image.open(fname)
    thumb.thumbnail(thumb_size)
    thumb_hash = hashlib.sha256(thumb.tobytes()).hexdigest()
    thumbhashpath = f"{thumb_hash[0:2]}/{thumb_hash[2:4]}"
    thumbpath = os.path.join(
        current_app.config["MEDIA_DIRECTORY"], "thumbs", thumbhashpath
    )
    # makedirs attempts to make every directory necessary to get to the "thumbs" folder
    os.makedirs(thumbpath, exist_ok=True)
    fname = os.path.join(thumbpath, thumb_hash + file_ext)
    thumb.save(fname)
    thumb.close()
    return thumb_hash


# Traceback (PIL.UnidentifiedImageError)
[2020-07-25 00:22:59,784] ERROR in app: Exception on /api/submit [POST]
Traceback (most recent call last):
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/.venv/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/natlas/natlas-server/app/auth/wrappers.py", line 49, in decorated_function
return f(*args, **kwargs)
File "/opt/natlas/natlas-server/app/api/routes.py", line 187, in submit
newhost["screenshots"], newhost["num_screenshots"] = process_screenshots(
File "/opt/natlas/natlas-server/app/api/processing/screenshot.py", line 52, in process_screenshots
item["thumb_hash"] = create_thumbnail(fname, file_ext)
File "/opt/natlas/natlas-server/app/api/processing/screenshot.py", line 10, in create_thumbnail
thumb = Image.open(fname)
File "/.venv/lib/python3.8/site-packages/PIL/Image.py", line 2895, in open
raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file '/data/media/original/e3/b0/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.png'

# Fixed code
def create_thumbnail(fname, file_ext):
    thumb_size = (255, 160)
    thumb = Image.open(fname)
    thumb.thumbnail(thumb_size)
    thumb_hash = hashlib.sha256(thumb.tobytes()).hexdigest()
    fname = get_file_path(thumb_hash, "thumbs", file_ext)
    thumb.save(fname)
    thumb.close()
    return thumb_hash
# Buggy code
def process_screenshots(screenshots):
    # Handle screenshots

    num_screenshots = 0
    for item in screenshots:
        if item["service"] == "VNC":
            file_ext = ".jpg"
        else:  # Handles http, https files from aquatone/chromium-headless
            file_ext = ".png"

        image = base64.b64decode(item["data"])
        image_hash = hashlib.sha256(image).hexdigest()

        hashpath = f"{image_hash[0:2]}/{image_hash[2:4]}"
        dirpath = os.path.join(
            current_app.config["MEDIA_DIRECTORY"], "original", hashpath
        )

        # makedirs attempts to make every directory necessary to get to the "original" folder
        os.makedirs(dirpath, exist_ok=True)

        fname = os.path.join(dirpath, image_hash + file_ext)
        with open(fname, "wb") as f:
            f.write(image)
        item["hash"] = image_hash
        del item["data"]

        item["thumb_hash"] = create_thumbnail(fname, file_ext)
        num_screenshots += 1

    return screenshots, num_screenshots


# Traceback (PIL.UnidentifiedImageError)
[2020-07-25 00:22:59,784] ERROR in app: Exception on /api/submit [POST]
Traceback (most recent call last):
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/.venv/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/natlas/natlas-server/app/auth/wrappers.py", line 49, in decorated_function
return f(*args, **kwargs)
File "/opt/natlas/natlas-server/app/api/routes.py", line 187, in submit
newhost["screenshots"], newhost["num_screenshots"] = process_screenshots(
File "/opt/natlas/natlas-server/app/api/processing/screenshot.py", line 52, in process_screenshots
item["thumb_hash"] = create_thumbnail(fname, file_ext)
File "/opt/natlas/natlas-server/app/api/processing/screenshot.py", line 10, in create_thumbnail
thumb = Image.open(fname)
File "/.venv/lib/python3.8/site-packages/PIL/Image.py", line 2895, in open
raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file '/data/media/original/e3/b0/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.png'

# Fixed code
def process_screenshots(screenshots: list) -> tuple:
    processed_screenshots = []
    for item in screenshots:
        screenshot = process_screenshot(item)
        if not screenshot:
            current_app.logger.warning(
                f"Received invalid image for {screenshot['hostname']} port {screenshot['port']}"
            )
            continue
        processed_screenshots.append(item)

    return processed_screenshots, len(processed_screenshots)
# Buggy code
def execute_delete_by_query(self, **kwargs):
    """Executes an arbitrary delete_by_query."""
    with self._new_trace_span(operation="delete_by", **kwargs) as span:
        results = self._execute_raw_query(
            self.es.delete_by_query, doc_type="_doc", **kwargs
        )
        self._attach_shard_span_attrs(span, results)
        return results


# Traceback (KeyError)
172.18.0.1 - - [26/Jun/2020 08:50:28] "POST /admin/scans/delete/60ab2a6a40250d8c6c13e9f6d1a39e84 HTTP/1.1" 500 -
Traceback (most recent call last):
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/.venv/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/.venv/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/.venv/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/.venv/lib/python3.8/site-packages/flask_login/utils.py", line 272, in decorated_view
return func(*args, **kwargs)
File "/opt/natlas/natlas-server/app/auth/wrappers.py", line 38, in decorated_function
return f(*args, **kwargs)
File "/opt/natlas/natlas-server/app/admin/routes.py", line 463, in delete_scan
deleted = current_app.elastic.delete_scan(scan_id)
File "/opt/natlas/natlas-server/app/elastic/interface.py", line 153, in delete_scan
result = self.client.execute_delete_by_query(
File "/opt/natlas/natlas-server/app/elastic/client.py", line 132, in execute_delete_by_query
self._attach_shard_span_attrs(span, results)
File "/opt/natlas/natlas-server/app/elastic/client.py", line 165, in _attach_shard_span_attrs
span.add_attribute("es.shards.total", results["_shards"]["total"])
KeyError: '_shards'

# Fixed code
def execute_delete_by_query(self, **kwargs):
    """Executes an arbitrary delete_by_query."""
    with self._new_trace_span(operation="delete_by", **kwargs):
        results = self._execute_raw_query(
            self.es.delete_by_query, doc_type="_doc", **kwargs
        )
        return results
# Buggy code
def index():
    return redirect(url_for("main.search"))


# Traceback (TypeError)
Nov 05 17:22:50 natlas-server bash[10026]: [2019-11-05 17:22:50,681] ERROR in app: Exception on /api/getwork [GET]
Nov 05 17:22:50 natlas-server bash[10026]: Traceback (most recent call last):
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
Nov 05 17:22:50 natlas-server bash[10026]:     response = self.full_dispatch_request()
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
Nov 05 17:22:50 natlas-server bash[10026]:     rv = self.handle_user_exception(e)
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
Nov 05 17:22:50 natlas-server bash[10026]:     reraise(exc_type, exc_value, tb)
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
Nov 05 17:22:50 natlas-server bash[10026]:     raise value
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
Nov 05 17:22:50 natlas-server bash[10026]:     rv = self.dispatch_request()
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/venv/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
Nov 05 17:22:50 natlas-server bash[10026]:     return self.view_functions[rule.endpoint](**req.view_args)
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/app/auth/wrappers.py", line 41, in decorated_function
Nov 05 17:22:50 natlas-server bash[10026]:     return f(*args, **kwargs)
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/app/api/routes.py", line 70, in getwork
Nov 05 17:22:50 natlas-server bash[10026]:     count, context = current_app.elastic.gethost_scan_id(rand)
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/app/elastic.py", line 238, in gethost_scan_id
Nov 05 17:22:50 natlas-server bash[10026]:     if not self.checkStatus():
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/app/elastic.py", line 60, in checkStatus
Nov 05 17:22:50 natlas-server bash[10026]:     if not self.attemptReconnect():
Nov 05 17:22:50 natlas-server bash[10026]:   File "/opt/natlas/natlas-server/app/elastic.py", line 43, in attemptReconnect
Nov 05 17:22:50 natlas-server bash[10026]:     delta = now - self.lastReconnectAttempt
Nov 05 17:22:50 natlas-server bash[10026]: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType

# Fixed code
def index():
    return redirect(url_for("main.browse"))
# Buggy code
def cleanup_files(scan_id):
    print_info("Cleaning up files for %s" % scan_id)
    for file in glob.glob("data/*." + scan_id + ".*"):
        os.remove(file)


# Traceback (IsADirectoryError)
[!] (3ud7hcwtnz) Killing slacker process
[!] Thread-2: Failed to acquire HTTPS screenshot for 178.128.187.177
[+] Thread-2: Cleaning up files for 3ud7hcwtnz
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "./natlas-agent.py", line 359, in run
result = scan(target_data)
File "./natlas-agent.py", line 335, in scan
cleanup_files(scan_id)
File "./natlas-agent.py", line 181, in cleanup_files
os.remove(file)
IsADirectoryError: [Errno 21] Is a directory: 'data/aquatone.3ud7hcwtnz.https'

# Fixed code
def cleanup_files(scan_id):
    print_info("Cleaning up files for %s" % scan_id)
    if os.path.isdir("data/aquatone.%s" % scan_id):
        shutil.rmtree("data/aquatone.%s" % scan_id)
    for file in glob.glob("data/natlas." + scan_id + ".*"):
        try:
            os.remove(file)
        except:
            print_err("Could not remove file %s" % file)
# Buggy code
def backoff_request(giveup=False, *args, **kwargs):
    attempt = 0
    result = None
    while not result:
        result = make_request(*args, **kwargs)
        RETRY = False

        if not result:
            RETRY = True
        if "retry" in result.json() and result.json()["retry"]:
            RETRY = True
        elif not "retry" in result.json() or not result.json()["retry"]:
            return result

        if RETRY:
            attempt += 1
            if giveup and attempt == config.max_retries:
                print_err(
                    "Request to %s failed %s times. Giving up"
                    % (config.server, config.max_retries)
                )
                return None
            jitter = (
                random.randint(0, 1000) / 1000
            )  # jitter to reduce chance of locking
            current_sleep = (
                min(config.backoff_max, config.backoff_base * 2**attempt) + jitter
            )
            print_err(
                "Request to %s failed. Waiting %s seconds before retrying."
                % (config.server, current_sleep)
            )
            time.sleep(current_sleep)
    return result


# Traceback (AttributeError)
[!] Thread-2: Expected 200, received 502
[!] Thread-2: Error: Expecting value: line 1 column 1 (char 0)
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "./natlas-agent.py", line 359, in run
result = scan(target_data)
File "./natlas-agent.py", line 286, in scan
response = backoff_request(giveup=True, endpoint="/api/submit", reqType="POST", postData=json.dumps(result))
File "./natlas-agent.py", line 117, in backoff_request
if 'retry' in result.json() and result.json()['retry']:
AttributeError: 'bool' object has no attribute 'json'

# Fixed code
def backoff_request(giveup=False, *args, **kwargs):
    attempt = 0
    result = None
    while not result:
        result = make_request(*args, **kwargs)
        RETRY = False

        if not result:
            RETRY = True
        elif "retry" in result.json() and result.json()["retry"]:
            RETRY = True
        elif not "retry" in result.json() or not result.json()["retry"]:
            return result

        if RETRY:
            attempt += 1
            if giveup and attempt == config.max_retries:
                print_err(
                    "Request to %s failed %s times. Giving up"
                    % (config.server, config.max_retries)
                )
                return None
            jitter = (
                random.randint(0, 1000) / 1000
            )  # jitter to reduce chance of locking
            current_sleep = (
                min(config.backoff_max, config.backoff_base * 2**attempt) + jitter
            )
            print_err(
                "Request to %s failed. Waiting %s seconds before retrying."
                % (config.server, current_sleep)
            )
            time.sleep(current_sleep)
    return result
# Buggy code
def getUser(self, username, **kwargs) -> dict:
    """Gets the full exposed user object

    :param username: The username of the user.
    :param language: The 2 letter code of the language to return.
                     Note: Doesn't seem to have an affect.
    :param proxy: The IP address of a proxy to make requests from.
    """
    (
        region,
        language,
        proxy,
        maxCount,
        did,
    ) = self.__process_kwargs__(kwargs)
    kwargs["custom_did"] = did
    query = {"uniqueId": username, "language": language}
    api_url = "{}api/user/detail/?{}&{}".format(
        BASE_URL, self.__add_new_params__(), urlencode(query)
    )

    return self.getData(url=api_url, **kwargs)["userInfo"]


# Traceback (json.decoder.JSONDecodeError)
Invalid Response
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 162, in getData
return r.json()
File "/home/user/.local/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/user/tiktok/tiktokhelper.py", line 33, in addUser
data = api.getUser(uniqueId)
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 1010, in getUser
return self.getData(url=api_url, **kwargs)["userInfo"]
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 170, in getData
raise Exception("Invalid Response")
Exception: Invalid Response

# Fixed code
def getUser(self, username, **kwargs) -> dict:
    """Gets the full exposed user object

    :param username: The username of the user.
    :param language: The 2 letter code of the language to return.
                     Note: Doesn't seem to have an affect.
    :param proxy: The IP address of a proxy to make requests from.
    """
    (
        region,
        language,
        proxy,
        maxCount,
        did,
    ) = self.__process_kwargs__(kwargs)
    kwargs["custom_did"] = did
    query = {"language": language}
    api_url = "{}node/share/user/@{}?{}&{}".format(
        BASE_URL, quote(username), self.__add_new_params__(), urlencode(query)
    )

    return self.getData(url=api_url, **kwargs)["userInfo"]
# Buggy code
def update_messager():
    # if not check("TikTokApi"):
    # Outdated
    #    print("TikTokApi package is outdated, please consider upgrading! \n(You can suppress this by setting ignore_version to True while calling the TikTok Api class)")

    if not check_future_deprecation():
        print(
            "Your version of python is going to be deprecated, for future updates upgrade to 3.7+"
        )


# Traceback (json.decoder.JSONDecodeError)
Invalid Response
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 162, in getData
return r.json()
File "/home/user/.local/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/user/tiktok/tiktokhelper.py", line 33, in addUser
data = api.getUser(uniqueId)
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 1010, in getUser
return self.getData(url=api_url, **kwargs)["userInfo"]
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 170, in getData
raise Exception("Invalid Response")
Exception: Invalid Response

# Fixed code
def update_messager():
    if not check("TikTokApi"):
        # Outdated
        print(
            "TikTokApi package is outdated, please consider upgrading! \n(You can suppress this by setting ignore_version=True in the TikTokApi constructor)"
        )

    if not check_future_deprecation():
        print(
            "Your version of python is going to be deprecated, for future updates upgrade to 3.7+"
        )
# Buggy code
def getMusicObject(self, id, **kwargs) -> dict:
    """Returns a music object for a specific sound id.

    :param id: The sound id to search by.
    :param language: The 2 letter code of the language to return.
                     Note: Doesn't seem to have an affect.
    :param proxy: The IP address of a proxy to make requests from.
    """
    (
        region,
        language,
        proxy,
        maxCount,
        did,
    ) = self.__process_kwargs__(kwargs)
    kwargs["custom_did"] = did

    query = {"musicId": id, "language": language}
    api_url = "{}api/music/detail/?{}&{}".format(
        BASE_URL, self.__add_new_params__(), urlencode(query)
    )

    return self.getData(url=api_url, **kwargs)


# Traceback (json.decoder.JSONDecodeError)
Invalid Response
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 162, in getData
return r.json()
File "/home/user/.local/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/user/tiktok/tiktokhelper.py", line 33, in addUser
data = api.getUser(uniqueId)
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 1010, in getUser
return self.getData(url=api_url, **kwargs)["userInfo"]
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 170, in getData
raise Exception("Invalid Response")
Exception: Invalid Response

# Fixed code
def getMusicObject(self, id, **kwargs) -> dict:
    """Returns a music object for a specific sound id.

    :param id: The sound id to search by.
    :param language: The 2 letter code of the language to return.
                     Note: Doesn't seem to have an affect.
    :param proxy: The IP address of a proxy to make requests from.
    """
    (
        region,
        language,
        proxy,
        maxCount,
        did,
    ) = self.__process_kwargs__(kwargs)
    kwargs["custom_did"] = did

    query = {"musicId": id, "language": language}
    api_url = "{}node/share/music/{}?{}&{}".format(
        BASE_URL,
        self.get_music_title(id) + "-" + str(id),
        self.__add_new_params__(),
        urlencode(query),
    )

    return self.getData(url=api_url, **kwargs)
# Buggy code
def getHashtagObject(self, hashtag, **kwargs) -> dict:
    """Returns a hashtag object.

    :param hashtag: The hashtag to search by.
    :param language: The 2 letter code of the language to return.
                     Note: Doesn't seem to have an affect.
    :param proxy: The IP address of a proxy to make requests from.
    """
    (
        region,
        language,
        proxy,
        maxCount,
        did,
    ) = self.__process_kwargs__(kwargs)
    kwargs["custom_did"] = did
    query = {"challengeName": hashtag, "language": language}
    api_url = "{}api/challenge/detail/?{}&{}".format(
        BASE_URL, self.__add_new_params__(), urlencode(query)
    )
    return self.getData(url=api_url, **kwargs)


# Traceback (json.decoder.JSONDecodeError)
Invalid Response
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 162, in getData
return r.json()
File "/home/user/.local/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/user/tiktok/tiktokhelper.py", line 33, in addUser
data = api.getUser(uniqueId)
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 1010, in getUser
return self.getData(url=api_url, **kwargs)["userInfo"]
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 170, in getData
raise Exception("Invalid Response")
Exception: Invalid Response

# Fixed code
def getHashtagObject(self, hashtag, **kwargs) -> dict:
    """Returns a hashtag object.

    :param hashtag: The hashtag to search by.
    :param language: The 2 letter code of the language to return.
                     Note: Doesn't seem to have an affect.
    :param proxy: The IP address of a proxy to make requests from.
    """
    (
        region,
        language,
        proxy,
        maxCount,
        did,
    ) = self.__process_kwargs__(kwargs)
    kwargs["custom_did"] = did
    query = {"name": hashtag, "isName": True, "lang": language}
    api_url = "{}node/share/tag/{}?{}&{}".format(
        BASE_URL, quote(hashtag), self.__add_new_params__(), urlencode(query)
    )
    return self.getData(url=api_url, **kwargs)
# Buggy code
def getHashtagDetails(self, hashtag, **kwargs) -> dict:
    """Returns a hashtag object.

    :param hashtag: The hashtag to search by.
    :param language: The 2 letter code of the language to return.
                     Note: Doesn't seem to have an affect.
    :param proxy: The IP address of a proxy to make requests from.
    """
    (
        region,
        language,
        proxy,
        maxCount,
        did,
    ) = self.__process_kwargs__(kwargs)
    kwargs["custom_did"] = did
    query = {"language": language}
    api_url = "{}node/share/tag/{}?{}&{}".format(
        BASE_URL, quote(hashtag), self.__add_new_params__(), urlencode(query)
    )

    return self.getData(url=api_url, **kwargs)


# Traceback (json.decoder.JSONDecodeError)
Invalid Response
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 162, in getData
return r.json()
File "/home/user/.local/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/user/tiktok/tiktokhelper.py", line 33, in addUser
data = api.getUser(uniqueId)
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 1010, in getUser
return self.getData(url=api_url, **kwargs)["userInfo"]
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 170, in getData
raise Exception("Invalid Response")
Exception: Invalid Response

# Fixed code
def getHashtagDetails(self, hashtag, **kwargs) -> dict:
    """Returns a hashtag object.

    :param hashtag: The hashtag to search by.
    :param language: The 2 letter code of the language to return.
                     Note: Doesn't seem to have an affect.
    :param proxy: The IP address of a proxy to make requests from.
    """
    logging.warning(
        "The getHashtagDetails will be deprecated in a future version. Replace it with getHashtagObject"
    )
    (
        region,
        language,
        proxy,
        maxCount,
        did,
    ) = self.__process_kwargs__(kwargs)
    kwargs["custom_did"] = did
    query = {"lang": language}
    api_url = "{}node/share/tag/{}?{}&{}".format(
        BASE_URL, quote(hashtag), self.__add_new_params__(), urlencode(query)
    )

    return self.getData(url=api_url, **kwargs)
# Buggy code
def __add_new_params__(self) -> str:
    query = {
        "aid": 1988,
        "app_name": "tiktok_web",
        "device_platform": "web",
        "referer": "https://www.tiktok.com/",
        "user_agent": self.__format_new_params__(self.userAgent),
        "cookie_enabled": "true",
        "screen_width": self.width,
        "screen_height": self.height,
        "browser_language": self.browser_language,
        "browser_platform": self.browser_platform,
        "browser_name": self.browser_name,
        "browser_version": self.browser_version,
        "browser_online": "true",
        "ac": "4g",
        "timezone_name": self.timezone_name,
        "appId": 1233,
        "appType": "m",
        "isAndroid": False,
        "isMobile": False,
        "isIOS": False,
        "OS": "windows",
    }
    return urlencode(query)


# Traceback (json.decoder.JSONDecodeError)
Invalid Response
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 162, in getData
return r.json()
File "/home/user/.local/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/user/tiktok/tiktokhelper.py", line 33, in addUser
data = api.getUser(uniqueId)
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 1010, in getUser
return self.getData(url=api_url, **kwargs)["userInfo"]
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 170, in getData
raise Exception("Invalid Response")
Exception: Invalid Response

# Fixed code
def __add_new_params__(self) -> str:
    query = {
        "aid": 1988,
        "app_name": "tiktok_web",
        "device_platform": "web",
        "referer": "https://www.tiktok.com/",
        "user_agent": self.__format_new_params__(self.userAgent),
        "cookie_enabled": "true",
        "screen_width": self.width,
        "screen_height": self.height,
        "browser_language": self.browser_language,
        "browser_platform": self.browser_platform,
        "browser_name": self.browser_name,
        "browser_version": self.browser_version,
        "browser_online": "true",
        "ac": "4g",
        "timezone_name": self.timezone_name,
        "appId": 1233,
        "appType": "m",
        "isAndroid": False,
        "isMobile": False,
        "isIOS": False,
        "OS": "windows",
        "page_referer": "https://www.tiktok.com/",
    }
    return urlencode(query)
# Buggy code
def getUser(self, username, **kwargs) -> dict:
    """Gets the full exposed user object

    :param username: The username of the user.
    :param language: The 2 letter code of the language to return.
                     Note: Doesn't seem to have an affect.
    :param proxy: The IP address of a proxy to make requests from.
    """
    (
        region,
        language,
        proxy,
        maxCount,
        did,
    ) = self.__process_kwargs__(kwargs)
    kwargs["custom_did"] = did
    query = {"language": language}
    api_url = "{}node/share/user/@{}?{}&{}".format(
        BASE_URL, quote(username), self.__add_new_params__(), urlencode(query)
    )

    return self.getData(url=api_url, **kwargs)["userInfo"]


# Traceback (json.decoder.JSONDecodeError)
Invalid Response
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 162, in getData
return r.json()
File "/home/user/.local/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/user/tiktok/tiktokhelper.py", line 33, in addUser
data = api.getUser(uniqueId)
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 1010, in getUser
return self.getData(url=api_url, **kwargs)["userInfo"]
File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 170, in getData
raise Exception("Invalid Response")
Exception: Invalid Response

# Fixed code
def getUser(self, username, **kwargs) -> dict:
    """Gets the full exposed user object

    :param username: The username of the user.
    :param language: The 2 letter code of the language to return.
                     Note: Doesn't seem to have an affect.
    :param proxy: The IP address of a proxy to make requests from.
    """
    (
        region,
        language,
        proxy,
        maxCount,
        did,
    ) = self.__process_kwargs__(kwargs)
    kwargs["custom_did"] = did
    query = {
        "uniqueId": username,
        "language": language,
        "isUniqueId": True,
        "validUniqueId": username,
    }
    api_url = "{}node/share/user/@{}?{}&{}".format(
        BASE_URL, quote(username), self.__add_new_params__(), urlencode(query)
    )

    return self.getData(url=api_url, **kwargs)["userInfo"]
# Buggy code
def trending(self, count=30, minCursor=0, maxCursor=0, **kwargs) -> dict:
    """
    Gets trending TikToks
    """
    (
        region,
        language,
        proxy,
        maxCount,
    ) = self.__process_kwargs__(kwargs)

    response = []
    first = True

    while len(response) < count:
        if count < maxCount:
            realCount = count
        else:
            realCount = maxCount

        query = {
            "count": realCount,
            "id": 1,
            "secUid": "",
            "maxCursor": maxCursor,
            "minCursor": minCursor,
            "sourceType": 12,
            "appId": 1233,
            "region": region,
            "priority_region": region,
            "language": language,
        }
        api_url = "{}api/item_list/?{}&{}".format(
            BASE_URL, self.__add_new_params__(), urlencode(query)
        )
        b = browser(api_url, **kwargs)
        res = self.getData(b, proxy=proxy)

        for t in res.get("items", []):
            response.append(t)

        if not res["hasMore"] and not first:
            if self.debug:
                print("TikTok isn't sending more TikToks beyond this point.")
            return response[:count]

        realCount = count - len(response)
        maxCursor = res["maxCursor"]

        first = False

    return response[:count]


# Traceback (TypeError)
# Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername
**kwargs,
TypeError: userPosts() got multiple values for keyword argument 'proxy'

# Fixed code
def trending(self, count=30, minCursor=0, maxCursor=0, **kwargs) -> dict:
    """
    Gets trending TikToks
    """
    (
        region,
        language,
        proxy,
        maxCount,
    ) = self.__process_kwargs__(kwargs)

    response = []
    first = True

    while len(response) < count:
        if count < maxCount:
            realCount = count
        else:
            realCount = maxCount

        query = {
            "count": realCount,
            "id": 1,
            "secUid": "",
            "maxCursor": maxCursor,
            "minCursor": minCursor,
            "sourceType": 12,
            "appId": 1233,
            "region": region,
            "priority_region": region,
            "language": language,
        }
        api_url = "{}api/item_list/?{}&{}".format(
            BASE_URL, self.__add_new_params__(), urlencode(query)
        )
        b = browser(api_url, **kwargs)
        res = self.getData(b, **kwargs)

        for t in res.get("items", []):
            response.append(t)

        if not res["hasMore"] and not first:
            if self.debug:
                print("TikTok isn't sending more TikToks beyond this point.")
            return response[:count]

        realCount = count - len(response)
        maxCursor = res["maxCursor"]

        first = False

    return response[:count]