gurudesh/pytracebugs huggingface dataset:
# Buggy code
def rand(random_state, *dn, **kw):
    """
    Random values in a given shape.

    Create a tensor of the given shape and populate it with
    random samples from a uniform distributionc
    over ``[0, 1)``.

    Parameters
    ----------
    d0, d1, ..., dn : int, optional
        The dimensions of the returned tensor, should all be positive.
        If no argument is given a single Python float is returned.

    Returns
    -------
    out : Tensor, shape ``(d0, d1, ..., dn)``
        Random values.

    See Also
    --------
    random

    Notes
    -----
    This is a convenience function. If you want an interface that
    takes a shape-tuple as the first argument, refer to
    mt.random.random_sample .

    Examples
    --------
    >>> import mars.tensor as mt

    >>> mt.random.rand(3,2).execute()
    array([[ 0.14022471,  0.96360618],  #random
           [ 0.37601032,  0.25528411],  #random
           [ 0.49313049,  0.94909878]]) #random
    """
    if "dtype" not in kw:
        kw["dtype"] = np.dtype("f8")
    chunks = kw.pop("chunks", None)
    op = TensorRand(state=random_state._state, size=dn, **kw)
    return op(chunks=chunks)


# Traceback (TypeError)
In [1]: import numpy as np

In [2]: np.random.rand((2, 3))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-e49eb55bb286> in <module>()
----> 1 np.random.rand((2, 3))

mtrand.pyx in mtrand.RandomState.rand()

mtrand.pyx in mtrand.RandomState.random_sample()

mtrand.pyx in mtrand.cont0_array()

TypeError: 'tuple' object cannot be interpreted as an integer

# Fixed code
def rand(random_state, *dn, **kw):
    """
    Random values in a given shape.

    Create a tensor of the given shape and populate it with
    random samples from a uniform distributionc
    over ``[0, 1)``.

    Parameters
    ----------
    d0, d1, ..., dn : int, optional
        The dimensions of the returned tensor, should all be positive.
        If no argument is given a single Python float is returned.

    Returns
    -------
    out : Tensor, shape ``(d0, d1, ..., dn)``
        Random values.

    See Also
    --------
    random

    Notes
    -----
    This is a convenience function. If you want an interface that
    takes a shape-tuple as the first argument, refer to
    mt.random.random_sample .

    Examples
    --------
    >>> import mars.tensor as mt

    >>> mt.random.rand(3,2).execute()
    array([[ 0.14022471,  0.96360618],  #random
           [ 0.37601032,  0.25528411],  #random
           [ 0.49313049,  0.94909878]]) #random
    """
    if len(dn) == 1 and isinstance(dn[0], (tuple, list)):
        raise TypeError("'tuple' object cannot be interpreted as an integer")
    if "dtype" not in kw:
        kw["dtype"] = np.dtype("f8")
    chunks = kw.pop("chunks", None)
    op = TensorRand(state=random_state._state, size=dn, **kw)
    return op(chunks=chunks)
# Buggy code
def on_train_begin(self, logs=None):
    self.num_epochs = self.params["epochs"]
    self.metrics = self.params["metrics"]

    if self.show_overall_progress:
        self.overall_progress_tqdm = self.tqdm(
            desc="Training",
            total=self.num_epochs,
            bar_format=self.overall_bar_format,
            leave=self.leave_overall_progress,
            dynamic_ncols=True,
            unit="epochs",
        )

    # set counting mode
    if "samples" in self.params:
        self.mode = "samples"
        self.total_steps = self.params["samples"]
    else:
        self.mode = "steps"
        self.total_steps = self.params["steps"]


# Traceback (KeyError)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-23-fdbb03f574a1> in <module>
48 #   class_weight=class_weights,
49     verbose=VERBOSE,
---> 50     callbacks=model_callbacks,
51 )

~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in _method_wrapper(self, *args, **kwargs)
63   def _method_wrapper(self, *args, **kwargs):
64     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
---> 65       return method(self, *args, **kwargs)
66
67     # Running inside `run_distribute_coordinator` already.

~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
763       self.stop_training = False
764       train_function = self.make_train_function()
--> 765       callbacks.on_train_begin()
766       # Handle fault-tolerance for multi-worker.
767       # TODO(omalleyt): Fix the ordering issues that mean this has to

~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow/python/keras/callbacks.py in on_train_begin(self, logs)
445     logs = self._process_logs(logs)
446     for callback in self.callbacks:
--> 447       callback.on_train_begin(logs)
448
449   def on_train_end(self, logs=None):

~/.pyenv/versions/3.7.6/lib/python3.7/site-packages/tensorflow_addons/callbacks/tqdm_progress_bar.py in on_train_begin(self, logs)
100     def on_train_begin(self, logs=None):
101         self.num_epochs = self.params["epochs"]
--> 102         self.metrics = self.params["metrics"]
103
104         if self.show_overall_progress:

KeyError: 'metrics'

# Fixed code
def on_train_begin(self, logs=None):
    self.num_epochs = self.params["epochs"]

    if self.show_overall_progress:
        self.overall_progress_tqdm = self.tqdm(
            desc="Training",
            total=self.num_epochs,
            bar_format=self.overall_bar_format,
            leave=self.leave_overall_progress,
            dynamic_ncols=True,
            unit="epochs",
        )

    # set counting mode
    self.mode = "steps"
    self.total_steps = self.params["steps"]
# Buggy code
def __init__(self, model, autobalance=False):
    super(ComputeLoss, self).__init__()
    device = next(model.parameters()).device  # get model device
    h = model.hyp  # hyperparameters

    # Define criteria
    BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["cls_pw"]], device=device))
    BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["obj_pw"]], device=device))

    # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
    self.cp, self.cn = smooth_BCE(eps=0.0)

    # Focal loss
    g = h["fl_gamma"]  # focal loss gamma
    if g > 0:
        BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)

    det = (
        model.module.model[-1] if is_parallel(model) else model.model[-1]
    )  # Detect() module
    self.balance = {
        3: [4.0, 1.0, 0.4],
        4: [4.0, 1.0, 0.25, 0.06],
        5: [4.0, 1.0, 0.25, 0.06, 0.02],
    }[det.nl]
    self.ssi = (det.stride == 16).nonzero(as_tuple=False).item()  # stride 16 index
    self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = (
        BCEcls,
        BCEobj,
        model.gr,
        h,
        autobalance,
    )
    for k in "na", "nc", "nl", "anchors":
        setattr(self, k, getattr(det, k))


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/Users/glennjocher/opt/anaconda3/envs/env1/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-5-be04c762b799>", line 5, in <module>
c = a / 0
RuntimeError: ZeroDivisionError

# Fixed code
def __init__(self, model, autobalance=False):
    super(ComputeLoss, self).__init__()
    device = next(model.parameters()).device  # get model device
    h = model.hyp  # hyperparameters

    # Define criteria
    BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["cls_pw"]], device=device))
    BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["obj_pw"]], device=device))

    # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
    self.cp, self.cn = smooth_BCE(eps=0.0)

    # Focal loss
    g = h["fl_gamma"]  # focal loss gamma
    if g > 0:
        BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)

    det = (
        model.module.model[-1] if is_parallel(model) else model.model[-1]
    )  # Detect() module
    self.balance = {3: [4.0, 1.0, 0.4]}.get(
        det.nl, [4.0, 1.0, 0.25, 0.06, 0.02]
    )  # P3-P7
    self.ssi = list(det.stride).index(16) if autobalance else 0  # stride 16 index
    self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = (
        BCEcls,
        BCEobj,
        model.gr,
        h,
        autobalance,
    )
    for k in "na", "nc", "nl", "anchors":
        setattr(self, k, getattr(det, k))
# Buggy code
def __init__(self, c1, c2, k, s):
    super(GhostBottleneck, self).__init__()
    c_ = c2 // 2
    self.conv = nn.Sequential(
        GhostConv(c1, c_, 1, 1),  # pw
        DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(),  # dw
        GhostConv(c_, c2, 1, 1, act=False),
    )  # pw-linear
    self.shortcut = (
        nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, act=False))
        if s == 2
        else nn.Identity()
    )


# Traceback (TypeError)
TypeError                                 Traceback (most recent call last)
<ipython-input-2-7facafecdabb> in <module>()
----> 1 model = Model("./models/yolov5s.yaml")
2

<ipython-input-1-7b447b7ed90c> in __init__(self, cfg, ch, nc)
78             logger.info('Overriding model.yaml nc=%g with nc=%g' % (self.yaml['nc'], nc))
79             self.yaml['nc'] = nc  # override yaml value
---> 80         self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch])  # model, savelist
81         self.names = [str(i) for i in range(self.yaml['nc'])]  # default names
82         # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])

<ipython-input-1-7b447b7ed90c> in parse_model(d, ch)
252
253         print(m, args)
--> 254         m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args)  # module
255         t = str(m)[8:-2].replace('__main__.', '')  # module type
256         np = sum([x.numel() for x in m_.parameters()])  # number params

TypeError: __init__() missing 1 required positional argument: 's'

# Fixed code
def __init__(self, c1, c2, k=3, s=1):  # ch_in, ch_out, kernel, stride
    super(GhostBottleneck, self).__init__()
    c_ = c2 // 2
    self.conv = nn.Sequential(
        GhostConv(c1, c_, 1, 1),  # pw
        DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(),  # dw
        GhostConv(c_, c2, 1, 1, act=False),
    )  # pw-linear
    self.shortcut = (
        nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, act=False))
        if s == 2
        else nn.Identity()
    )
# Buggy code
def color_list():
    # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
    def hex2rgb(h):
        return tuple(int(h[1 + i : 1 + i + 2], 16) for i in (0, 2, 4))

    return [hex2rgb(h) for h in plt.rcParams["axes.prop_cycle"].by_key()["color"]]


# Traceback (TypeError)
Traceback (most recent call last):
File "D:\software\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "D:\software\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "D:\yolov5\utils\plots.py", line 124, in plot_images
colors = color_list()  # list of colors
File "D:\yolov5\utils\plots.py", line 34, in color_list
return [hex2rgb(h) for h in plt.rcParams['axes.prop_cycle'].by_key()['color']]
File "D:\yolov5\utils\plots.py", line 34, in <listcomp>
return [hex2rgb(h) for h in plt.rcParams['axes.prop_cycle'].by_key()['color']]
File "D:\yolov5\utils\plots.py", line 32, in hex2rgb
return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
File "D:\yolov5\utils\plots.py", line 32, in <genexpr>
return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
TypeError: int() can't convert non-string with explicit base

# Fixed code
def color_list():
    # Return first 10 plt colors as (r,g,b) https://stackoverflow.com/questions/51350872/python-from-color-name-to-rgb
    def hex2rgb(h):
        return tuple(int(h[1 + i : 1 + i + 2], 16) for i in (0, 2, 4))

    return [
        hex2rgb(h) for h in matplotlib.colors.TABLEAU_COLORS.values()
    ]  # or BASE_ (8), CSS4_ (148), XKCD_ (949)
# Buggy code
def __init__(self, path, img_size=640):
    p = str(Path(path))  # os-agnostic
    p = os.path.abspath(p)  # absolute path
    if "*" in p:
        files = sorted(glob.glob(p, recursive=True))  # glob
    elif os.path.isdir(p):
        files = sorted(glob.glob(os.path.join(p, "*.*")))  # dir
    elif os.path.isfile(p):
        files = [p]  # files
    else:
        raise Exception("ERROR: %s does not exist" % p)

    images = [x for x in files if x.split(".")[-1].lower() in img_formats]
    videos = [x for x in files if x.split(".")[-1].lower() in vid_formats]
    ni, nv = len(images), len(videos)

    self.img_size = img_size
    self.files = images + videos
    self.nf = ni + nv  # number of files
    self.video_flag = [False] * ni + [True] * nv
    self.mode = "images"
    if any(videos):
        self.new_video(videos[0])  # new video
    else:
        self.cap = None
    assert self.nf > 0, (
        "No images or videos found in %s. Supported formats are:\nimages: %s\nvideos: %s"
        % (p, img_formats, vid_formats)
    )


# Traceback (RuntimeError)
** On entry to DGEBAL parameter number  3 had an illegal value
** On entry to DGEHRD  parameter number  2 had an illegal value
** On entry to DORGHR DORGQR parameter number  2 had an illegal value
** On entry to DHSEQR parameter number  4 had an illegal value
Traceback (most recent call last):
File "D:\Softwares\Python\lib\site-packages\numpy\__init__.py", line 305, in <module>
_win_os_check()
File "D:\Softwares\Python\lib\site-packages\numpy\__init__.py", line 302, in _win_os_check
raise RuntimeError(msg.format(__file__)) from None
RuntimeError: The current Numpy installation ('D:\\Softwares\\Python\\lib\\site-packages\\numpy\\__init__.py') fails to pass a sanity check due to a bug in the windows runtime. See this issue for more information: https://tinyurl.com/y3dm3h86
Traceback (most recent call last):
File ".\detect.py", line 5, in <module>
import cv2
File "D:\Softwares\Python\lib\site-packages\cv2\__init__.py", line 5, in <module>
from .cv2 import *
ImportError: numpy.core.multiarray failed to import

# Fixed code
def __init__(self, path, img_size=640):
    p = str(Path(path))  # os-agnostic
    p = os.path.abspath(p)  # absolute path
    if "*" in p:
        files = sorted(glob.glob(p, recursive=True))  # glob
    elif os.path.isdir(p):
        files = sorted(glob.glob(os.path.join(p, "*.*")))  # dir
    elif os.path.isfile(p):
        files = [p]  # files
    else:
        raise Exception("ERROR: %s does not exist" % p)

    images = [x for x in files if x.split(".")[-1].lower() in img_formats]
    videos = [x for x in files if x.split(".")[-1].lower() in vid_formats]
    ni, nv = len(images), len(videos)

    self.img_size = img_size
    self.files = images + videos
    self.nf = ni + nv  # number of files
    self.video_flag = [False] * ni + [True] * nv
    self.mode = "image"
    if any(videos):
        self.new_video(videos[0])  # new video
    else:
        self.cap = None
    assert self.nf > 0, (
        "No images or videos found in %s. Supported formats are:\nimages: %s\nvideos: %s"
        % (p, img_formats, vid_formats)
    )
# Buggy code
def output_to_target(output, width, height):
    # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
    if isinstance(output, torch.Tensor):
        output = output.cpu().numpy()

    targets = []
    for i, o in enumerate(output):
        if o is not None:
            for pred in o:
                box = pred[:4]
                w = (box[2] - box[0]) / width
                h = (box[3] - box[1]) / height
                x = box[0] / width + w / 2
                y = box[1] / height + h / 2
                conf = pred[4]
                cls = int(pred[5])

                targets.append([i, cls, x, y, w, h, conf])

    return np.array(targets)


# Traceback (ValueError)
Traceback (most recent call last):
File "train.py", line 491, in <module>
train(hyp, opt, device, tb_writer, wandb)
File "train.py", line 186, in train
mlc = np.concatenate(dataset.labels, 0)[:, 0].max()  # max label class
File "<__array_function__ internals>", line 6, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 114824 has 1 dimension(s)

# Fixed code
def output_to_target(output):
    # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
    targets = []
    for i, o in enumerate(output):
        for *box, conf, cls in o.cpu().numpy():
            targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
    return np.array(targets)
# Buggy code
def init_seeds(seed=0):
    random.seed(seed)
    np.random.seed(seed)
    init_seeds(seed=seed)


# Traceback (RecursionError)
RecursionError                            Traceback (most recent call last)
<ipython-input-2-f6caabb30a03> in <module>
----> 1 init_seeds()

~/git/yolov5/utils/general.py in init_seeds(seed)
57     random.seed(seed)
58     np.random.seed(seed)
---> 59     init_seeds(seed=seed)
60
61

... last 1 frames repeated, from the frame below ...

~/git/yolov5/utils/general.py in init_seeds(seed)
57     random.seed(seed)
58     np.random.seed(seed)
---> 59     init_seeds(seed=seed)
60
61

RecursionError: maximum recursion depth exceeded while calling a Python object

# Fixed code
def init_seeds(seed=0):
    random.seed(seed)
    np.random.seed(seed)
    init_torch_seeds(seed=seed)
# Buggy code
def print_mutation(hyp, results, bucket=""):
    # Print mutation results to evolve.txt (for use with train.py --evolve)
    a = "%10s" * len(hyp) % tuple(hyp.keys())  # hyperparam keys
    b = "%10.3g" * len(hyp) % tuple(hyp.values())  # hyperparam values
    c = "%10.4g" * len(results) % results  # results (P, R, mAP, F1, test_loss)
    print("\n%s\n%s\nEvolved fitness: %s\n" % (a, b, c))

    if bucket:
        os.system("gsutil cp gs://%s/evolve.txt ." % bucket)  # download evolve.txt

    with open("evolve.txt", "a") as f:  # append result
        f.write(c + b + "\n")
    x = np.unique(np.loadtxt("evolve.txt", ndmin=2), axis=0)  # load unique rows
    np.savetxt(
        "evolve.txt", x[np.argsort(-fitness(x))], "%10.3g"
    )  # save sort by fitness

    if bucket:
        os.system("gsutil cp evolve.txt gs://%s" % bucket)  # upload evolve.txt


# Traceback (TypeError)
Traceback (most recent call last):
File "yolov5/train.py", line 516, in <module>
print_mutation(hyp, results, opt.bucket)
File "/content/drive/.shortcut-targets-by-id/1hQ281-8ogL2dJzHbXZSWEYDIYei6RRbe/YOLOv5/yolov5/utils/utils.py", line 830, in print_mutation
b = '%10.3g' * len(hyp) % tuple(hyp.values())  # hyperparam values
TypeError: must be real number, not str

# Fixed code
def print_mutation(hyp, results, yaml_file="hyp_evolved.yaml", bucket=""):
    # Print mutation results to evolve.txt (for use with train.py --evolve)
    a = "%10s" * len(hyp) % tuple(hyp.keys())  # hyperparam keys
    b = "%10.3g" * len(hyp) % tuple(hyp.values())  # hyperparam values
    c = (
        "%10.4g" * len(results) % results
    )  # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
    print("\n%s\n%s\nEvolved fitness: %s\n" % (a, b, c))

    if bucket:
        os.system("gsutil cp gs://%s/evolve.txt ." % bucket)  # download evolve.txt

    with open("evolve.txt", "a") as f:  # append result
        f.write(c + b + "\n")
    x = np.unique(np.loadtxt("evolve.txt", ndmin=2), axis=0)  # load unique rows
    x = x[np.argsort(-fitness(x))]  # sort
    np.savetxt("evolve.txt", x, "%10.3g")  # save sort by fitness

    if bucket:
        os.system("gsutil cp evolve.txt gs://%s" % bucket)  # upload evolve.txt

    # Save yaml
    for i, k in enumerate(hyp.keys()):
        hyp[k] = float(x[0, i + 7])
    with open(yaml_file, "w") as f:
        f.write(
            "# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: "
            % len(x)
            + c
            + "\n\n"
        )
        yaml.dump(hyp, f, sort_keys=False)
# Buggy code
def plot_evolution_results(
    hyp,
):  # from utils.utils import *; plot_evolution_results(hyp)
    # Plot hyperparameter evolution results in evolve.txt
    x = np.loadtxt("evolve.txt", ndmin=2)
    f = fitness(x)
    # weights = (f - f.min()) ** 2  # for weighted results
    plt.figure(figsize=(12, 10), tight_layout=True)
    matplotlib.rc("font", **{"size": 8})
    for i, (k, v) in enumerate(hyp.items()):
        y = x[:, i + 7]
        # mu = (y * weights).sum() / weights.sum()  # best weighted result
        mu = y[f.argmax()]  # best single result
        plt.subplot(4, 5, i + 1)
        plt.plot(mu, f.max(), "o", markersize=10)
        plt.plot(y, f, ".")
        plt.title("%s = %.3g" % (k, mu), fontdict={"size": 9})  # limit to 40 characters
        print("%15s: %.3g" % (k, mu))
    plt.savefig("evolve.png", dpi=200)


# Traceback (TypeError)
Traceback (most recent call last):
File "yolov5/train.py", line 516, in <module>
print_mutation(hyp, results, opt.bucket)
File "/content/drive/.shortcut-targets-by-id/1hQ281-8ogL2dJzHbXZSWEYDIYei6RRbe/YOLOv5/yolov5/utils/utils.py", line 830, in print_mutation
b = '%10.3g' * len(hyp) % tuple(hyp.values())  # hyperparam values
TypeError: must be real number, not str

# Fixed code
def plot_evolution_results(
    yaml_file="hyp_evolved.yaml",
):  # from utils.utils import *; plot_evolution_results()
    # Plot hyperparameter evolution results in evolve.txt
    with open(yaml_file) as f:
        hyp = yaml.load(f, Loader=yaml.FullLoader)
    x = np.loadtxt("evolve.txt", ndmin=2)
    f = fitness(x)
    # weights = (f - f.min()) ** 2  # for weighted results
    plt.figure(figsize=(14, 10), tight_layout=True)
    matplotlib.rc("font", **{"size": 8})
    for i, (k, v) in enumerate(hyp.items()):
        y = x[:, i + 7]
        # mu = (y * weights).sum() / weights.sum()  # best weighted result
        mu = y[f.argmax()]  # best single result
        plt.subplot(4, 6, i + 1)
        plt.plot(mu, f.max(), "o", markersize=10)
        plt.plot(y, f, ".")
        plt.title("%s = %.3g" % (k, mu), fontdict={"size": 9})  # limit to 40 characters
        print("%15s: %.3g" % (k, mu))
    plt.savefig("evolve.png", dpi=200)
    print("\nPlot saved as evolve.png")
# Buggy code
def hist2d(x, y, n=100):
    xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
    hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
    xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
    yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
    return np.log(hist[xidx, yidx])


# Traceback (TypeError)
Traceback (most recent call last):
File "yolov5/train.py", line 516, in <module>
print_mutation(hyp, results, opt.bucket)
File "/content/drive/.shortcut-targets-by-id/1hQ281-8ogL2dJzHbXZSWEYDIYei6RRbe/YOLOv5/yolov5/utils/utils.py", line 830, in print_mutation
b = '%10.3g' * len(hyp) % tuple(hyp.values())  # hyperparam values
TypeError: must be real number, not str

# Fixed code
def hist2d(x, y, n=100):
    # 2d histogram used in labels.png and evolve.png
    xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
    hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
    xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
    yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
    return np.log(hist[xidx, yidx])
# Buggy code
def plot_labels(labels, save_dir=""):
    # plot dataset labels
    def hist2d(x, y, n=100):
        xedges, yedges = (
            np.linspace(x.min(), x.max(), n),
            np.linspace(y.min(), y.max(), n),
        )
        hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
        xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
        yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
        return np.log(hist[xidx, yidx])

    c, b = labels[:, 0], labels[:, 1:].transpose()  # classes, boxes
    nc = int(c.max() + 1)  # number of classes

    fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
    ax = ax.ravel()
    ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
    ax[0].set_xlabel("classes")
    ax[1].scatter(b[0], b[1], c=hist2d(b[0], b[1], 90), cmap="jet")
    ax[1].set_xlabel("x")
    ax[1].set_ylabel("y")
    ax[2].scatter(b[2], b[3], c=hist2d(b[2], b[3], 90), cmap="jet")
    ax[2].set_xlabel("width")
    ax[2].set_ylabel("height")
    plt.savefig(Path(save_dir) / "labels.png", dpi=200)
    plt.close()


# Traceback (TypeError)
Traceback (most recent call last):
File "yolov5/train.py", line 516, in <module>
print_mutation(hyp, results, opt.bucket)
File "/content/drive/.shortcut-targets-by-id/1hQ281-8ogL2dJzHbXZSWEYDIYei6RRbe/YOLOv5/yolov5/utils/utils.py", line 830, in print_mutation
b = '%10.3g' * len(hyp) % tuple(hyp.values())  # hyperparam values
TypeError: must be real number, not str

# Fixed code
def plot_labels(labels, save_dir=""):
    # plot dataset labels
    c, b = labels[:, 0], labels[:, 1:].transpose()  # classes, boxes
    nc = int(c.max() + 1)  # number of classes

    fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
    ax = ax.ravel()
    ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
    ax[0].set_xlabel("classes")
    ax[1].scatter(b[0], b[1], c=hist2d(b[0], b[1], 90), cmap="jet")
    ax[1].set_xlabel("x")
    ax[1].set_ylabel("y")
    ax[2].scatter(b[2], b[3], c=hist2d(b[2], b[3], 90), cmap="jet")
    ax[2].set_xlabel("width")
    ax[2].set_ylabel("height")
    plt.savefig(Path(save_dir) / "labels.png", dpi=200)
    plt.close()
# Buggy code
def print_mutation(hyp, results, yaml_file="hyp_evolved.yaml", bucket=""):
    # Print mutation results to evolve.txt (for use with train.py --evolve)
    a = "%10s" * len(hyp) % tuple(hyp.keys())  # hyperparam keys
    b = "%10.3g" * len(hyp) % tuple(hyp.values())  # hyperparam values
    c = (
        "%10.4g" * len(results) % results
    )  # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
    print("\n%s\n%s\nEvolved fitness: %s\n" % (a, b, c))

    if bucket:
        os.system("gsutil cp gs://%s/evolve.txt ." % bucket)  # download evolve.txt

    with open("evolve.txt", "a") as f:  # append result
        f.write(c + b + "\n")
    x = np.unique(np.loadtxt("evolve.txt", ndmin=2), axis=0)  # load unique rows
    x = x[np.argsort(-fitness(x))]  # sort
    np.savetxt("evolve.txt", x, "%10.3g")  # save sort by fitness

    if bucket:
        os.system("gsutil cp evolve.txt gs://%s" % bucket)  # upload evolve.txt

    # Save yaml
    for i, k in enumerate(hyp.keys()):
        hyp[k] = float(x[0, i + 7])
    with open(yaml_file, "w") as f:
        f.write(
            "# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: "
            % len(x)
            + c
            + "\n\n"
        )
        yaml.dump(hyp, f, sort_keys=False)


# Traceback (TypeError)
Traceback (most recent call last):
File "yolov5/train.py", line 516, in <module>
print_mutation(hyp, results, opt.bucket)
File "/content/drive/.shortcut-targets-by-id/1hQ281-8ogL2dJzHbXZSWEYDIYei6RRbe/YOLOv5/yolov5/utils/utils.py", line 830, in print_mutation
b = '%10.3g' * len(hyp) % tuple(hyp.values())  # hyperparam values
TypeError: must be real number, not str

# Fixed code
def print_mutation(hyp, results, yaml_file="hyp_evolved.yaml", bucket=""):
    # Print mutation results to evolve.txt (for use with train.py --evolve)
    a = "%10s" * len(hyp) % tuple(hyp.keys())  # hyperparam keys
    b = "%10.3g" * len(hyp) % tuple(hyp.values())  # hyperparam values
    c = (
        "%10.4g" * len(results) % results
    )  # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
    print("\n%s\n%s\nEvolved fitness: %s\n" % (a, b, c))

    if bucket:
        os.system("gsutil cp gs://%s/evolve.txt ." % bucket)  # download evolve.txt

    with open("evolve.txt", "a") as f:  # append result
        f.write(c + b + "\n")
    x = np.unique(np.loadtxt("evolve.txt", ndmin=2), axis=0)  # load unique rows
    x = x[np.argsort(-fitness(x))]  # sort
    np.savetxt("evolve.txt", x, "%10.3g")  # save sort by fitness

    if bucket:
        os.system("gsutil cp evolve.txt gs://%s" % bucket)  # upload evolve.txt

    # Save yaml
    for i, k in enumerate(hyp.keys()):
        hyp[k] = float(x[0, i + 7])
    with open(yaml_file, "w") as f:
        results = x[0, :7]
        c = (
            "%10.4g" * len(results) % results
        )  # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
        f.write(
            "# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: "
            % len(x)
            + c
            + "\n\n"
        )
        yaml.dump(hyp, f, sort_keys=False)
# Buggy code
def __call__(self, parent, index):
    _val = self._init(parent, index)
    if self._dimen in {1, None, UnknownSetDimen}:
        return _val
    elif _val is Set.Skip:
        return _val
    elif not _val:
        return _val

    if not isinstance(_val, collections_Sequence):
        _val = tuple(_val)
    if isinstance(_val[0], tuple):
        return _val
    return self._tuplize(_val, parent, index)


# Traceback (IndexError)
a : Size=1, Index=None, Ordered=Insertion
Key  : Dimen : Domain : Size : Members
None :     1 :    Any :    0 :      {}
ERROR: Constructing component 'b' from data=None failed: IndexError: tuple
index out of range
Traceback (most recent call last):
File "blah.py", line 18, in <module>
m.b = pe.Set(initialize=b_rule, dimen=2)
File "/.../pyomo/pyomo/core/base/block.py", line 543, in __setattr__
self.add_component(name, val)
File "/.../pyomo/pyomo/core/base/block.py", line 1079, in add_component
val.construct(data)
File "/.../pyomo/pyomo/core/base/util.py", line 125, in construct
return base.construct(self, data)
File "/.../pyomo/pyomo/core/base/set.py", line 1976, in construct
self._getitem_when_not_present(index)
File "/.../pyomo/pyomo/core/base/set.py", line 2019, in _getitem_when_not_present
_values = self._init_values(_block, index)
File "/.../pyomo/pyomo/core/base/set.py", line 419, in __call__
if isinstance(_val[0], tuple):
IndexError: tuple index out of range

# Fixed code
def __call__(self, parent, index):
    _val = self._init(parent, index)
    if self._dimen in {1, None, UnknownSetDimen}:
        return _val
    elif _val is Set.Skip:
        return _val
    elif not _val:
        return _val

    if not isinstance(_val, collections_Sequence):
        _val = tuple(_val)
    if len(_val) == 0:
        return _val
    if isinstance(_val[0], tuple):
        return _val
    return self._tuplize(_val, parent, index)
# Buggy code
def set_value(self, val):
    for k in list(getattr(self, "_decl", {})):
        self.del_component(k)
    self._ctypes = {}
    self._decl = {}
    self._decl_order = []
    if val:
        for k in sorted(iterkeys(val)):
            self.add_component(k, val[k])


# Traceback (TypeError)
Traceback (most recent call last):
File "blockSetValue.py", line 11, in <module>
m.block_list[1] = movingBlock
File "/home/esjohn/src/pyomo/pyomo/core/base/indexed_component.py", line 412, in __setitem__
return self._setitem_when_not_present(index, val)
File "/home/esjohn/src/pyomo/pyomo/core/base/indexed_component.py", line 675, in _setitem_when_not_present
obj.set_value(value)
File "/home/esjohn/src/pyomo/pyomo/core/base/block.py", line 711, in set_value
self.add_component(k,val[k])
File "/home/esjohn/src/pyomo/pyomo/core/base/block.py", line 923, in add_component
super(_BlockData, self).__setattr__(name, val)
TypeError: attribute name must be string, not 'NoneType'

# Fixed code
def set_value(self, val):
    raise RuntimeError(
        textwrap.dedent(
            """\
            Block components do not support assignment or set_value().
            Use the transfer_attributes_from() method to transfer the
            components and public attributes from one block to another:
                model.b[1].transfer_attributes_from(other_block)
            """
        )
    )
# Buggy code
def _getitem_when_not_present(self, idx):
    return self._setitem_when_not_present(idx, None)


# Traceback (TypeError)
Traceback (most recent call last):
File "blockSetValue.py", line 11, in <module>
m.block_list[1] = movingBlock
File "/home/esjohn/src/pyomo/pyomo/core/base/indexed_component.py", line 412, in __setitem__
return self._setitem_when_not_present(index, val)
File "/home/esjohn/src/pyomo/pyomo/core/base/indexed_component.py", line 675, in _setitem_when_not_present
obj.set_value(value)
File "/home/esjohn/src/pyomo/pyomo/core/base/block.py", line 711, in set_value
self.add_component(k,val[k])
File "/home/esjohn/src/pyomo/pyomo/core/base/block.py", line 923, in add_component
super(_BlockData, self).__setattr__(name, val)
TypeError: attribute name must be string, not 'NoneType'

# Fixed code
def _getitem_when_not_present(self, idx):
    return self._setitem_when_not_present(idx)
# Buggy code
def _setitem_when_not_present(self, index, value):
    """Perform the fundamental component item creation and storage.

    Components that want to implement a nonstandard storage mechanism
    should override this method.

    Implementations may assume that the index has already been
    validated and is a legitimate entry in the _data dict.
    """
    #
    # If we are a scalar, then idx will be None (_validate_index ensures
    # this)
    if index is None and not self.is_indexed():
        obj = self._data[index] = self
    else:
        obj = self._data[index] = self._ComponentDataClass(component=self)
    try:
        obj.set_value(value)
        return obj
    except:
        del self._data[index]
        raise


# Traceback (TypeError)
Traceback (most recent call last):
File "blockSetValue.py", line 11, in <module>
m.block_list[1] = movingBlock
File "/home/esjohn/src/pyomo/pyomo/core/base/indexed_component.py", line 412, in __setitem__
return self._setitem_when_not_present(index, val)
File "/home/esjohn/src/pyomo/pyomo/core/base/indexed_component.py", line 675, in _setitem_when_not_present
obj.set_value(value)
File "/home/esjohn/src/pyomo/pyomo/core/base/block.py", line 711, in set_value
self.add_component(k,val[k])
File "/home/esjohn/src/pyomo/pyomo/core/base/block.py", line 923, in add_component
super(_BlockData, self).__setattr__(name, val)
TypeError: attribute name must be string, not 'NoneType'

# Fixed code
def _setitem_when_not_present(self, index, value=_NotSpecified):
    """Perform the fundamental component item creation and storage.

    Components that want to implement a nonstandard storage mechanism
    should override this method.

    Implementations may assume that the index has already been
    validated and is a legitimate entry in the _data dict.
    """
    #
    # If we are a scalar, then idx will be None (_validate_index ensures
    # this)
    if index is None and not self.is_indexed():
        obj = self._data[index] = self
    else:
        obj = self._data[index] = self._ComponentDataClass(component=self)
    try:
        if value is not _NotSpecified:
            obj.set_value(value)
    except:
        del self._data[index]
        raise
    return obj
# Buggy code
def set_value(self, val):
    _indicator_var = self.indicator_var
    # Remove everything
    for k in list(getattr(self, "_decl", {})):
        self.del_component(k)
    self._ctypes = {}
    self._decl = {}
    self._decl_order = []
    # Now copy over everything from the other block.  If the other
    # block has an indicator_var, it should override this block's.
    # Otherwise restore this block's indicator_var.
    if val:
        if "indicator_var" not in val:
            self.add_component("indicator_var", _indicator_var)
        for k in sorted(iterkeys(val)):
            self.add_component(k, val[k])
    else:
        self.add_component("indicator_var", _indicator_var)


# Traceback (TypeError)
Traceback (most recent call last):
File "blockSetValue.py", line 11, in <module>
m.block_list[1] = movingBlock
File "/home/esjohn/src/pyomo/pyomo/core/base/indexed_component.py", line 412, in __setitem__
return self._setitem_when_not_present(index, val)
File "/home/esjohn/src/pyomo/pyomo/core/base/indexed_component.py", line 675, in _setitem_when_not_present
obj.set_value(value)
File "/home/esjohn/src/pyomo/pyomo/core/base/block.py", line 711, in set_value
self.add_component(k,val[k])
File "/home/esjohn/src/pyomo/pyomo/core/base/block.py", line 923, in add_component
super(_BlockData, self).__setattr__(name, val)
TypeError: attribute name must be string, not 'NoneType'

# Fixed code
def set_value(self, val, guarantee_components=set()):
    # Copy over everything from the other block.  If the other
    # block has an indicator_var, it should override this block's.
    # Otherwise restore this block's indicator_var.
    guarantee_components.add("indicator_var")
    super(_DisjunctData, self).set_value(val, guarantee_components)
# Buggy code
def _disable_method(fcn, msg=None):
    if msg is None:
        msg = "access %s on" % (fcn.__name__,)

    def impl(self, *args, **kwds):
        raise RuntimeError(
            "Cannot %s %s '%s' before it has been constructed (initialized)."
            % (msg, type(self).__name__, self.name)
        )

    # functools.wraps doesn't preserve the function signature until
    # Python 3.4.  For backwards compatability with Python 2.x, we will
    # create a temporary (lambda) function using eval that matches the
    # function signature passed in and calls the generic impl() function
    args = inspect.formatargspec(*inspect.getargspec(fcn))
    impl_args = eval("lambda %s: impl%s" % (args[1:-1], args), {"impl": impl})
    return functools.wraps(fcn)(impl_args)


# Traceback (AttributeError)
======================================================================
ERROR: test_bundles (pyomo.pysp.tests.unit.test_scenariotree.TestScenarioTreeFromNetworkX)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/build/Pyomo/pyomo/pyomo/pysp/tests/unit/test_scenariotree.py", line 745, in test_bundles
edge_probability_attribute=None)
File "/home/travis/build/Pyomo/pyomo/pyomo/pysp/scenariotree/tree_structure_model.py", line 313, in ScenarioTreeModelFromNetworkX
networkx.dfs_successors(tree, root))
File "/home/travis/build/Pyomo/pyomo/pyomo/pysp/scenariotree/tree_structure_model.py", line 296, in _setup
_setup(v, succ)
File "/home/travis/build/Pyomo/pyomo/pyomo/pysp/scenariotree/tree_structure_model.py", line 311, in _setup
tree.node[u].get('bundle', None)
AttributeError: 'DiGraph' object has no attribute 'node'

# Fixed code
def _disable_method(fcn, msg=None):
    if msg is None:
        msg = "access %s on" % (fcn.__name__,)

    def impl(self, *args, **kwds):
        raise RuntimeError(
            "Cannot %s %s '%s' before it has been constructed (initialized)."
            % (msg, type(self).__name__, self.name)
        )

    # functools.wraps doesn't preserve the function signature until
    # Python 3.4.  For backwards compatability with Python 2.x, we will
    # create a temporary (lambda) function using eval that matches the
    # function signature passed in and calls the generic impl() function
    args = inspect.formatargspec(*getargspec(fcn))
    impl_args = eval("lambda %s: impl%s" % (args[1:-1], args), {"impl": impl})
    return functools.wraps(fcn)(impl_args)
# Buggy code
def _setup(u, succ):
    if node_name_attribute is not None:
        if node_name_attribute not in tree.node[u]:
            raise KeyError(
                "node '%s' missing node name attribute: '%s'" % (u, node_name_attribute)
            )
        node_name = tree.node[u][node_name_attribute]
    else:
        node_name = u
    node_to_name[u] = node_name
    m.Nodes.add(node_name)
    if u in succ:
        for v in succ[u]:
            _setup(v, succ)
    else:
        # a leaf node
        if scenario_name_attribute is not None:
            if scenario_name_attribute not in tree.node[u]:
                raise KeyError(
                    "node '%s' missing scenario name "
                    "attribute: '%s'" % (u, scenario_name_attribute)
                )
            scenario_name = tree.node[u][scenario_name_attribute]
        else:
            scenario_name = u
        node_to_scenario[u] = scenario_name
        m.Scenarios.add(scenario_name)
        scenario_bundle[scenario_name] = tree.node[u].get("bundle", None)


# Traceback (AttributeError)
======================================================================
ERROR: test_bundles (pyomo.pysp.tests.unit.test_scenariotree.TestScenarioTreeFromNetworkX)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/build/Pyomo/pyomo/pyomo/pysp/tests/unit/test_scenariotree.py", line 745, in test_bundles
edge_probability_attribute=None)
File "/home/travis/build/Pyomo/pyomo/pyomo/pysp/scenariotree/tree_structure_model.py", line 313, in ScenarioTreeModelFromNetworkX
networkx.dfs_successors(tree, root))
File "/home/travis/build/Pyomo/pyomo/pyomo/pysp/scenariotree/tree_structure_model.py", line 296, in _setup
_setup(v, succ)
File "/home/travis/build/Pyomo/pyomo/pyomo/pysp/scenariotree/tree_structure_model.py", line 311, in _setup
tree.node[u].get('bundle', None)
AttributeError: 'DiGraph' object has no attribute 'node'

# Fixed code
def _setup(u, succ):
    if node_name_attribute is not None:
        if node_name_attribute not in tree.nodes[u]:
            raise KeyError(
                "node '%s' missing node name attribute: '%s'" % (u, node_name_attribute)
            )
        node_name = tree.nodes[u][node_name_attribute]
    else:
        node_name = u
    node_to_name[u] = node_name
    m.Nodes.add(node_name)
    if u in succ:
        for v in succ[u]:
            _setup(v, succ)
    else:
        # a leaf node
        if scenario_name_attribute is not None:
            if scenario_name_attribute not in tree.nodes[u]:
                raise KeyError(
                    "node '%s' missing scenario name "
                    "attribute: '%s'" % (u, scenario_name_attribute)
                )
            scenario_name = tree.nodes[u][scenario_name_attribute]
        else:
            scenario_name = u
        node_to_scenario[u] = scenario_name
        m.Scenarios.add(scenario_name)
        scenario_bundle[scenario_name] = tree.nodes[u].get("bundle", None)
# Buggy code
def normalize_index(index):
    """
    Flatten a component index.  If it has length 1, then
    return just the element.  If it has length > 1, then
    return a tuple.
    """
    idx = pyutilib.misc.flatten(index)
    if type(idx) is list:
        if len(idx) == 1:
            idx = idx[0]
        else:
            idx = tuple(idx)
    return idx


# Traceback (pyomo.util._config.DeveloperError)
qichen@QC-CMU-Tower:~$ pyothon
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
from pyomo.environ import *
m = ConcreteModel()
m.s = Set(initialize=['one'])
m.c = Constraint(m.s)
m.c[m.s].deactivate()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/qichen/.solvers/pyomo/src/pyomo/pyomo/core/base/indexed_component.py", line 492, in __getitem__
return self._default(ndx)
File "/home/qichen/.solvers/pyomo/src/pyomo/pyomo/core/base/indexed_component.py", line 655, in _default
% (self.__class__.__name__,))
pyomo.util._config.DeveloperError: Internal Pyomo implementation error:
'Derived component IndexedConstraint failed to define _default().'
Please report this to the Pyomo Developers.


# Fixed code
def normalize_index(index):
    """
    Flatten a component index.  If it has length 1, then
    return just the element.  If it has length > 1, then
    return a tuple.
    """
    ans = flatten(index)
    if len(ans) == 1:
        return ans[0]
    return ans
# Buggy code
def load():
    import pyomo.scripting.plugins.check
    import pyomo.scripting.plugins.convert
    import pyomo.scripting.plugins.solve
    import pyomo.scripting.plugins.download
    import pyomo.scripting.plugins.build_ext


# Traceback (ModuleNotFoundError)
Traceback (most recent call last):
File "/XXX/myvenv/bin/get_pyomo_extras", line 7, in <module>
from scripts.get_pyomo_extras import main
ModuleNotFoundError: No module named 'scripts'

# Fixed code
def load():
    import pyomo.scripting.plugins.check
    import pyomo.scripting.plugins.convert
    import pyomo.scripting.plugins.solve
    import pyomo.scripting.plugins.download
    import pyomo.scripting.plugins.build_ext
    import pyomo.scripting.plugins.extras
# Buggy code
def set_proxy(self, proxy):
    self.proxy = proxy


# Traceback (TypeError)
Traceback (most recent call last):
File "/ascldap/users/gseastr/envs/python3.6/bin/pyomo", line 11, in <module>
load_entry_point('Pyomo', 'console_scripts', 'pyomo')()
File "/home/gseastr/envs/pyomo/pyomo/scripting/pyomo_main.py", line 82, in main
retval = _options.func(_options)
File "/home/gseastr/envs/pyomo/pyomo/scripting/driver_help.py", line 456, in help_exec
help_solvers()
File "/home/gseastr/envs/pyomo/pyomo/scripting/driver_help.py", line 373, in help_solvers
kestrel = pyomo.neos.kestrel.kestrelAMPL()
File "/home/gseastr/envs/pyomo/pyomo/neos/kestrel.py", line 66, in __init__
self.setup_connection()
File "/home/gseastr/envs/pyomo/pyomo/neos/kestrel.py", line 87, in setup_connection
result = self.neos.ping()
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1112, in __call__
return self.__send(self.__name, args)
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1452, in __request
verbose=self.__verbose
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1154, in request
return self.single_request(host, handler, request_body, verbose)
File "/home/gseastr/envs/python3.6/lib/python3.6/xmlrpc/client.py", line 1166, in single_request
http_conn = self.send_request(host, handler, request_body, verbose)
TypeError: send_request() takes 4 positional arguments but 5 were given

# Fixed code
def set_proxy(self, host):
    self.proxy = urlparse(host)
    if not self.proxy.hostname:
        # User omitted scheme from the proxy; assume http
        self.proxy = urlparse("http://" + proxy)