gurudesh/pytracebugs huggingface dataset:
# Buggy code
def sensors_battery():
    """Return battery info."""
    percent, minsleft, power_plugged = cext.sensors_battery()
    power_plugged = power_plugged == 1
    if power_plugged:
        secsleft = _common.POWER_TIME_UNLIMITED
    elif minsleft == -1:
        secsleft = _common.POWER_TIME_UNKNOWN
    else:
        secsleft = minsleft * 60
    return _common.sbattery(percent, secsleft, power_plugged)


# Traceback (OSError)
#PYTHONPATH=/usr/src/psutil python2 psutil/tests/test_connections.py

Traceback (most recent call last):
File "psutil/tests/test_connections.py", line 30, in <module>
from psutil.tests import AF_UNIX
File "/usr/src/psutil/psutil/tests/__init__.py", line 156, in <module>
HAS_BATTERY = HAS_SENSORS_BATTERY and psutil.sensors_battery()
File "/usr/src/psutil/psutil/__init__.py", line 2316, in sensors_battery
return _psplatform.sensors_battery()
File "/usr/src/psutil/psutil/_psbsd.py", line 411, in sensors_battery
percent, minsleft, power_plugged = cext.sensors_battery()
OSError: [Errno 2] No such file or directory

# Fixed code
def sensors_battery():
    """Return battery info."""
    try:
        percent, minsleft, power_plugged = cext.sensors_battery()
    except NotImplementedError:
        # see: https://github.com/giampaolo/psutil/issues/1074
        return None
    power_plugged = power_plugged == 1
    if power_plugged:
        secsleft = _common.POWER_TIME_UNLIMITED
    elif minsleft == -1:
        secsleft = _common.POWER_TIME_UNKNOWN
    else:
        secsleft = minsleft * 60
    return _common.sbattery(percent, secsleft, power_plugged)
# Buggy code
def pid_exists(pid):
    """Check For the existence of a unix pid."""
    return _psposix.pid_exists(pid)


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/giampaolo/svn/psutil/test/test_psutil.py", line 738, in test_pid_exists_range
assert not os.path.exists('/proc/%s' % pid), pid
AssertionError: 947

# Fixed code
def pid_exists(pid):
    """Check for the existence of a unix PID."""
    if not _psposix.pid_exists(pid):
        return False
    else:
        # Linux's apparently does not distinguish between PIDs and TIDs
        # (thread IDs).
        # listdir("/proc") won't show any TID (only PIDs) but
        # os.stat("/proc/{tid}") will succeed if {tid} exists.
        # os.kill() can also be passed a TID. This is quite confusing.
        # In here we want to enforce this distinction and support PIDs
        # only, see:
        # https://github.com/giampaolo/psutil/issues/687
        try:
            # Note: already checked that this is faster than using a
            # regular expr. Also (a lot) faster than doing
            # 'return pid in pids()'
            with open_binary("%s/%s/status" % (get_procfs_path(), pid)) as f:
                for line in f:
                    if line.startswith(b"Tgid:"):
                        tgid = int(line.split()[1])
                        # If tgid and pid are the same then we're
                        # dealing with a process PID.
                        return tgid == pid
                raise ValueError("'Tgid' line not found")
        except (EnvironmentError, ValueError):
            return pid in pids()
# Buggy code
def swap_memory():
    """System swap memory as (total, used, free, sin, sout) namedtuple."""
    pagesize = 1 if OPENBSD else PAGESIZE
    total, used, free, sin, sout = [x * pagesize for x in cext.swap_mem()]
    percent = usage_percent(used, total, _round=1)
    return _common.sswap(total, used, free, percent, sin, sout)


# Traceback (AssertionError)
======================================================================
FAIL: test_bsd.NetBSDSpecificTestCase.test_swapmem_free
----------------------------------------------------------------------
Traceback (most recent call last):
File "/vagrant/psutil/psutil/tests/test_bsd.py", line 401, in test_swapmem_free
psutil.swap_memory().free, self.parse_meminfo("SwapFree:"))
AssertionError: 2197127430144L != 536403968

======================================================================
FAIL: test_bsd.NetBSDSpecificTestCase.test_swapmem_total
----------------------------------------------------------------------
Traceback (most recent call last):
File "/vagrant/psutil/psutil/tests/test_bsd.py", line 397, in test_swapmem_total
psutil.swap_memory().total, self.parse_meminfo("SwapTotal:"))
AssertionError: 2197127430144L != 536403968

======================================================================
FAIL: test_bsd.NetBSDSpecificTestCase.test_vmem_free
----------------------------------------------------------------------
Traceback (most recent call last):
File "/vagrant/psutil/psutil/tests/test_bsd.py", line 385, in test_vmem_free
psutil.virtual_memory().buffers, self.parse_meminfo("MemFree:"))
AssertionError: 46714880 != 1939644416

======================================================================
FAIL: test_bsd.NetBSDSpecificTestCase.test_vmem_total
----------------------------------------------------------------------
Traceback (most recent call last):
File "/vagrant/psutil/psutil/tests/test_bsd.py", line 381, in test_vmem_total
psutil.virtual_memory().total, self.parse_meminfo("MemTotal:"))
AssertionError: 2147020800L != 2067423232

# Fixed code
def swap_memory():
    """System swap memory as (total, used, free, sin, sout) namedtuple."""
    total, used, free, sin, sout = cext.swap_mem()
    percent = usage_percent(used, total, _round=1)
    return _common.sswap(total, used, free, percent, sin, sout)
# Buggy code
def cpu_affinity_set(self, cpus):
    try:
        cext.proc_cpu_affinity_set(self.pid, cpus)
    except OSError as err:
        if err.errno == errno.EINVAL:
            allcpus = tuple(range(len(per_cpu_times())))
            for cpu in cpus:
                if cpu not in allcpus:
                    raise ValueError(
                        "invalid CPU #%i (choose between %s)" % (cpu, allcpus)
                    )
        raise


# Traceback (SystemError)
~/svn/psutil {master}$ python3 -c "import psutil; psutil.Process().cpu_affinity([-1])"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/giampaolo/svn/psutil/psutil/__init__.py", line 764, in cpu_affinity
self._proc.cpu_affinity_set(list(set(cpus)))
File "/home/giampaolo/svn/psutil/psutil/_pslinux.py", line 1067, in wrapper
return fun(self, *args, **kwargs)
File "/home/giampaolo/svn/psutil/psutil/_pslinux.py", line 1423, in cpu_affinity_set
cext.proc_cpu_affinity_set(self.pid, cpus)
SystemError: <built-in function proc_cpu_affinity_set> returned NULL without setting an error

# Fixed code
def cpu_affinity_set(self, cpus):
    try:
        cext.proc_cpu_affinity_set(self.pid, cpus)
    except (OSError, ValueError) as err:
        if isinstance(err, ValueError) or err.errno == errno.EINVAL:
            allcpus = tuple(range(len(per_cpu_times())))
            for cpu in cpus:
                if cpu not in allcpus:
                    raise ValueError(
                        "invalid CPU number %r; choose between %s" % (cpu, allcpus)
                    )
        raise
# Buggy code
def status(self):
    """The process current status as a STATUS_* constant."""
    return self._proc.status()


# Traceback (psutil._error.NoSuchProcess)
How to reproduce:

1. start Photoshop CS6 on a Mountain Lion OSX
2. import psutil; [x.as_dict() for x in psutil.process_iter()] # (in .py file, ipython)



What is the expected output?
A long list of processes and related information



What do you see instead?


$ python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
[x.as_dict() for x in psutil.process_iter() if x.is_running()]
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.py",
line 225, in as_dict
ret = attr()
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.py",
line 414, in get_nice
return self._platform_impl.get_process_nice()
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/_psosx.py",
line 151, in wrapper
raise NoSuchProcess(self.pid, self._process_name)
psutil._error.NoSuchProcess: process no longer exists (pid=46244)

or within iPython notebook:
[x.as_dict() for x in psutil.process_iter() if x.is_running()]
---------------------------------------------------------------------------
NoSuchProcess                             Traceback (most recent call last)
<ipython-input-108-a71c6dffe397> in <module>()
----> 1 [x.as_dict() for x in psutil.process_iter() if x.is_running()]

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.pyc
in as_dict(self, attrs, ad_value)
223                         ret = attr(interval=0)
224                     else:
--> 225                         ret = attr()
226                 else:
227                     ret = attr

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.pyc
in get_nice(self)
412     def get_nice(self):
413         """Get process niceness (priority)."""
--> 414         return self._platform_impl.get_process_nice()
415
416     @_assert_pid_not_reused

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/_psosx.pyc in
wrapper(self, *args, **kwargs)
149             err = sys.exc_info()[1]
150             if err.errno == errno.ESRCH:
--> 151                 raise NoSuchProcess(self.pid, self._process_name)
152             if err.errno in (errno.EPERM, errno.EACCES):
153                 raise AccessDenied(self.pid, self._process_name)

NoSuchProcess: process no longer exists (pid=46243, name='adobe_licutil')

When I close Photoshop, the error will not show up. When starting it again the
error reappears.
An additional is_running() check within the list comprehension does not change
a thing and running the code several times will not change the reported pid.

# Fixed code
def status(self):
    """The process current status as a STATUS_* constant."""
    try:
        return self._proc.status()
    except ZombieProcess:
        return STATUS_ZOMBIE
# Buggy code
def __init__(self, pid):
    self.pid = pid
    self._name = None


# Traceback (psutil._error.NoSuchProcess)
How to reproduce:

1. start Photoshop CS6 on a Mountain Lion OSX
2. import psutil; [x.as_dict() for x in psutil.process_iter()] # (in .py file, ipython)



What is the expected output?
A long list of processes and related information



What do you see instead?


$ python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
[x.as_dict() for x in psutil.process_iter() if x.is_running()]
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.py",
line 225, in as_dict
ret = attr()
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.py",
line 414, in get_nice
return self._platform_impl.get_process_nice()
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/_psosx.py",
line 151, in wrapper
raise NoSuchProcess(self.pid, self._process_name)
psutil._error.NoSuchProcess: process no longer exists (pid=46244)

or within iPython notebook:
[x.as_dict() for x in psutil.process_iter() if x.is_running()]
---------------------------------------------------------------------------
NoSuchProcess                             Traceback (most recent call last)
<ipython-input-108-a71c6dffe397> in <module>()
----> 1 [x.as_dict() for x in psutil.process_iter() if x.is_running()]

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.pyc
in as_dict(self, attrs, ad_value)
223                         ret = attr(interval=0)
224                     else:
--> 225                         ret = attr()
226                 else:
227                     ret = attr

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.pyc
in get_nice(self)
412     def get_nice(self):
413         """Get process niceness (priority)."""
--> 414         return self._platform_impl.get_process_nice()
415
416     @_assert_pid_not_reused

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/_psosx.pyc in
wrapper(self, *args, **kwargs)
149             err = sys.exc_info()[1]
150             if err.errno == errno.ESRCH:
--> 151                 raise NoSuchProcess(self.pid, self._process_name)
152             if err.errno in (errno.EPERM, errno.EACCES):
153                 raise AccessDenied(self.pid, self._process_name)

NoSuchProcess: process no longer exists (pid=46243, name='adobe_licutil')

When I close Photoshop, the error will not show up. When starting it again the
error reappears.
An additional is_running() check within the list comprehension does not change
a thing and running the code several times will not change the reported pid.

# Fixed code
def __init__(self, pid):
    self.pid = pid
    self._name = None
    self._ppid = None
# Buggy code
def wrapper(self, *args, **kwargs):
    try:
        return wrap_exceptions(fun)(self)
    except NoSuchProcess:
        if not pid_exists(self.pid):
            raise
        else:
            raise ZombieProcess(self.pid, self._name)


# Traceback (psutil._error.NoSuchProcess)
How to reproduce:

1. start Photoshop CS6 on a Mountain Lion OSX
2. import psutil; [x.as_dict() for x in psutil.process_iter()] # (in .py file, ipython)



What is the expected output?
A long list of processes and related information



What do you see instead?


$ python test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
[x.as_dict() for x in psutil.process_iter() if x.is_running()]
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.py",
line 225, in as_dict
ret = attr()
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.py",
line 414, in get_nice
return self._platform_impl.get_process_nice()
File
"/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/_psosx.py",
line 151, in wrapper
raise NoSuchProcess(self.pid, self._process_name)
psutil._error.NoSuchProcess: process no longer exists (pid=46244)

or within iPython notebook:
[x.as_dict() for x in psutil.process_iter() if x.is_running()]
---------------------------------------------------------------------------
NoSuchProcess                             Traceback (most recent call last)
<ipython-input-108-a71c6dffe397> in <module>()
----> 1 [x.as_dict() for x in psutil.process_iter() if x.is_running()]

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.pyc
in as_dict(self, attrs, ad_value)
223                         ret = attr(interval=0)
224                     else:
--> 225                         ret = attr()
226                 else:
227                     ret = attr

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/__init__.pyc
in get_nice(self)
412     def get_nice(self):
413         """Get process niceness (priority)."""
--> 414         return self._platform_impl.get_process_nice()
415
416     @_assert_pid_not_reused

/Users/rico/.virtualenvs/temp/lib/python2.7/site-packages/psutil/_psosx.pyc in
wrapper(self, *args, **kwargs)
149             err = sys.exc_info()[1]
150             if err.errno == errno.ESRCH:
--> 151                 raise NoSuchProcess(self.pid, self._process_name)
152             if err.errno in (errno.EPERM, errno.EACCES):
153                 raise AccessDenied(self.pid, self._process_name)

NoSuchProcess: process no longer exists (pid=46243, name='adobe_licutil')

When I close Photoshop, the error will not show up. When starting it again the
error reappears.
An additional is_running() check within the list comprehension does not change
a thing and running the code several times will not change the reported pid.

# Fixed code
def wrapper(self, *args, **kwargs):
    try:
        return wrap_exceptions(fun)(self)
    except NoSuchProcess:
        if not pid_exists(self.pid):
            raise
        else:
            raise ZombieProcess(self.pid, self._name, self._ppid)
# Buggy code
def cpu_affinity(self, cpus=None):
    """Get or set process CPU affinity.
    If specified 'cpus' must be a list of CPUs for which you
    want to set the affinity (e.g. [0, 1]).
    """
    if cpus is None:
        return self._proc.cpu_affinity_get()
    else:
        self._proc.cpu_affinity_set(cpus)


# Traceback (AssertionError)
======================================================================
FAIL: test_cpu_count_physical (__main__.TestModuleFunctionsLeaks)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test/test_memory_leaks.py", line 340, in test_cpu_count_physical
self.execute('cpu_count')
File "test/test_memory_leaks.py", line 86, in execute
% (rss2, rss3, difference))
AssertionError: rss2=15773696, rss3=19410944, difference=3637248

# Fixed code
def cpu_affinity(self, cpus=None):
    """Get or set process CPU affinity.
    If specified 'cpus' must be a list of CPUs for which you
    want to set the affinity (e.g. [0, 1]).
    (Windows, Linux and BSD only).
    """
    if cpus is None:
        return self._proc.cpu_affinity_get()
    else:
        self._proc.cpu_affinity_set(cpus)
# Buggy code
def add_vertical_dim_from_xarray(func):
    """Fill in optional vertical_dim from DataArray argument."""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        bound_args = signature(func).bind(*args, **kwargs)
        bound_args.apply_defaults()

        # Search for DataArray in arguments
        dataarray_arguments = [
            value
            for value in bound_args.arguments.values()
            if isinstance(value, xr.DataArray)
        ]

        # Fill in vertical_dim
        if len(dataarray_arguments) > 0 and "vertical_dim" in bound_args.arguments:
            try:
                bound_args.arguments["vertical_dim"] = dataarray_arguments[
                    0
                ].metpy.find_axis_number("vertical")
            except AttributeError:
                # If axis number not found, fall back to default but warn.
                warnings.warn(
                    "Vertical dimension number not found. Defaulting to initial dimension."
                )

        return func(*bound_args.args, **bound_args.kwargs)

    return wrapper


# Traceback (ValueError)
Traceback (most recent call last):
File "moist_4panel.py", line 168, in <module>
pw[x,y] = mpcalc.precipitable_water(ds['P'].isel(latitude=x,longitude=y),ds['TD'].isel(latitude=x,longitude=y),bottom=pbot,top=ptop).m
File "/d1/anaconda3/envs/era5/lib/python3.8/site-packages/metpy/xarray.py", line 1174, in wrapper
return wrapping(result, match)
File "/d1/anaconda3/envs/era5/lib/python3.8/site-packages/metpy/xarray.py", line 1214, in _wrap_output_like_not_matching_units
xr.DataArray(result, coords=match.coords, dims=match.dims) if output_xarray
File "/d1/anaconda3/envs/era5/lib/python3.8/site-packages/xarray/core/dataarray.py", line 344, in __init__
coords, dims = _infer_coords_and_dims(data.shape, coords, dims)
File "/d1/anaconda3/envs/era5/lib/python3.8/site-packages/xarray/core/dataarray.py", line 121, in _infer_coords_and_dims
raise ValueError(
ValueError: different number of dimensions on data and dims: 0 vs 1

# Fixed code
def add_vertical_dim_from_xarray(func):
    """Fill in optional vertical_dim from DataArray argument."""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        bound_args = signature(func).bind(*args, **kwargs)
        bound_args.apply_defaults()

        # Fill in vertical_dim
        if "vertical_dim" in bound_args.arguments:
            a = next(dataarray_arguments(bound_args), None)
            if a is not None:
                try:
                    bound_args.arguments["vertical_dim"] = a.metpy.find_axis_number(
                        "vertical"
                    )
                except AttributeError:
                    # If axis number not found, fall back to default but warn.
                    warnings.warn(
                        "Vertical dimension number not found. Defaulting to initial dimension."
                    )

        return func(*bound_args.args, **bound_args.kwargs)

    return wrapper
# Buggy code
def wrapper(*args, **kwargs):
    bound_args = signature(func).bind(*args, **kwargs)
    bound_args.apply_defaults()

    # Search for DataArray in arguments
    dataarray_arguments = [
        value
        for value in bound_args.arguments.values()
        if isinstance(value, xr.DataArray)
    ]

    # Fill in vertical_dim
    if len(dataarray_arguments) > 0 and "vertical_dim" in bound_args.arguments:
        try:
            bound_args.arguments["vertical_dim"] = dataarray_arguments[
                0
            ].metpy.find_axis_number("vertical")
        except AttributeError:
            # If axis number not found, fall back to default but warn.
            warnings.warn(
                "Vertical dimension number not found. Defaulting to initial dimension."
            )

    return func(*bound_args.args, **bound_args.kwargs)


# Traceback (ValueError)
Traceback (most recent call last):
File "moist_4panel.py", line 168, in <module>
pw[x,y] = mpcalc.precipitable_water(ds['P'].isel(latitude=x,longitude=y),ds['TD'].isel(latitude=x,longitude=y),bottom=pbot,top=ptop).m
File "/d1/anaconda3/envs/era5/lib/python3.8/site-packages/metpy/xarray.py", line 1174, in wrapper
return wrapping(result, match)
File "/d1/anaconda3/envs/era5/lib/python3.8/site-packages/metpy/xarray.py", line 1214, in _wrap_output_like_not_matching_units
xr.DataArray(result, coords=match.coords, dims=match.dims) if output_xarray
File "/d1/anaconda3/envs/era5/lib/python3.8/site-packages/xarray/core/dataarray.py", line 344, in __init__
coords, dims = _infer_coords_and_dims(data.shape, coords, dims)
File "/d1/anaconda3/envs/era5/lib/python3.8/site-packages/xarray/core/dataarray.py", line 121, in _infer_coords_and_dims
raise ValueError(
ValueError: different number of dimensions on data and dims: 0 vs 1

# Fixed code
def wrapper(*args, **kwargs):
    bound_args = signature(func).bind(*args, **kwargs)
    bound_args.apply_defaults()

    # Fill in vertical_dim
    if "vertical_dim" in bound_args.arguments:
        a = next(dataarray_arguments(bound_args), None)
        if a is not None:
            try:
                bound_args.arguments["vertical_dim"] = a.metpy.find_axis_number(
                    "vertical"
                )
            except AttributeError:
                # If axis number not found, fall back to default but warn.
                warnings.warn(
                    "Vertical dimension number not found. Defaulting to initial dimension."
                )

    return func(*bound_args.args, **bound_args.kwargs)
# Buggy code
def _insert_lcl_level(pressure, temperature, lcl_pressure):
    """Insert the LCL pressure into the profile."""
    interp_temp = interpolate_1d(lcl_pressure, pressure, temperature)

    # Pressure needs to be increasing for searchsorted, so flip it and then convert
    # the index back to the original array
    loc = pressure.size - pressure[::-1].searchsorted(lcl_pressure)
    return np.insert(temperature.m, loc, interp_temp.m) * temperature.units


# Traceback (ValueError)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-d3bf39d73e06> in <module>
7 td = units.degC * np.ma.array([20, 10, -5])
8
----> 9 mpcalc.surface_based_cape_cin(pressure, t, td)

~/repos/metpy/src/metpy/xarray.py in wrapper(*args, **kwargs)
1065         kwargs = {name: (v.metpy.unit_array if isinstance(v, xr.DataArray) else v)
1066                   for name, v in kwargs.items()}
-> 1067         return func(*args, **kwargs)
1068     return wrapper
1069

~/repos/metpy/src/metpy/units.py in wrapper(*args, **kwargs)
231                             '    x = x * units.meter / units.second')
232                 raise ValueError(msg)
--> 233             return func(*args, **kwargs)
234
235         return wrapper

~/repos/metpy/src/metpy/calc/thermo.py in surface_based_cape_cin(pressure, temperature, dewpoint)
1826     pressure, temperature, dewpoint = _remove_nans(pressure, temperature, dewpoint)
1827     p, t, td, profile = parcel_profile_with_lcl(pressure, temperature, dewpoint)
-> 1828     return cape_cin(p, t, td, profile)
1829
1830

~/repos/metpy/src/metpy/xarray.py in wrapper(*args, **kwargs)
1065         kwargs = {name: (v.metpy.unit_array if isinstance(v, xr.DataArray) else v)
1066                   for name, v in kwargs.items()}
-> 1067         return func(*args, **kwargs)
1068     return wrapper
1069

~/repos/metpy/src/metpy/units.py in wrapper(*args, **kwargs)
230                             '    from metpy.units import units\n'
231                             '    x = x * units.meter / units.second')
--> 232                 raise ValueError(msg)
233             return func(*args, **kwargs)
234

ValueError: `cape_cin` given arguments with incorrect units: `temperature` requires "[temperature]" but given "none", `dewpoint` requires "[temperature]" but given "none"
Any variable `x` can be assigned a unit as follows:
from metpy.units import units
x = x * units.meter / units.second

# Fixed code
def _insert_lcl_level(pressure, temperature, lcl_pressure):
    """Insert the LCL pressure into the profile."""
    interp_temp = interpolate_1d(lcl_pressure, pressure, temperature)

    # Pressure needs to be increasing for searchsorted, so flip it and then convert
    # the index back to the original array
    loc = pressure.size - pressure[::-1].searchsorted(lcl_pressure)
    return temperature.units * np.insert(temperature.m, loc, interp_temp.m)
# Buggy code
def cluster_vectorspace(self, vectors, trace=False):
    if self._means and self._repeats > 1:
        print("Warning: means will be discarded for subsequent trials")

    meanss = []
    for trial in range(self._repeats):
        if trace:
            print("k-means trial", trial)
        if not self._means or trial > 1:
            self._means = self._rng.sample(vectors, self._num_means)
        self._cluster_vectorspace(vectors, trace)
        meanss.append(self._means)

    if len(meanss) > 1:
        # sort the means first (so that different cluster numbering won't
        # effect the distance comparison)
        for means in meanss:
            means.sort(key=sum)

        # find the set of means that's minimally different from the others
        min_difference = min_means = None
        for i in range(len(meanss)):
            d = 0
            for j in range(len(meanss)):
                if i != j:
                    d += self._sum_distances(meanss[i], meanss[j])
            if min_difference is None or d < min_difference:
                min_difference, min_means = d, meanss[i]

        # use the best means
        self._means = min_means


# Traceback (TypeError)
Traceback (most recent call last):
...
File "D:\SourceCode\voc\nltk\cluster\util.py", line 65, in cluster
self.cluster_vectorspace(vectors, trace)
File "D:\SourceCode\voc\nltk\cluster\kmeans.py", line 84, in cluster_vectorspace
self._means = self._rng.sample(vectors, self._num_means)
File "C:\Python32-64\lib\random.py", line 299, in sample
raise TypeError("Population must be a sequence or Set.  For dicts, use list(d).")
TypeError: Population must be a sequence or Set.  For dicts, use list(d).

# Fixed code
def cluster_vectorspace(self, vectors, trace=False):
    if self._means and self._repeats > 1:
        print("Warning: means will be discarded for subsequent trials")

    meanss = []
    for trial in range(self._repeats):
        if trace:
            print("k-means trial", trial)
        if not self._means or trial > 1:
            self._means = self._rng.sample(list(vectors), self._num_means)
        self._cluster_vectorspace(vectors, trace)
        meanss.append(self._means)

    if len(meanss) > 1:
        # sort the means first (so that different cluster numbering won't
        # effect the distance comparison)
        for means in meanss:
            means.sort(key=sum)

        # find the set of means that's minimally different from the others
        min_difference = min_means = None
        for i in range(len(meanss)):
            d = 0
            for j in range(len(meanss)):
                if i != j:
                    d += self._sum_distances(meanss[i], meanss[j])
            if min_difference is None or d < min_difference:
                min_difference, min_means = d, meanss[i]

        # use the best means
        self._means = min_means
# Buggy code
def _make_tagdict(self, sentences):
    """
    Make a tag dictionary for single-tag words.
    :param sentences: A list of list of (word, tag) tuples.
    """
    counts = defaultdict(lambda: defaultdict(int))
    for sentence in sentences:
        for word, tag in sentence:
            counts[word][tag] += 1
            self.classes.add(tag)
    freq_thresh = 20
    ambiguity_thresh = 0.97
    for word, tag_freqs in counts.items():
        tag, mode = max(tag_freqs.items(), key=lambda item: item[1])
        n = sum(tag_freqs.values())
        # Don't add rare words to the tag dictionary
        # Only add quite unambiguous words
        if n >= freq_thresh and (mode / n) >= ambiguity_thresh:
            self.tagdict[word] = tag


# Traceback (TypeError)
from nltk.tag import PerceptronTagger
from nltk.corpus import alpino as alp
training_corpus = alp.tagged_sents()
tagger = PerceptronTagger(load=False)
tagger.train(training_corpus)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/nltk/tag/perceptron.py", line 194, in train
random.shuffle(sentences)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 291, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'StreamBackedCorpusView' object does not support item assignment

# Fixed code
def _make_tagdict(self, sentences):
    """
    Make a tag dictionary for single-tag words.
    :param sentences: A list of list of (word, tag) tuples.
    """
    counts = defaultdict(lambda: defaultdict(int))
    for sentence in sentences:
        self._sentences.append(sentence)
        for word, tag in sentence:
            counts[word][tag] += 1
            self.classes.add(tag)
    freq_thresh = 20
    ambiguity_thresh = 0.97
    for word, tag_freqs in counts.items():
        tag, mode = max(tag_freqs.items(), key=lambda item: item[1])
        n = sum(tag_freqs.values())
        # Don't add rare words to the tag dictionary
        # Only add quite unambiguous words
        if n >= freq_thresh and (mode / n) >= ambiguity_thresh:
            self.tagdict[word] = tag
# Buggy code
def __init__(self, strings=None):
    """Builds a Trie object, which is built around a ``defaultdict``

    If ``strings`` is provided, it will add the ``strings``, which
    consist of a ``list`` of ``strings``, to the Trie.
    Otherwise, it'll construct an empty Trie.

    :param strings: List of strings to insert into the trie
        (Default is ``None``)
    :type strings: list(str)

    """
    defaultdict.__init__(self, Trie)
    if strings:
        for string in strings:
            self.insert(string)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-47-205693e12b16> in <module>()
1 with open('tokenizer.pkl', 'rb') as f:
----> 2     t = pickle.load(f)

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load(file)
1382
1383 def load(file):
-> 1384     return Unpickler(file).load()
1385
1386 def loads(str):

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load(self)
862             while 1:
863                 key = read(1)
--> 864                 dispatch[key](self)
865         except _Stop, stopinst:
866             return stopinst.value

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load_reduce(self)
1137         args = stack.pop()
1138         func = stack[-1]
-> 1139         value = func(*args)
1140         stack[-1] = value
1141     dispatch[REDUCE] = load_reduce

/Users/vinay/Sites/nltk_mwe/.env/lib/python2.7/site-packages/nltk/collections.pyc in __init__(self, strings)
611         defaultdict.__init__(self, Trie)
612         if strings:
--> 613             for string in strings:
614                 self.insert(string)
615

TypeError: 'type' object is not iterable

# Fixed code
def __init__(self, strings=None):
    """Builds a Trie object, which is built around a ``dict``

    If ``strings`` is provided, it will add the ``strings``, which
    consist of a ``list`` of ``strings``, to the Trie.
    Otherwise, it'll construct an empty Trie.

    :param strings: List of strings to insert into the trie
        (Default is ``None``)
    :type strings: list(str)

    """
    super(Trie, self).__init__()
    if strings:
        for string in strings:
            self.insert(string)
# Buggy code
def insert(self, string):
    """Inserts ``string`` into the Trie

    :param string: String to insert into the trie
    :type string: str

    :Example:

    >>> from nltk.collections import Trie
    >>> trie = Trie(["ab"])
    >>> trie
    defaultdict(<class 'nltk.collections.Trie'>, {'a': defaultdict(<class 'nltk.collections.Trie'>, {'b': defaultdict(<class 'nltk.collections.Trie'>, {True: None})})})

    """
    if len(string):
        self[string[0]].insert(string[1:])
    else:
        # mark the string is complete
        self[Trie.LEAF] = None


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-47-205693e12b16> in <module>()
1 with open('tokenizer.pkl', 'rb') as f:
----> 2     t = pickle.load(f)

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load(file)
1382
1383 def load(file):
-> 1384     return Unpickler(file).load()
1385
1386 def loads(str):

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load(self)
862             while 1:
863                 key = read(1)
--> 864                 dispatch[key](self)
865         except _Stop, stopinst:
866             return stopinst.value

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load_reduce(self)
1137         args = stack.pop()
1138         func = stack[-1]
-> 1139         value = func(*args)
1140         stack[-1] = value
1141     dispatch[REDUCE] = load_reduce

/Users/vinay/Sites/nltk_mwe/.env/lib/python2.7/site-packages/nltk/collections.pyc in __init__(self, strings)
611         defaultdict.__init__(self, Trie)
612         if strings:
--> 613             for string in strings:
614                 self.insert(string)
615

TypeError: 'type' object is not iterable

# Fixed code
def insert(self, string):
    """Inserts ``string`` into the Trie

        :param string: String to insert into the trie
        :type string: str

        :Example:

        >>> from nltk.collections import Trie
        >>> trie = Trie(["abc", "def"])
        >>> expected = {'a': {'b': {'c': {True: None}}}, \
                        'd': {'e': {'f': {True: None}}}}
        >>> trie == expected
        True

        """
    if len(string):
        self[string[0]].insert(string[1:])
    else:
        # mark the string is complete
        self[Trie.LEAF] = None
# Buggy code
def __missing__(self, key):
    if not self._default_factory and key not in self._keys:
        raise KeyError()
    return self._default_factory()


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-47-205693e12b16> in <module>()
1 with open('tokenizer.pkl', 'rb') as f:
----> 2     t = pickle.load(f)

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load(file)
1382
1383 def load(file):
-> 1384     return Unpickler(file).load()
1385
1386 def loads(str):

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load(self)
862             while 1:
863                 key = read(1)
--> 864                 dispatch[key](self)
865         except _Stop, stopinst:
866             return stopinst.value

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load_reduce(self)
1137         args = stack.pop()
1138         func = stack[-1]
-> 1139         value = func(*args)
1140         stack[-1] = value
1141     dispatch[REDUCE] = load_reduce

/Users/vinay/Sites/nltk_mwe/.env/lib/python2.7/site-packages/nltk/collections.pyc in __init__(self, strings)
611         defaultdict.__init__(self, Trie)
612         if strings:
--> 613             for string in strings:
614                 self.insert(string)
615

TypeError: 'type' object is not iterable

# Fixed code
def __missing__(self, key):
    self[key] = Trie()
    return self[key]
# Buggy code
def add_mwe(self, mwe):
    """Add a multi-word expression to the lexicon (stored as a word trie)

    We use ``util.Trie`` to represent the trie. Its form is a dict of dicts.
    The key True marks the end of a valid MWE.

    :param mwe: The multi-word expression we're adding into the word trie
    :type mwe: tuple(str) or list(str)

    :Example:

    >>> tokenizer = MWETokenizer()
    >>> tokenizer.add_mwe(('a', 'b'))
    >>> tokenizer.add_mwe(('a', 'b', 'c'))
    >>> tokenizer.add_mwe(('a', 'x'))
    >>> expected = {'a': {'x': {True: None}, 'b': {True: None, 'c': {True: None}}}}
    >>> tokenizer._mwes.as_dict() == expected
    True

    """
    self._mwes.insert(mwe)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-47-205693e12b16> in <module>()
1 with open('tokenizer.pkl', 'rb') as f:
----> 2     t = pickle.load(f)

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load(file)
1382
1383 def load(file):
-> 1384     return Unpickler(file).load()
1385
1386 def loads(str):

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load(self)
862             while 1:
863                 key = read(1)
--> 864                 dispatch[key](self)
865         except _Stop, stopinst:
866             return stopinst.value

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.pyc in load_reduce(self)
1137         args = stack.pop()
1138         func = stack[-1]
-> 1139         value = func(*args)
1140         stack[-1] = value
1141     dispatch[REDUCE] = load_reduce

/Users/vinay/Sites/nltk_mwe/.env/lib/python2.7/site-packages/nltk/collections.pyc in __init__(self, strings)
611         defaultdict.__init__(self, Trie)
612         if strings:
--> 613             for string in strings:
614                 self.insert(string)
615

TypeError: 'type' object is not iterable

# Fixed code
def add_mwe(self, mwe):
    """Add a multi-word expression to the lexicon (stored as a word trie)

    We use ``util.Trie`` to represent the trie. Its form is a dict of dicts.
    The key True marks the end of a valid MWE.

    :param mwe: The multi-word expression we're adding into the word trie
    :type mwe: tuple(str) or list(str)

    :Example:

    >>> tokenizer = MWETokenizer()
    >>> tokenizer.add_mwe(('a', 'b'))
    >>> tokenizer.add_mwe(('a', 'b', 'c'))
    >>> tokenizer.add_mwe(('a', 'x'))
    >>> expected = {'a': {'x': {True: None}, 'b': {True: None, 'c': {True: None}}}}
    >>> tokenizer._mwes == expected
    True

    """
    self._mwes.insert(mwe)
# Buggy code
def has_numeric_only(self, text):
    return bool(re.match(r"(.*)[\s]+(\#NUMERIC_ONLY\#)", text))


# Traceback (sre_constants.error)
$ python -c 'from nltk.tokenize.moses import MosesTokenizer; m = MosesTokenizer(); m.penn_tokenize("this aint funny")'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "nltk/tokenize/moses.py", line 299, in penn_tokenize
text = re.sub(regexp, subsitution, text)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis

# Fixed code
def has_numeric_only(self, text):
    return bool(re.search(r"(.*)[\s]+(\#NUMERIC_ONLY\#)", text))
# Buggy code
def escape_xml(self, text):
    for regexp, subsitution in self.MOSES_ESCAPE_XML_REGEXES:
        text = re.sub(regexp, subsitution, text)
    return text


# Traceback (sre_constants.error)
$ python -c 'from nltk.tokenize.moses import MosesTokenizer; m = MosesTokenizer(); m.penn_tokenize("this aint funny")'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "nltk/tokenize/moses.py", line 299, in penn_tokenize
text = re.sub(regexp, subsitution, text)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis

# Fixed code
def escape_xml(self, text):
    for regexp, substitution in self.MOSES_ESCAPE_XML_REGEXES:
        text = re.sub(regexp, substitution, text)
    return text
# Buggy code
def penn_tokenize(self, text, return_str=False):
    """
    This is a Python port of the Penn treebank tokenizer adapted by the Moses
    machine translation community. It's a little different from the
    version in nltk.tokenize.treebank.
    """
    # Converts input string into unicode.
    text = text_type(text)
    # Perform a chain of regex substituitions using MOSES_PENN_REGEXES_1
    for regexp, subsitution in self.MOSES_PENN_REGEXES_1:
        text = re.sub(regexp, subsitution, text)
    # Handles nonbreaking prefixes.
    text = handles_nonbreaking_prefixes(text)
    # Restore ellipsis, clean extra spaces, escape XML symbols.
    for regexp, subsitution in self.MOSES_PENN_REGEXES_2:
        text = re.sub(regexp, subsitution, text)
    return text if return_str else text.split()


# Traceback (sre_constants.error)
$ python -c 'from nltk.tokenize.moses import MosesTokenizer; m = MosesTokenizer(); m.penn_tokenize("this aint funny")'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "nltk/tokenize/moses.py", line 299, in penn_tokenize
text = re.sub(regexp, subsitution, text)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis

# Fixed code
def penn_tokenize(self, text, return_str=False):
    """
    This is a Python port of the Penn treebank tokenizer adapted by the Moses
    machine translation community. It's a little different from the
    version in nltk.tokenize.treebank.
    """
    # Converts input string into unicode.
    text = text_type(text)
    # Perform a chain of regex substituitions using MOSES_PENN_REGEXES_1
    for regexp, substitution in self.MOSES_PENN_REGEXES_1:
        text = re.sub(regexp, substitution, text)
    # Handles nonbreaking prefixes.
    text = self.handles_nonbreaking_prefixes(text)
    # Restore ellipsis, clean extra spaces, escape XML symbols.
    for regexp, substitution in self.MOSES_PENN_REGEXES_2:
        text = re.sub(regexp, substitution, text)
    return text if return_str else text.split()
# Buggy code
def unescape_xml(self, text):
    for regexp, subsitution in self.MOSES_UNESCAPE_XML_REGEXES:
        text = re.sub(regexp, subsitution, text)
    return text


# Traceback (sre_constants.error)
$ python -c 'from nltk.tokenize.moses import MosesTokenizer; m = MosesTokenizer(); m.penn_tokenize("this aint funny")'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "nltk/tokenize/moses.py", line 299, in penn_tokenize
text = re.sub(regexp, subsitution, text)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis

# Fixed code
def unescape_xml(self, text):
    for regexp, substitution in self.MOSES_UNESCAPE_XML_REGEXES:
        text = re.sub(regexp, substitution, text)
    return text
# Buggy code
def __str__(self, **kwargs):
    return self._str_repr(formatting="plain", **kwargs)


# Traceback (AttributeError)
vals
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sayam/.local/lib/python3.8/site-packages/theano/gof/graph.py", line 449, in __repr__
to_print = [str(self)]
File "/home/sayam/Desktop/pymc/pymc3/pymc3/model.py", line 83, in __str__
return self._str_repr(formatting="plain", **kwargs)
File "/home/sayam/Desktop/pymc/pymc3/pymc3/model.py", line 77, in _str_repr
return self.distribution._str_repr(name=name, dist=dist, formatting=formatting)
File "/home/sayam/Desktop/pymc/pymc3/pymc3/distributions/distribution.py", line 176, in _str_repr
param_values = [
File "/home/sayam/Desktop/pymc/pymc3/pymc3/distributions/distribution.py", line 177, in <listcomp>
get_repr_for_variable(getattr(dist, x), formatting=formatting) for x in param_names
File "/home/sayam/Desktop/pymc/pymc3/pymc3/util.py", line 131, in get_repr_for_variable
name = variable.name if variable is not None else None
AttributeError: 'list' object has no attribute 'name'

# Fixed code
def __str__(self, **kwargs):
    try:
        return self._str_repr(formatting="plain", **kwargs)
    except:
        return super().__str__()
# Buggy code
def _distr_parameters_for_repr(self):
    return ["a"]


# Traceback (AttributeError)
vals
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sayam/.local/lib/python3.8/site-packages/theano/gof/graph.py", line 449, in __repr__
to_print = [str(self)]
File "/home/sayam/Desktop/pymc/pymc3/pymc3/model.py", line 83, in __str__
return self._str_repr(formatting="plain", **kwargs)
File "/home/sayam/Desktop/pymc/pymc3/pymc3/model.py", line 77, in _str_repr
return self.distribution._str_repr(name=name, dist=dist, formatting=formatting)
File "/home/sayam/Desktop/pymc/pymc3/pymc3/distributions/distribution.py", line 176, in _str_repr
param_values = [
File "/home/sayam/Desktop/pymc/pymc3/pymc3/distributions/distribution.py", line 177, in <listcomp>
get_repr_for_variable(getattr(dist, x), formatting=formatting) for x in param_names
File "/home/sayam/Desktop/pymc/pymc3/pymc3/util.py", line 131, in get_repr_for_variable
name = variable.name if variable is not None else None
AttributeError: 'list' object has no attribute 'name'

# Fixed code
def _distr_parameters_for_repr(self):
    return ["mu"]