@@ -72,7 +72,7 @@ def main():
         pastTime=startTime
         if d < commandLength:
             pastTime=startTime-commandLength
-            printout="Due to long processing time the look-back time has been extended to " +str(pastTime.total_seconds()) + " seconds" + "\n"
+            printout="Due to long processing time the look-back time has been extended to " +str(commandLength.total_seconds()) + " seconds" + "\n"
             f.write(printout)
         else:
             pastTime=startTime-d


@@ -3524,7 +3524,7 @@ def iodp_kly4s_lore(kly4s_file, meas_out='measurements.txt',
     tau3=in_df['Kmin susceptibility (SI)']/3
     v3_dec=in_df['Kmin dec (deg)']
     v3_inc=in_df['Kmin inc (deg)']
-    specimens_df['aniso_v3']=tau1.astype('str')+":"+v3_dec.astype('str')+":"+v3_inc.astype('str')
+    specimens_df['aniso_v3']=tau3.astype('str')+":"+v3_dec.astype('str')+":"+v3_inc.astype('str')

 # output data files


@@ -1671,7 +1671,7 @@ class _DocCreatorVisitor:
         # assign tag to copy now
         variant_copy.tag = self._decode_unary(t.tag.value)

-        return variant
+        return variant_copy

     def _type_to_obj(self, t):
         return self._type_to_obj_map[type(t)](t)


@@ -585,7 +585,7 @@ class YoutubeDataApi:
         else:
             captions = []
             for v_id in video_id:
-                captions.append(_get_captions(video_id, lang_code=lang_code, parser=parser, **kwargs))
+                captions.append(_get_captions(v_id, lang_code=lang_code, parser=parser, **kwargs))
         return captions


@@ -85,5 +85,5 @@ def test_handling_bad_package(tmpdir, repodata):
     with bz2.BZ2File(bad_pkg_path, 'wb') as f:
         f.write("This is a fake package".encode())
     assert bad_pkg_name in os.listdir(bad_pkg_root)
-    conda_mirror._validate_packages(repodata, local_repo_root)
+    conda_mirror._validate_packages(repodata, bad_pkg_root)
     assert bad_pkg_name not in os.listdir(bad_pkg_root)
\ No newline at end of file


@@ -45,6 +45,6 @@ def others_months():

 def daterange(start, end, step=datetime.timedelta(1)):
     curr = start
-    while curr < end:
+    while curr <= end:
         yield curr
         curr += step


@@ -5,7 +5,7 @@ MODEL_EXCHANGE = 'model_exchange'

 __REQUIRED_INIT_KWARGS = {AMQP_URL, MODEL_EXCHANGE}
 __OPTIONAL_INIT_KWARGS = set()
-__ALLOWED_INIT_KWARGS = __REQUIRED_INIT_KWARGS & __OPTIONAL_INIT_KWARGS
+__ALLOWED_INIT_KWARGS = __REQUIRED_INIT_KWARGS | __OPTIONAL_INIT_KWARGS

 def init(**kwargs):


@@ -310,7 +310,7 @@ class Parent:
               kwargs (dict) - dict of arg that will be passed to init() as **kwargs (plugins only)
         """
         from kframe.base.plugin import Plugin
-        if issubclass(target, Plugin):
+        if not issubclass(target, Plugin):
             raise ValueError('target ({}) bust be isinstance of kframe.Plugin'.format(str(target)))
         self.plugin_t[kw.get('key', target.name)] = {
             'target': target,


@@ -329,7 +329,7 @@ class Task:
         cfg.update(kwargs)
         if 'shedule' in cfg:
             cfg['shedule'] = self._convert_shedule(cfg['shedule'])
-        self.cfg.update(kwargs)
+        self.cfg.update(cfg)

     def ready_for_run(self, t, tm):
         """


@@ -63,7 +63,7 @@ class Build(Prep):
     def update_version(self, version):
         version = self.versioning(version)
         content = self.get_pkg_init()
-        if b'\n__version__' not in content or not content.startswith(b'__version__'):
+        if b'\n__version__' not in content and not content.startswith(b'__version__'):
             raise IOError("missing __version__ in the package __init__.py file")
         lines = content.splitlines()
         for i, line in enumerate(lines):


@@ -256,7 +256,7 @@ class BatchHeader:
     def _get_effective_entry_date(effective_entry_date):
         _date = datetime.datetime.today()
         _date += datetime.timedelta(days=effective_entry_date)
-        while _date.isoweekday() not in WEEKEND:
+        while _date.isoweekday() in WEEKEND:
             _date += datetime.timedelta(days=1)
         return _date.strftime(day_format_string)


@@ -72,7 +72,7 @@ class Rating(models.Model):
             rating_obj = None

         if rating_obj and rating == 0:
-            return rating.clear()
+            return rating_obj.clear()

         if rating_obj is None:
             rating_obj = cls.objects.create(


@@ -94,7 +94,7 @@ class PatchesGenerator(Dataset):
             img_tensor = self.transform(img_tensor)

         if self.segment_mode:
-            return self.data[ID], img_tensor, self.labels[index]
+            return self.data[index], img_tensor, self.labels[index]

         return img_tensor, self.labels[index]


@@ -96,7 +96,7 @@ class ThrnetTrainer(NNTrainer):
                     img_loss += current_loss

                     thr = thr_map[..., None][..., None]
-                    segmented = (prob_map >= thr.byte())
+                    segmented = (prob_map > thr.byte())

                     # batch_score = ScoreAccumulator().add_tensor(segmented, truth)
                     print('Loss: ', current_loss, end='\r')


@@ -50,7 +50,7 @@ class ThrnetTrainer(NNTrainer):

                 if gen_images:
                     img = segmented_img.clone().cpu().numpy()
-                    img_score.add_array(img_obj.ground_truth, img)
+                    img_score.add_array(img, img_obj.ground_truth)
                     # img = iu.remove_connected_comp(np.array(segmented_img, dtype=np.uint8),
                     #                                connected_comp_diam_limit=10)
                     IMG.fromarray(np.array(img, dtype=np.uint8)).save(


@@ -59,7 +59,7 @@ class UNetNNTrainer(NNTrainer):
                 if gen_images:
                     map_img = map_img.cpu().numpy()
                     predicted_img = predicted_img.cpu().numpy()
-                    img_score.add_array(img_obj.ground_truth, predicted_img)
+                    img_score.add_array(predicted_img, img_obj.ground_truth)
                     IMG.fromarray(np.array(predicted_img, dtype=np.uint8)).save(
                         os.path.join(self.log_dir, 'pred_' + img_obj.file_name.split('.')[0] + '.png'))
                     IMG.fromarray(np.array(map_img, dtype=np.uint8)).save(


@@ -144,7 +144,7 @@ class Star(object):
                 E * self.Tmag**4 + F * self.Tmag**5)

     def get_oneSigmaNoise(self):
-        return (np.exp(self.get_oneHourNoiseLnsigma()) *
+        return (np.exp(self.get_oneHourNoiseLnsigma()) /
                 np.sqrt(self.integration / 60.))

     def TESS_Mag_VJKs(self):


@@ -94,7 +94,7 @@ class SparseRegressionCoefficientSampler():
         ))
         precond_hessian_matvec = lambda beta: \
             precond_prior_prec * beta \
-            + precond_scale * loglik_hessian_matvec(precond_scale * beta)
+            - precond_scale * loglik_hessian_matvec(precond_scale * beta)
         precond_hessian_op = sp.sparse.linalg.LinearOperator(
             (X.shape[1], X.shape[1]), precond_hessian_matvec
         )


@@ -70,7 +70,7 @@ class BayesBridge():
             self.model = LinearModel(outcome, X)
         elif model == 'logit':
             n_success, n_trial = outcome
-            self.model = LogisticModel(n_success, X, n_trial)
+            self.model = LogisticModel(n_success, n_trial, X)
         elif model == 'cox':
             self.model = CoxModel(event_time, censoring_time, X)
         else:


@@ -36,7 +36,7 @@ from btrdb4.endpoint import Endpoint
 from btrdb4.utils import *

 MIN_TIME = -(16 << 56)
-MAX_TIME = 48 >> 56
+MAX_TIME = 48 << 56
 MAX_POINTWIDTH = 63

 class Connection(object):


@@ -62,7 +62,7 @@ def prepare_url(url, source_url=None):
     """operations that purify a url, removes arguments,
     redirects, and merges relatives with absolutes"""

-    if source_url is None:
+    if source_url is not None:
         source_domain = urlparse(source_url).netloc
         proper_url = urljoin(source_url, url)
         proper_url = redirect_back(proper_url, source_domain)

ReplaceText(target=' is not ' @(65,17)->(65,21))


@@ -28,7 +28,7 @@ class Session(object):

         if 'Code' in response:
             raise OnelyaAPIError(method, response, data)
-        return data
+        return response

     def __send_api_request(self, method, data):
         url = '{}{}'.format(Session.API_URL, method)


@@ -50,7 +50,7 @@ def sanitize_redirect(host, redirect_to):
     """
     # Quick sanity check.
     if not redirect_to or \
-       not isinstance(redirect_to, six.string_types) and \
+       not isinstance(redirect_to, six.string_types) or \
        getattr(redirect_to, 'decode', None) and \
        not isinstance(redirect_to.decode(), six.string_types):
         return None


@@ -132,7 +132,7 @@ def partial_pipeline_data(strategy, user, *args, **kwargs):
         kwargs.setdefault('user', user)
         kwargs.setdefault('request', strategy.request)
         kwargs.update(xkwargs)
-        return idx, backend, xargs, xkwargs
+        return idx, backend, xargs, kwargs

 def build_absolute_uri(host_url, path=None):


@@ -27,7 +27,7 @@ class SocialAuthExceptionMiddleware(object):
             return

         if isinstance(exception, SocialAuthBaseException):
-            backend_name = strategy.backend.name
+            backend_name = request.backend.name
             message = self.get_message(request, exception)
             url = self.get_redirect_uri(request, exception)
             try:


@@ -34,7 +34,7 @@ class ComponentSettings:
         """Create app settings, overrided by env."""
         settings = settings or {}
         if base_settings:
-            settings = update_dict_recur(settings, base_settings)
+            settings = update_dict_recur(base_settings, settings)
         for key, value in os.environ.items():
             if 'SETTINGS_' not in key:
                 continue


@@ -141,7 +141,7 @@ class TagAttributes(type):
                     full_attribute_map = dict(parents[0].attribute_map)
                     full_attribute_map.update(attribute_map)
                     attribute_map = full_attribute_map
-                class_dict['attribute_map'] = full_attributes
+                class_dict['attribute_map'] = attribute_map

             class_dict['attribute_descriptors'] = attributes
             attribute_signals = (attribute.signal for attribute in attributes.values() if getattr(attribute, 'signal'))


@@ -557,5 +557,5 @@ class Layer:
         # confirm update

         # update other layer
-        target_layer.update(update_params=payload, token=token)
+        target_layer.update(update_params=filtered_payload, token=token)


@@ -7,7 +7,7 @@ def html_snippet(obj):
     else:
         lat, lon = loc
     content = IListing(obj).summary
-    if lat < 0:
+    if lat > 0:
         hemi = "west"
     else:
         hemi = "east"


@@ -392,7 +392,7 @@ class ModelManager:
                 with open(qc.ref_smd, 'rb') as fb:
                     child_ref = Mesh.parse_smd(fb)

-                if prop.skin != 0 and prop.skin <= len(mdl.skins):
+                if prop.skin != 0 and prop.skin < len(mdl.skins):
                     # We need to rename the materials to match the skin.
                     swap_skins = dict(zip(
                         mdl.skins[0],


@@ -1799,7 +1799,7 @@ class Entity:

         base_name = orig_name.rstrip('0123456789')

-        if self.map.by_target[orig_name]:
+        if self.map.by_target[base_name]:
             # Check every index in order.
             for i in itertools.count(start=1):
                 name = base_name + str(i)


@@ -88,7 +88,7 @@ def main(argv: List[str]) -> None:
         LOGGER.warning('No studiomdl path provided.')
         studiomdl_loc = None

-    run_transformations(vmf, fsys, packlist, path, game_info, studiomdl_loc)
+    run_transformations(vmf, fsys, packlist, bsp_file, game_info, studiomdl_loc)

     if studiomdl_loc is not None and args.propcombine:
         LOGGER.info('Combining props...')


@@ -31,4 +31,4 @@ class Assistant():
         with open(self.setting_file, 'w') as f:
             json.dump(self.setting,f)

-        return True
\ No newline at end of file
+        return False
\ No newline at end of file


@@ -272,7 +272,7 @@ def evalPolynomialDerivative(poly, u, der=1):
     tck, dummy = interpolate.splprep([x.tolist(),x.tolist()], s=0, k=1)
     xU = np.array(interpolate.splev(u, tck)[1])
     out = f2(xU)
-    p = np.array([np.ones((x.shape[0],)), out]).T
+    p = np.array([np.ones((xU.shape[0],)), out]).T
     return p


@@ -509,7 +509,7 @@ def deploy_node(app, deltas={}):
     first_time = False
     if not exists(virtualenv_path):
         echo("-----> Creating virtualenv_path for '{}'".format(app), fg='green')
-        makedirs(node_path)
+        makedirs(virtualenv_path)
         first_time = True
     if not exists(node_path):
         echo("-----> Creating node_modules for '{}'".format(app), fg='green')


@@ -16,7 +16,7 @@ def handle_opts(opts):

 def datahandler(line):
     global n
-    if n > clmax:
+    if n >= clmax:
         raise StopIteration

     n += 1


@@ -45,7 +45,7 @@ class FileChangedDriver(Driver):
         mods = time.strftime('%Y%m%dT%H%M%S', modt)
         return self.format % {
             'version': mods,
-            'path': path,
+            'path': stream,
         }


@@ -7,7 +7,7 @@ if __name__ == '__main__':

     initial_conditions = [0] * 100 + [1] + [0] * 99

-    activities, connectivities = evolve(adjacencies, initial_conditions, timesteps=100,
+    activities, connectivities = evolve(initial_conditions, adjacencies, timesteps=100,
                                         activity_rule=lambda n, c, t: ActivityRule.nks_ca_rule(n, c, 30))

     plot_grid(activities)


@@ -61,7 +61,7 @@ if __name__ == '__main__':

     initial_conditions = half_two

-    activities, connectivities = evolve(hopfield_net.adjacency_matrix, initial_conditions, timesteps=155,
+    activities, connectivities = evolve(initial_conditions, hopfield_net.adjacency_matrix, timesteps=155,
                                         activity_rule=hopfield_net.activity_rule)

     # view the weights, stored in the adjacency matrix


@@ -96,7 +96,7 @@ class TestConfigMapping(unittest.TestCase):
         assert value == bool(new_value) and type(value) == bool, "did not set the correct value from the map, expected {} but got {} (which is not the original {})".format("bool", bool(new_value), type(value), value)
         set_by_path(test_config, path, new_value, is_bool=False)
         int_value = get_by_path(test_config, path)
-        assert new_value == int_value and type(int_value) == int, "did not set the correct value from the map, expected type {} = {} but got type {} = {})".format("int", int_value, type(int_value), new_value)
+        assert value == int_value and type(int_value) == int, "did not set the correct value from the map, expected type {} = {} but got type {} = {})".format("int", int_value, type(int_value), new_value)

     def test_set_from_map_invalid(self):
         test_value = "three_levels"


@@ -188,7 +188,7 @@ def move_does_not_stack_tiles(letter_list, location_set):
     #     return False

 def move_is_rack_size_or_less(location_set):
-    return len(location_set) > config.PLAYER_RACK_SIZE
+    return len(location_set) <= config.PLAYER_RACK_SIZE
         # print('Move places greater than seven tiles.')
     #     return False
     # else:


@@ -179,7 +179,7 @@ def center(target, reference=None):
         geometry = reference.winfo_geometry()
     else:
         geometry = reference
-    if isinstance(reference, str):
+    if isinstance(geometry, str):
         geometry = Geometry(geometry)
     target_geometry = Geometry(target.winfo_geometry())
     target.geometry(str(target_geometry.set_to_center(geometry)))


@@ -13,7 +13,7 @@ def test_IsDone(state):
 def test_NLPIterations(state):
     reward_func = R.NLPIterations()
     reward_func.reset(state)
-    assert reward_func.get(state) >= 0
+    assert reward_func.get(state) <= 0
     assert reward_func.get(state, done=True) == 0


@@ -101,4 +101,4 @@ def test_LpIterations(model):
 def test_NNodes(model):
     reward_func = R.NNodes()
     reward_func.reset(model)
-    assert reward_func.obtain_reward(model) <= 0
+    assert reward_func.obtain_reward(model) >= 0


@@ -313,7 +313,7 @@ class GraphicsView(QGraphicsView):
             event.localPos(),
             event.screenPos(),
             Qt.LeftButton,
-            event.buttons() & -Qt.LeftButton,
+            event.buttons() | -Qt.LeftButton,
             event.modifiers(),
         )
         super().mouseReleaseEvent(fake_event)


@@ -130,7 +130,7 @@ class UMBase:
             return content.data
         lang = attributes.lang()
         if not len(node.children) and content.text is None:
-            if self.nillable(content.data) and content.node.isnil():
+            if self.nillable(content.data) or content.node.isnil():
                 return None
             else:
                 return xlstr.string('', lang)


@@ -113,6 +113,6 @@ class Options(Skin):
             Definition('retxml', bool, False),
             Definition('autoblend', bool, False),
             Definition('cachingpolicy', int, 0),
-            Definition('plugins', [], (list, tuple)),
+            Definition('plugins', (list, tuple), []),
         ]
         Skin.__init__(self, domain, definitions, kwargs)


@@ -122,7 +122,7 @@ class BaseBackend(object):
         self._serial.write(h2b('1d21' + hex))

     def get_characters_per_line(self, font_width):
-        return self.BASE_CHARS_PER_LINE / font_width
+        return self.BASE_CHARS_PER_LINE // font_width

 class Ibm4610Backend(BaseBackend):
     BARCODE_MAP = {


@@ -60,7 +60,7 @@ def iterate_correction(crispr_file, crispr_lib_file, cnv_file, output_folder, bs
     assert len(overlap_genes) > 0, 'No genes (rows) overlap between CRISPR and Copy-number matrices'

     # run correction for each cell line
-    for sample in overlap_genes:
+    for sample in overlap_samples:
         if bsub_flag:
             print('[{}] Crispy: bsub {}'.format(dt.now().strftime('%Y-%m-%d %H:%M:%S'), sample))


@@ -159,4 +159,4 @@ def check_spelling(page, settings):
         message = "No misspellings found" if not found_misspellings else u'Found %s misspelling(s): "%s"' % (len(misspelled), '", "'.join(misspelled))
         return found_misspellings, message

-    return True, 'No article found'
+    return False, 'No article found'


@@ -132,7 +132,7 @@ class Table(object):
         end = row_lenght
         filt_data = []

-        while end < len(self._table_data):
+        while end <= len(self._table_data):
             filt_data.extend(self._filter_list(self._table_data[start:end], mask))
             start = end
             end += row_lenght


@@ -156,7 +156,7 @@ def request(method, path, queryParams=None, content=None):
                     path=path,
                     queryParams=queryParams,
                     content=content)
-    if res.status / 100 != 2:
+    if res.status // 100 != 2:
         raise Exception('{} {}'.format(res.status, res.content['message']))
     return res.content


@@ -111,7 +111,7 @@ if __name__ == '__main__':
         testing_dataset.load(testing_filename, args.nb_testing_image)
     else:
         input_image_dir = os.path.join(input_repo, "testing")
-        testing_dataset.populate(input_image_dir, preprocessed_testing_path,
+        testing_dataset.populate(preprocessed_testing_path, input_image_dir,
                                  nb_images=args.nb_testing_image, labelling=False)
         testing_dataset.save(testing_filename)


@@ -158,7 +158,7 @@ class SemanticSegmentationModel(ConvolutionalNeuralNetwork):
                                                   name=dataset_type+"_images")
             label_filepaths = [dataset.image_info[i]["label_filename"]
                                for i in range(dataset.get_nb_images())]
-            label_tensors = ops.convert_to_tensor(image_filepaths, dtype=tf.string,
+            label_tensors = ops.convert_to_tensor(label_filepaths, dtype=tf.string,
                                                   name=dataset_type+"_labels")
             input_queue = tf.train.slice_input_producer([image_tensors,
                                                          label_tensors],


@@ -449,7 +449,7 @@ def main(args):
         "semseg",
         "predicted_geometries",
     )
-    os.makedirs(predicted_label_folder, exist_ok=True)
+    os.makedirs(predicted_geom_folder, exist_ok=True)
     predicted_geom_file = os.path.join(
         predicted_geom_folder,
         args.image_basename + "_" + str(args.image_size) + ".geojson",


@@ -72,7 +72,7 @@ class VideoFrameGenerator(Sequence):

         # split factor should be a propoer value
         if split is not None:
-            assert 0.0 > split < 1.0
+            assert 0.0 < split < 1.0

         # be sure that classes are well ordered
         classes.sort()


@@ -142,7 +142,7 @@ class RandomEmbedding(BaseEmbedding):
                     else:
                         raise RuntimeError("your input level_type is wrong, it must be 'word', 'char', 'ngram'")
                     for text_one in text:
-                        if term_one not in token2idx:
+                        if text_one not in token2idx:
                             token2idx[text_one] = len(token2idx)
         else:
             raise RuntimeError("your input corpus_path is wrong, it must be 'dict' or 'corpus'")


@@ -156,7 +156,7 @@ class IRCString(UserString):

     def convert(self, case):
         """Convert string into another caseform"""
-        return IRCString(self, case)
+        return IRCString(case, self)

     def ascii_lower(self):
         """Return a copy of the string S converted to lowercase, using ASCII


@@ -332,7 +332,7 @@ class UserTrack(BaseExtension):

         basicrfc = self.get_extension("BasicRFC")

-        if self.casecmp(user.nick, basicrfc.nick):
+        if self.casecmp(target.nick, basicrfc.nick):
             # It's us!
             isupport = self.get_extension("ISupport")


@@ -48,7 +48,7 @@ class NullSocket(IRCBase):

     def inject_line(self, line):
         """Inject a Line into the recvq for the client."""
-        assert isinstance(Line, line)
+        assert isinstance(line, Line)
         self.recvq.put(line)

     def loop(self):


@@ -362,7 +362,7 @@ class XTerm16ColourFormatter(ANSIFormatter):

             if self.background is not None:
                 bgc = ColoursANSI[self.background.name].value
-                ret.append(str(fgc.background_16))
+                ret.append(str(bgc.background_16))
             else:
                 # Reset background just in case
                 ret.append(self.fmt_resetbackground)


@@ -14,7 +14,7 @@ from ..permissions import FullDjangoModelPermissions

 User = get_user_model()

-if User is PFUser:
+if User is not PFUser:
     raise ImproperlyConfigured("Pf User is not the User model")

ReplaceText(target=' is not ' @(17,7)->(17,11))


@@ -65,7 +65,7 @@ class worker_administrator(object):
             else:
                 worker = name + '_worker'

-            self.workers.append((name, worker, order))
+            self.workers.append((name, worker, i))

         self.workers = sorted(self.workers, key=lambda a: a[2])


@@ -528,7 +528,7 @@ found in our database or in the CASA NRAO database'.format(field))
                 step = 'plot_fluxscale_{0:d}'.format(i)
                 table = prefix+".F0"
                 fieldtoplot = []
-                fieldtoplot.append(utils.get_field_id(msinfo, ref)[0])
+                fieldtoplot.append(utils.get_field_id(msinfo, trans)[0])
                 recipe.add('cab/ragavi', step,
                     {
                      "table"        : '{0:s}/{1:s}:{2:s}'.format(get_dir_path(pipeline.caltables, pipeline), table, 'output'),


@@ -176,7 +176,7 @@ def worker(pipeline, recipe, config):
                     substep = 'delete_flag_versions_after_{0:s}_ms{1:d}'.format(version, target_iter)
                     manflags.delete_cflags(pipeline, recipe,
                         available_flagversions[available_flagversions.index(version)+1],
-                        msname, cab_name=substep)
+                        fms, cab_name=substep)

             flagv = tms+'.flagversions'


@@ -48,4 +48,4 @@ class TestReaction:

         assert re.count == 420
         assert re.me is True
-        test_state.parse_emoji.assert_called_with(None, emoji_dict)
+        test_state.parse_emoji.assert_called_with(emoji_dict, None)


@@ -286,7 +286,7 @@ class DispatchingEventAdapterImpl(dispatching_event_adapter.DispatchingEventAdap

             for role_id in role_ids:
                 role_obj = self.fabric.state_registry.get_role_by_id(guild_id, role_id)
-                if role_objs is not None:
+                if role_obj is not None:
                     role_objs.append(role_obj)
                 else:
                     self.logger.warning(


@@ -699,7 +699,7 @@ class BotAppImpl(bot.IBotApp):
             if plat == "win32":
                 supports_color |= os.getenv("TERM_PROGRAM", None) == "mintty"
                 supports_color |= "ANSICON" in os.environ
-                supports_color |= is_a_tty
+                supports_color &= is_a_tty
             else:
                 supports_color = is_a_tty


@@ -33,7 +33,7 @@ class s3(object):
         _url = deepcopy(url)
         if url[0:5] == 'https':
             _url = cls.https_to_s3(url)
-        if url[0:5] != 's3://':
+        if _url[0:5] != 's3://':
             raise Exception('Invalid S3 url %s' % _url)

         url_obj = _url.replace('s3://', '').split('/')


@@ -131,7 +131,7 @@ class OGIPRegion(Region):
         if isinstance(corr, Pha):
             self.corr = corr
             self.input_corr = True
-        elif back is None:
+        elif corr is None:
             self.input_corr = False
         else:
             self.input_corr = False


@@ -1975,7 +1975,7 @@ class Sheet(BaseObject):
             nchars = data2_len - 1
             if nb:
                 assert nchars % 2 == 0
-                nchars /= 2
+                nchars //= 2
             utext, endpos = unpack_unicode_update_pos(data2, 0, known_len=nchars)
             assert endpos == data2_len
             o.text += utext


@@ -61,7 +61,7 @@ class GeneralModelTest(FileReadingTestCase, DirectoryCleaningTestCase):
         # Put a real fits image on the first source, first observation
         apcor_str = "4 15   0.19   0.01"
         with open(self.get_abs_path(path), "rb") as fh:
-            self.first_image = DownloadedFitsImage(fh.read(), apcor_str, Mock(), in_memory=True)
+            self.first_image = DownloadedFitsImage(fh.read(), Mock(), apcor_str, in_memory=True)
             first_reading = self.model.get_current_workunit().get_sources()[0].get_readings()[0]
             self.model._on_image_loaded(first_reading, self.first_image)


@@ -12,7 +12,7 @@ def post_save_receiver(sender, instance, **kwargs):

         name = m.pop(0)
         app, model = name.lower().split('.')
-        if app != instance._meta.app_label and model != instance._meta.module_name:
+        if app != instance._meta.app_label or model != instance._meta.module_name:
             continue

         if any(m):


@@ -95,7 +95,7 @@ def plot_aggregated_map(

     if aggregation_method not in aggregates:
         raise ValueError(
-            f"{group} is not a valid aggregation method. Possible values are: {', '.join([k for k in aggregates])}"
+            f"{aggregation_method} is not a valid aggregation method. Possible values are: {', '.join([k for k in aggregates])}"
         )

     map_data = aggregates[aggregation_method][variables]


@@ -146,4 +146,4 @@ def create_database(db_name, table_name, directory_name, data_file, alias, silen
     if not silent:
         _initialization_display_message_epilogue()
     if not integrity_cancel:
-        integrity_check(directory_name, table_name, "None", silent)
+        integrity_check(db_name, table_name, "None", silent)


@@ -361,7 +361,7 @@ class KubeSpawner(Spawner):
             # shut down to complete
             while True:
                 data = yield self.get_pod_info(self.pod_name)
-                if data is not None:
+                if data is None:
                     break
                 time.sleep(5)


@@ -404,7 +404,7 @@ class KubeSpawner(Spawner):
     @gen.coroutine
     def start(self):
         pvc_data = get_pvc_info(self.pvc_name)
-        if pvc_data is not None:
+        if pvc_data is None:
             pvc_manifest = self.get_pvc_manifest()
             yield self.httpclient.fetch(self.request(
                 url=k8s_url(self.namespace, 'persistentvolumeclaims'),


@@ -48,5 +48,5 @@ def bend_kick(dt, Bz, ensemble, forces, reference_impl=False):
         f = np.zeros_like(ensemble.v)
         for force in forces:
             force.force(dt, ensemble, f)
-        ensemble.v *= f / m
+        ensemble.v += f / m
         updater(0.5 * dt, omegaB, ensemble.x, ensemble.v)


@@ -41,7 +41,7 @@ class SilvaCascadingPASPlugin(SearchPrincipalsPlugin):
         for authenticator_id, auth in authenticators:
             try:
                 info = auth.authenticateCredentials(credentials)
-                if info is not None and info[0] is None:
+                if info is not None and info[0] is not None:
                     # Failed login can be None OR (None, None)
                     return info
             except _SWALLOWABLE_PLUGIN_EXCEPTIONS:

ReplaceText(target=' is not ' @(44,47)->(44,51))


@@ -239,7 +239,7 @@ class Workflow_Placement(sl.WorkflowTask):
         lpca = self.new_task(
             'calculate_lpca',
             Jplace_PCA,
-            containerinfo=long_containerinfo,
+            containerinfo=highmem_containerinfo,
             path=os.path.join(
                 self.destination_dir,
                 'placement',


@@ -115,7 +115,7 @@ class Workflow_DADA2(sl.WorkflowTask):
             batch_errModels[batch] = self.new_task(
                 'dada2_learn_error_batch_{}'.format(batch),
                 DADA2_LearnError,
-                containerinfo=heavy_containerinfo,
+                containerinfo=midcpu_containerinfo,
                 batch=batch,
                 tar_reads=False,
                 path=os.path.join(


@@ -203,7 +203,7 @@ class Workflow_Classify(sl.WorkflowTask):
         placement_db_classified = self.new_task(
             'classify_into_placement_db',
             PlacementDB_Classify_SV,
-            containerinfo=heavy_containerinfo,
+            containerinfo=midcpu_containerinfo,
         )
         placement_db_classified.in_placement_db = placement_db_w_si.out_placement_db
         placement_db_classified.in_refpkg_tgz = refpkg_tgz.out_refpkg_tgz


@@ -203,7 +203,7 @@ class Workflow_Classify(sl.WorkflowTask):
         placement_db_classified = self.new_task(
             'classify_into_placement_db',
             PlacementDB_Classify_SV,
-            containerinfo=midcpu_containerinfo,
+            containerinfo=highmem_containerinfo,
         )
         placement_db_classified.in_placement_db = placement_db_w_si.out_placement_db
         placement_db_classified.in_refpkg_tgz = refpkg_tgz.out_refpkg_tgz


@@ -46,7 +46,7 @@ def SeparateFlagArgs(args: list):
   Returns:
     A tuple with the Fire args (a list), followed by the Flag args (a list).
   """
-  if len(args) > 1 and (args[-1] == '-h' or args[-1] == '--help') and '--' not in args:
+  if len(args) > 0 and (args[-1] == '-h' or args[-1] == '--help') and '--' not in args:
     args.pop()
     args.append('--')
     args.append('-h')


@@ -47,7 +47,7 @@ def backend_factory(path, *args, **kwargs):
     if os.path.isfile(path) or os.path.isdir(path):
         from pyrameter.db.local import JsonStorage
         return JsonStorage(path, *args, **kwargs)
-    elif path.find('mongodb://') >= 0:
+    elif path.find('mongodb://') == 0:
         from pyrameter.db.mongo import MongoStorage
         return MongoStorage(path, *args, **kwargs)
     else:


@@ -115,7 +115,7 @@ class Project(RadarObject):
             self.ptcs_update_info(info)

         labels = kwargs.get('labels', False)
-        if info:
+        if labels:
             for ptc in labels:
                 if ptc not in self.participants:
                     self.add_participant(ptc)


@@ -145,7 +145,7 @@ class Rope(object):
                     else:
                         if start is None:
                             offset = index.step + (head.length - 1) % (-index.step)
-                        elif start > 0:
+                        elif start >= 0:
                             offset = index.step + min(start, head.length - 1) % (-index.step)
                         else:
                             offset = index.step + (start + head.length) % (-index.step)


@@ -204,7 +204,7 @@ class Dump (multitool.Command):
     help_if_no_args = False

     def invoke (self, args, app=None, **kwargs):
-        if len (args) != 1:
+        if len (args) != 0:
             raise multitool.UsageError ('expected no arguments')

         app.export_all (sys.stdout, 72)


@@ -20,7 +20,7 @@ class Hammock(object):
 		entities = set()
 		self.collections_by_class_name = {}

-		for collection_cls in collections:
+		for collection_cls in collection_classes:
 			entities.add(collection_cls.entity)
 			collection = collection_cls(storage)
 			self.collections_by_class_name[collection_cls.__name__] = collection


@@ -97,7 +97,7 @@ def visualize_with_jupyter_notebook(obj, mode="element", transformation=None):
         for element in grid.entity_iterator(0):
             index = element.index
             local_values = np.real(
-                transformation(obj.evaluate(element, local_coordinates))
+                transformation(obj.evaluate(index, local_coordinates))
             )
             values[index] = local_values.flatten()


@@ -91,7 +91,7 @@ def assemble_dense(
     cols = domain.global_dof_count

     nshape_test = dual_to_range.number_of_shape_functions
-    nshape_trial = dual_to_range.number_of_shape_functions
+    nshape_trial = domain.number_of_shape_functions

     precision = operator_descriptor.precision


@@ -1035,9 +1035,9 @@ def helmholtz_hypersingular_regular(
                             ] * (
                                 curl_product[test_fun_index, trial_fun_index]
                                 - wavenumber
-                                * wavenumber
+                                * wavenumber
                                 * local_test_fun_values[
-                                    0, test_fun_index, quad_point_index
+                                    0, test_fun_index, test_point_index
                                 ]
                                 * local_trial_fun_values[
                                     0, trial_fun_index, quad_point_index


@@ -33,7 +33,7 @@ class DensePotentialAssembler(object):
             x_transformed = self.space.map_to_full_grid @ (
                 self.space.dof_transformation @ x
             )
-            result = implementation(x)
+            result = implementation(x_transformed)
             return result.reshape([kernel_dimension, -1], order="F")

         self._evaluator = potential_evaluator


@@ -34,7 +34,7 @@ def read_config(conf_file='service.conf'):
         raise RuntimeError('No config file found.')
     if not parser.parser.read(place):
         raise RuntimeError("couldn't read config file from {0}"
-                           .format(', '.join(place)))
+                           .format(', '.join(places)))
     return parser

 Config = read_config()
\ No newline at end of file


@@ -27,7 +27,7 @@ class JarvisPatrick(object):
     def __call__(self, number_of_neighbors, number_of_common_neighbors):
         """
         """
-        if number_of_common_neighbors >= number_of_neighbors:
+        if number_of_common_neighbors > number_of_neighbors:
             raise ValueError('Asked for more common neighbors than number of neighbors')
         neighbors_list = {}
         for element in self.dataset_elements:


@@ -112,7 +112,7 @@ def collect_parameters(uri_query='', body='', headers=None,
         if isinstance(k, str):
             k = k.decode('utf-8')
         if isinstance(v, str):
-            if v.startswith('oauth_'):
+            if k.startswith('oauth_'):
                 v = utils.unescape(v)
             else:
                 v = v.decode('utf-8')


@@ -281,7 +281,7 @@ def add_params_to_uri(uri, params, fragment=False):
     """Add a list of two-tuples to the uri query components."""
     sch, net, path, par, query, fra = urlparse.urlparse(uri)
     if fragment:
-        fra = add_params_to_qs(query, params)
+        fra = add_params_to_qs(fra, params)
     else:
         query = add_params_to_qs(query, params)
     return urlparse.urlunparse((sch, net, path, par, query, fra))


@@ -236,7 +236,7 @@ def time_bin_with_mask(data, time_bin_length, sample_selector=None):
         sample_selector.shape = (T, 1)

     bindata = numpy.zeros(
-        (T / time_bin_length,) + data.shape[1:], dtype="float32")
+        (T // time_bin_length,) + data.shape[1:], dtype="float32")
     for index, i in enumerate(range(0, T - time_bin_length + 1,
                                     time_bin_length)):
         # print weighted_avg_and_std(fulldata[i:i+time_bin_length], axis=0,


@@ -528,7 +528,7 @@ class LinearMediation(Models):

     def tsg_to_net(self, node, max_lag):
         """Helper function to translate from time series graph to network."""
-        row = node / max_lag
+        row = node // max_lag
         lag = node % max_lag
         return (row, -lag)


@@ -2577,7 +2577,7 @@ class CMIsymb(CondIndTest):
         dim, T = symb_array.shape

         # Needed because np.bincount cannot process longs
-        if isinstance(self.n_symbs ** dim, int):
+        if not isinstance(self.n_symbs ** dim, int):
             raise ValueError("Too many n_symbs and/or dimensions, "
                              "numpy.bincount cannot process longs")
         if self.n_symbs ** dim * 16. / 8. / 1024. ** 3 > 3.:


@@ -8,7 +8,7 @@ class SCTest(FunctionCode):
     @staticmethod
     def Main(a, b):

-        if a > b:
+        if a == b:

             return True


@@ -59,7 +59,7 @@ def cancelPZ(arg1, tol=1e-6):
     z = copy.copy(arg1.zeros)
     p = copy.copy(arg1.poles)
     k = arg1.gain
-    for i in range(max(z.shape) - 1, 0, -1):
+    for i in range(max(z.shape) - 1, -1, -1):
         d = z[i] - p
         cancel = np.nonzero(np.abs(d) < tol)[0]
         if cancel.size:


@@ -199,7 +199,7 @@ class Analysis(object):
             axp, axm, axsm, axss, axo = axi
             axp.add_patch(mpl.patches.Circle((0, 0), r, edgecolor="black",
                 facecolor="none"))
-            axp.text(-.1, .5, "OY=%s" % hi, rotation="vertical",
+            axo.text(-.1, .5, "OY=%s" % hi, rotation="vertical",
                     transform=axp.transAxes,
                     verticalalignment="center")
             for i, (wi, ci) in enumerate(zip(wavelengths, colors)):


@@ -333,7 +333,7 @@ class System(list):
             c = getattr(el, "curvature", 0)
             if pending is not None:
                 r = max(el.radius, pending.radius)
-                if c < 0:
+                if c <= 0:
                     el.radius = r
                 if c0 > 0:
                     pending.radius = r


@@ -92,7 +92,7 @@ def main():
             print('Similar domains to {}'.format(dom))
             domains.difference_update(set(dom))
             for d in domains:
-                print_diff(d, args.domain)
+                print_diff(args.domain, d)
                 if write:
                     f.write(d + "\n")
             if (args.check):


@@ -92,7 +92,7 @@ def main():
     if not os.path.isdir(dump_dir):
         print('Folder \'%s\' not found' % dump_dir)
         sys.exit(1)
-    if keep_count <= 0:
+    if keep_count < 0:
         print('keep_count must be greater than 0')
         sys.exit(1)
     make_dump(conf_file, dump_dir, keep_count)


@@ -14,7 +14,7 @@ class Doge:
         plugin_full_name = self.contrib_name + '-' + plugin_name
         plugin_package = self.contrib_name + '_' + plugin_name

-        if not self.check_plugin_installed(plugin_full_name):
+        if not self.check_plugin_installed(plugin_package):
             self.pip.install(plugin_full_name)  # ???

         file, path, desc = self.find_dotted_module(plugin_package + '.loader')


@@ -329,7 +329,7 @@ class DictArithmetic(dict):
             for k, v in other.items():
                 self[k] -= v
         else:
-            self[()] -= v
+            self[()] -= other
         return self

     def __mul__(self, other):


@@ -323,7 +323,7 @@ class SpinSimulation:
                 # the change in energy from flipping variable i is equal to
                 # -2 * (the energy of the subgraph depending on i)
                 dE = -2 * puso_value(self._state, self._subgraphs[i])
-                if dE < 0 or (T and random.random() < exp(-dE / T)):
+                if dE <= 0 or (T and random.random() < exp(-dE / T)):
                     self._flip_bit(i)


@@ -124,7 +124,7 @@ class ValidatorConversionDispatcher(object):
         if isinstance(validator, colander.All):
             converted = {}
             for v in validator.validators:
-                ret = self(schema_node, validator)
+                ret = self(schema_node, v)
                 converted.update(ret)
         return converted


@@ -127,7 +127,7 @@ def main():

     wlgrid = np.log10(10000/bindown_wngrid)
     if args.plot:
-        if get_rank()==0  and nprocs()==1:
+        if get_rank()==0  and nprocs()<=1:
             import matplotlib.pyplot as plt
             if args.contrib:
                 for name,value in contrib:


@@ -135,7 +135,7 @@ def main():
                 priors = {}
                 priors['Profiles'] = profiles
                 priors['Spectra'] = spectrum
-                out.store_dictionary(solution,group_name='Priors')
+                out.store_dictionary(priors,group_name='Priors')
             else:
                 out.store_dictionary(profiles,group_name='Profiles')
                 out.store_dictionary(spectrum,group_name='Spectra')


@@ -13,7 +13,7 @@ def nprocs():
     try:
         from mpi4py import MPI
     except ImportError:
-        return 0
+        return 1

     comm = MPI.COMM_WORLD


@@ -66,7 +66,7 @@ def add(context: ClockifyPluginContext, message, project, time):
         project_obj = None

     log_start = time
-    click.echo(f"Adding {message} at {as_local(log_start)} to project {project}")
+    click.echo(f"Adding {message} at {as_local(log_start)} to project {project_obj}")
     context.session.add_time_entry(
         start_time=time, description=message, project=project_obj
     )


@@ -58,7 +58,7 @@ class PackedSegmentTupleProvider(TuplesProviderABC):

                 # Create the new object
                 foundDocuments.append(GraphDbPackedSegmentTuple(
-                    key=key,
+                    key=subKey,
                     packedJson=segmentsByKey[subKey]
                 ))


@@ -50,7 +50,7 @@ def get_matsize(m):
     size = 0
     depth = len(m)
     for i in range(depth):
-        layer = m[depth]
+        layer = m[i]
         lngth = len(layer)
         for j in range(lngth):
             size = size + 1


@@ -258,7 +258,7 @@ class GRL(object):
         version = root.find('NamedLumiRange/Version')
         if version is not None:
             self.version = version.text
-        self.metadata = root.findall('NamedLumiRange/Metadata')
+        self.metadata += root.findall('NamedLumiRange/Metadata')
         lbcols = root.findall(
             'NamedLumiRange/LumiBlockCollection')
         for lbcol in lbcols:


@@ -37,7 +37,7 @@ except NameError:

 def select(loomfile, min_read_count, min_cell_count, layer):
     with loompy.connect(loomfile) as ds:
-        gsurv = (ds.sparse(layer=layer) >= min_read_count).sum(axis=1) > min_cell_count
+        gsurv = (ds.sparse(layer=layer) >= min_read_count).sum(axis=1) >= min_cell_count
         ds.ra.Selected = np.squeeze(np.asarray(gsurv))
         LOG.info('Total %d genes selected' % gsurv.sum())
         # totals = ds.map([np.sum], axis=1)[0]  # Select based upon cell size?


@@ -48,7 +48,7 @@ def iterrecords(bind=ENGINE, windowsize=WINDOWSIZE, skip_unknown=True):
     with bind.connect() as conn:
         select_files.bind = conn
         select_values.bind = conn
-        for in_slice in window_slices(File.id, size=windowsize, bind=bind):
+        for in_slice in window_slices(File.id, size=windowsize, bind=conn):
             if log.level <= logging.DEBUG:
                 where = literal_compile(in_slice(File.id))
                 log.debug('fetch rows %r', where.string)


@@ -14,7 +14,7 @@ class RatedMiddleware(object):
     def process_view(self, request, view_func, view_args, view_kwargs):
         # Try to determine the realm for this view
         try:
-            realm = request._rated_realm
+            realm = view_func._rated_realm
         except AttributeError:
             try:
                 realm = settings.REALM_MAP[request.resolver_match.url_name]


@@ -25,7 +25,7 @@ def _check_argvals(argvals):
     ------
     argvals : list of numpy.ndarray
     """
-    if isinstance(argvals, (np.ndarray, list)):
+    if not isinstance(argvals, (np.ndarray, list)):
         raise ValueError(
             'argvals has to be a list of numpy.ndarray or a numpy.ndarray!')
     # TODO: Modify the condition to accept multidimensional irregular


@@ -30,7 +30,7 @@ def _check_argvals(argvals):
     ------
     argvals : list of numpy.ndarray
     """
-    if isinstance(argvals, (np.ndarray, list)):
+    if not isinstance(argvals, (np.ndarray, list)):
         raise ValueError(
             'argvals has to be a list of numpy.ndarray or a numpy.ndarray!')
     if isinstance(argvals, list) and \


@@ -24,9 +24,9 @@ def _check_data(data):
     ------
     data : list of UnivariateFunctionalData ot IrregularFunctionalData
     """
-    if isinstance(data, (list,
-                         UnivariateFunctionalData,
-                         IrregularFunctionalData)):
+    if not isinstance(data, (list,
+                             UnivariateFunctionalData,
+                             IrregularFunctionalData)):
         raise ValueError(
             """Data has to be a list or elements of UnivariateFunctionalData
             or IrregularFunctionalData!""")


@@ -1075,7 +1075,7 @@ class IrregularFunctionalData(FunctionalData):
                                  bandwidth=b,
                                  degree=degree)
             pred = lp.fit_predict(arg, val, points_estim)
-            smooth_argvals[i] = arg
+            smooth_argvals[i] = points_estim
             smooth_values[i] = pred
         return IrregularFunctionalData({'input_dim_0': smooth_argvals},
                                        smooth_values)


@@ -138,7 +138,7 @@ def _task_gen(item, **kwds):
         provide_context=True,
         dag=dag,
     )
-    dag.set_dependency(task_id, "__pytest_branch")
+    dag.set_dependency("__pytest_branch", task_id)
     return task


@@ -77,7 +77,7 @@ def design(u,y,y_iv,Td,C,L):
         y_iv=y_iv[0:N,:]
         # virtual error
         ebar=rv-y
-        ebar_iv=rv-y_iv
+        ebar_iv=rv_iv-y_iv
         # remove the last samples of the input (to match the dimension of the virtual error)
         uf=uf[0:N,:]


@@ -67,7 +67,7 @@ class Resource(object):

   @property
   def root(self):
-    return self.ancestors[0]
+    return self.ancestors[-1]

   def __getitem__(self, name):
     if not name:


@@ -336,7 +336,7 @@ Returns:
         if not configSpec:
             raise UnfurlError(
                 'unable to find an implementation to "%s" "%s" on ""%s": %s'
-                % (action, resource.template.name, resource.template.name, reason)
+                % (action, resource.template.name, resource.template.name, notfoundmsg)
             )
         logger.debug(
             "creating configuration %s with %s to run for %s: %s",


@@ -35,7 +35,7 @@ class HTMLTagsEvalItem(EvalItem):

 def _as_html_tags_eval_item(item):
-    if not isinstance(HTMLTagsEvalItem, item):
+    if not isinstance(item, HTMLTagsEvalItem):
         return HTMLTagsEvalItem(item)
     return item


@@ -20,7 +20,7 @@ class CTCBeamDecoder(object):
     def decode(self, probs, seq_lens):
         # We expect batch x seq x label_size
         probs = probs.cpu().float()
-        seq_lens = probs.cpu().int()
+        seq_lens = seq_lens.cpu().int()
         batch_size, max_seq_len = probs.size(0), probs.size(1)
         output = torch.IntTensor(batch_size, self._beam_width, max_seq_len).cpu().int()
         timesteps = torch.IntTensor(batch_size, self._beam_width, max_seq_len).cpu().int()


@@ -107,7 +107,7 @@ def to_constant_bin_number(d,N_bin,weight_pos=None,lower_bound=None,upper_bound=
         while not found_bin:

             #if this weight fits in the bin
-            if new_weight_sum < V_bin_max:
+            if new_weight_sum <= V_bin_max:

                 #...put it in
                 if isdict:


@@ -257,7 +257,7 @@ integers'.format(
                 min_value=min_value
             ))

-        return values
+        return validated

     def optionally_parse_bool(
         self,


@@ -70,7 +70,7 @@ class Resource:
                 if not candidate.grants_read_to(unauthorised_agent):
                     raise NotAuthorised
                 continue
-            return broadcast_candidate
+            return unauthorised_agent

         if not broadcast_candidate.grants_read_to(unauthorised_agent):
             raise NotAuthorised


@@ -54,7 +54,7 @@ def make_positive_pairs(label, frag_steps, contig_frags, fppc, encoding_len=128)
     if k < fppc:
         # print("WARNING: cannot make {} unique pairs with genome of {} fragments".format(fppc, contig_frags), end='\r')
         pairs.sp = np.tile(label, [fppc, 2])
-        pairs.start = np.random.choice(frag_steps, [fppc, 2])
+        pairs.start = np.random.choice(contig_frags, [fppc, 2])
         pairs.end = pairs.start + frag_steps

     return pairs


@@ -305,7 +305,7 @@ class FileBrowser(FileTree):
                     fileName=os.path.split(path)[-1]

-                    stc.SetText(FileOperations().readFile(filePath=fname))
+                    stc.SetText(FileOperations().readFile(filePath=path))
                     centerPaneTab.window.addTab(name='openFileLoad'+fileName, worksheetPanel=stc)

 #         win = wx.GetApp().GetActiveWindow()


@@ -2306,7 +2306,7 @@ class ScrolledThumbnail(wx.ScrolledWindow):
                 logger.error(e, exc_info=True)
                 logger.error('selectedBookIndex: %s, len: %s', selectedBookIndex, len(self._items))
 #         logger.debug(.0deleteBooks)
-        if len(deleteBooks) > 0:
+        if len(deleteBooks) >= 0:
             self.updateStatusBar(text=f'{len(deleteBooks)} books deleted')
             self.GetParent().GetParent().loadingBook()
             self.GetParent().GetParent().updatePangnation()


@@ -186,7 +186,7 @@ class internal_force(generic_force):
         defflection = self.LF - distance
         velocity    = unit_vector.T*self.joint.dijd

-        self.Fi = unit_vector*(self.Fs(defflection) + self.Fd(velocity))
+        self.Fi = unit_vector*(self.Fs(defflection) - self.Fd(velocity))
         Ti_e = 2*G(self.Pi).T*(self.Ti + Skew(self.ui).T*self.Fi)

         force_vector = sm.BlockMatrix([[self.Fi], [Ti_e]])


@@ -74,7 +74,7 @@ class FieldAttrStringRedundant(Plugin):
                 f'for field "{field.name}". The same value will be computed '
                 f"by Odoo automatically.",
                 addon,
-                locations=[Location(path, [column_index_1(string_kwarg.start_pos)])],
+                locations=[Location(path, [column_index_1(field.start_pos)])],
                 confidence=Confidence.LOW,
                 categories=["redundancy"],
                 sources=sources,


@@ -23,7 +23,7 @@ class TrackVisibilityAlways(Plugin):
                     "deprecated since version 12.0",
                     addon,
                     locations=[
-                        Location(field.model.path, [column_index_1(kwarg.start_pos)])
+                        Location(field.model.path, [column_index_1(field.start_pos)])
                     ],
                     categories=["deprecated"],
                     sources=[


@@ -115,7 +115,7 @@ def get(*paths, **options):
         elif value is not MANDATORY:
             result[key] = value
         else:
-            path = '/'.join(path)
+            path = '/'.join(paths)
             raise HaipConfigException(f'option "{key}" not found in section "{path}"')
     return result


@@ -37,7 +37,7 @@ class rightmove_data(object):
         There are 24 results on each results page, but note that the
         rightmove website limits results pages to a maximum of 42 pages."""

-        page_count = self.results_count() / 24
+        page_count = self.results_count() // 24
         if self.results_count() % 24 > 0:
             page_count += 1


@@ -39,7 +39,7 @@ with open(os.path.join(working_dir, "data", "test_alignment.p"),
 # MOCK
 def dummy_blast(query, subj, minoverlap):
     # should return bools and positions
-    bools = [True for e in subj]
+    bools = [True for e in query]
     positions = [0 for e in subj]
     max_positions = [len(e) for e in subj]
     positions.extend(max_positions)


@@ -159,7 +159,7 @@ class Stager(object):
     @classmethod
     def run_all(klass, wd, stages):
         for s in stages:
-            if check(stage=s, directory=wd):
+            if not check(stage=s, directory=wd):
                 Stager(wd, s).run()


@@ -62,7 +62,7 @@ def main():
     exit(0)

   if sys.argv[1] == "help":
-    if len(sys.argv) < 2:
+    if len(sys.argv) <= 2:
       print(usage_str)
     elif sys.argv[2] == "datestr":
       print(bomail.util.datestr.datestr_str)


@@ -73,7 +73,7 @@ class TabNoThread:
     new_fileset = set(new_filenames)
     self.remove_files([t[0] for t in self.file_data if t[0] not in new_fileset], old_disp_info)
     # assume, worst-case, that all matching files have changed/added
-    self.update_for_change(new_fileset, old_disp_info)
+    self.update_for_change(new_filenames, old_disp_info)

   # lazily load display data and return disp_data, is_unread, is_marked


@@ -69,7 +69,7 @@ class FuturesSession(Session):
         func = super(FuturesSession, self).send
         if isinstance(self.executor, ProcessPoolExecutor):
             try:
-                dumps(request)
+                dumps(func)
             except (TypeError, PickleError):
                 raise RuntimeError(PICKLE_ERROR)
         return self.executor.submit(func, request, **kwargs)


@@ -95,7 +95,7 @@ class SubscriptionPod(Pod):
                 'subscription_ids': active_sub_ids
             }
         })
-        if len(active_sub_ids) > 0:
+        if len(active_sub_ids) > 1:
             actions.append(self.get_cancel_action(active_sub_ids))

         content['actions'] = actions


@@ -783,7 +783,7 @@ def _yfinance_request(names, start_date=None, end_date=None):
     try:
         import datetime
         if isinstance(start_date, str):
-            start_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
+            start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
         if isinstance(end_date, str):
             end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
     except ImportError:


@@ -1173,7 +1173,7 @@ class Argument(Parameter):
             if attrs.get('default') is not None:
                 required = False
             else:
-                required = attrs.get('nargs', 0) > 0
+                required = attrs.get('nargs', 1) > 0
         Parameter.__init__(self, param_decls, required=required, **attrs)

     def make_metavar(self):


@@ -224,7 +224,7 @@ def version_option(version=None, *param_decls, **attrs):
         message = attrs.pop('message', '%(prog)s, version %(version)s')

         def callback(ctx, param, value):
-            if value or ctx.resilient_parsing:
+            if not value or ctx.resilient_parsing:
                 return
             prog = prog_name
             if prog is None:


@@ -213,7 +213,7 @@ class CliRunner(object):
         old_env = {}
         try:
             for key, value in iteritems(env):
-                old_env[key] = os.environ.get(value)
+                old_env[key] = os.environ.get(key)
                 if value is None:
                     try:
                         del os.environ[key]


@@ -69,7 +69,7 @@ class Chatroom:
 	def displayMessages(this, dom):
 		global messages

-		if len(messages) >= this.lastMessage:
+		if len(messages) > this.lastMessage:
 			id = dom.createElement("span")
 			dom.setLayoutXSL(id, this.buildXML(), "Messages.xsl")
 			dom.insertChild(id, "Board")


@@ -15,7 +15,7 @@ def send_request(url, method,
 	"""
 	## Parse url args
 	for p in args:
-		url = url.replace(':'+p, str(params[p]))
+		url = url.replace(':' + p, str(args[p]))

 	try:
 		if data:


@@ -39,7 +39,7 @@ class SecretService(SilvaService):
         assert len(args) > 1, u'Too few arguments'
         challenge = hmac.new(self.__key, str(args[0]), hashlib.sha1)
         for arg in args[1:]:
-            challenge.update(str(args))
+            challenge.update(str(arg))
         return challenge.hexdigest()

 InitializeClass(SecretService)


@@ -225,7 +225,7 @@ class SeDASAPI:
         req = Request(url, headers=self.headers)
         try:
             decoded = json.load(urlopen(req))
-            if len(decoded) > 1 and 'downloadUrl' in decoded[0]:
+            if len(decoded) >= 1 and 'downloadUrl' in decoded[0]:
                 return decoded[0]['downloadUrl']
             return None
         except HTTPError as e:


@@ -91,7 +91,7 @@ class YamlDao(Dao):
         cur_data = self.fetch(_id)
         new_data = DictUtils.merge(cur_data, data)
         Yaml.to_file(file_path=file_path, data=new_data)
-        return data
+        return new_data

     def delete(self, _id) -> None:
         """


@@ -790,7 +790,7 @@ class BizObject(
                         related_bizobj_list.append(obj)
                     else:
                         related_bizobj_list.append(
-                            rel.target(related_data)
+                            rel.target(obj)
                         )

                 self._related_bizobjs[rel.name] = related_bizobj_list


@@ -79,6 +79,6 @@ class BreadthFirstSaver(Saver):
                 v_type = v.__class__
                 if v._id is None:
                     to_create[v_type].append(v)
-                elif x.dirty:
+                elif v.dirty:
                     to_update[v_type].append(x)
                 self._aggregate_related(v, to_create, to_update)


@@ -80,5 +80,5 @@ class BreadthFirstSaver(Saver):
                 if v._id is None:
                     to_create[v_type].append(v)
                 elif v.dirty:
-                    to_update[v_type].append(x)
+                    to_update[v_type].append(v)
                 self._aggregate_related(v, to_create, to_update)


@@ -116,7 +116,7 @@ class CompositeGuard(Guard):
             if rhs_exc is not None and lhs_exc is not None:
                 return CompositeGuardException(lhs_exc, rhs_exc)
         elif self._op == OP_CODE.NOT:
-            if lhs_exc is not None:
+            if lhs_exc is None:
                 return lhs_exc
         else:
             return ValueError(f'op not recognized, "{self._op}"')


@@ -43,7 +43,7 @@ class ActionDecorator(object):
         else:
             func = obj
             action = self.setup_action(func, False)
-            return action
+            return func

     def setup_action(self, func, overwrite):
         action = self.app.action_type(func, self)


@@ -429,7 +429,7 @@ def display_board(date=False, sort=False, im=False):
                   (Fore.LIGHTBLACK_EX + "(due: {})".format(color + str(duedate) + Fore.LIGHTBLACK_EX)) if item["due"] else "",
                   Fore.LIGHTBLACK_EX + str(item["date"]))
             else:
-                p(star, Fore.LIGHTMAGENTA_EX + str(item["id"]).rjust(2), mark, text_color + item["text"], tag_text, due_text, day_text)
+                p(star, Fore.LIGHTMAGENTA_EX + str(item["id"]).rjust(2), mark, text_color + item["text"], tag_text, day_text, due_text)
     print()
     print_footer()
     print_total()


@@ -54,7 +54,7 @@ def _next_note(first_note, second_note_name):
     If the second note name is less than the first ("G" is greater than "C"),
     return a note of the second name in the octave above the first.
     '''
-    if second_note_name > first_note.name:
+    if second_note_name >= first_note.name:
         second_note_octave = first_note.octave
     else:
         second_note_octave = first_note.octave + 1


@@ -80,4 +80,4 @@ def util_functions():

 def functions():
     callables = reduce(u.merge, [scale_functions(), chord_functions(), progression_functions(), interval_functions(), util_functions()])
-    return {k:u.to_function(v, k) for k,v in callables.items()}
+    return {k:u.to_function(k, v) for k,v in callables.items()}


@@ -207,7 +207,7 @@ class Model(core.ParameterModel):
             raise TypeError("Rate name must be str")
         if not callable(rate_function):
             raise TypeError("Rate function must be a function")
-        if variables is not None:
+        if variables is None:
             variables = []
         if not isinstance(variables, list):
             raise TypeError("Variables must be a list")


@@ -281,7 +281,7 @@ class Model(core.ParameterModel):
     def get_rate_indexes(self, rate_name=None):
         v, k = zip(*enumerate(self.get_rate_names()))
         rate_idx = dict(zip(k, v))
-        if rate_name is not None:
+        if rate_name is None:
             return rate_idx
         return rate_idx[rate_name]


@@ -637,7 +637,7 @@ class Session(object):

 MAXFD = 1024
-fdset = c_int32 * (MAXFD/32)
+fdset = c_int32 * (MAXFD//32)

 class timeval(Structure):
     _fields_ = [


@@ -312,7 +312,7 @@ def strToOid(oidStr):
     return mkoid(tuple([int(x) for x in oidStr.strip('.').split('.')]))

 def decodeOid(pdu):
-    return tuple([pdu.val.objid[i] for i in range(pdu.val_len / sizeof(u_long))])
+    return tuple([pdu.val.objid[i] for i in range(pdu.val_len // sizeof(u_long))])

 def decodeIp(pdu):
     return '.'.join(map(str, pdu.val.bitstring[:4]))


@@ -14,7 +14,7 @@ def stats(dir_stats=DIR_STATS):
 		stat_links = ('Average links in webpage: ' + str(average(content)))
 		if len(content) > 10000:
 			compress_stats(dir_stats + 'stat_links')
-	result += stat_links + '\n'
+	result = stat_links + '\n'
 	try:
 		with open(dir_stats + 'stat_webpages', 'r') as myfile:
 			content = myfile.read().split()


@@ -187,7 +187,7 @@ class AdapterBase(object):
         :returns: Item list and corresponding ORM models as a list of lists
             (in case one item updates multiple models).
         """
-        return db_persist(cls, item, adapter_settings)
+        return db_persist(item, cls, adapter_settings)

     @classmethod


@@ -64,7 +64,7 @@ class Queue:
 if __name__ == '__main__':
     queue = Queue()

-    if len(sys.argv) > 0:
+    if len(sys.argv) > 1:
         sys.stdin = open(sys.argv[1])
         while not stdio.isEmpty():
             input_item = stdio.readString()


@@ -9,6 +9,6 @@ class ThreeSumFast:
         count = 0
         for i in range(n):
             for j in range(i+1, n):
-                if binary_search.index_of(a, -a[i]-a[j]) > i:
+                if binary_search.index_of(a, -a[i]-a[j]) > j:
                     count += 1
         return count


@@ -183,7 +183,7 @@ class BinarySearchST:
         while j < self._n-1:
             self._keys[j] = self._keys[j+1]
             self._vals[j] = self._vals[j+1]
-            j = 1
+            j += 1

         self._n -= 1
         n = self._n


@@ -481,7 +481,7 @@ class RedBlackBST(Generic[Key, Val]):
             return
         if lo < x.key:
             self._keys(x.left, queue, lo, hi)
-        if not x.key < lo  and x.key <  hi:
+        if not x.key < lo  and x.key <=  hi:
             queue.enqueue(x.key)
         if hi > x.key:
             self._keys(x.right, queue, lo, hi)


@@ -15,7 +15,7 @@ logger = logging.getLogger(__name__)

 class ReCaptchaField(forms.CharField):
     def __init__(self, attrs=None, *args, **kwargs):
-        if os.environ.get('RECAPTCHA_DISABLE', None) is not None:
+        if os.environ.get('RECAPTCHA_DISABLE', None) is None:
             self._private_key = kwargs.pop('private_key', settings.RECAPTCHA_PRIVATE_KEY)
             self._score_threshold = kwargs.pop('score_threshold', settings.RECAPTCHA_SCORE_THRESHOLD)


@@ -375,7 +375,7 @@ class ProfilerObjectParser:
         except json.JSONDecodeError as json_error:
             LOGGER.warning("W001: Cannot parse object")
             LOGGER.warning(json_string)
-            LOGGER.warning("Decoder reports %s", json_string)
+            LOGGER.warning("Decoder reports %s", json_error)
             return

         dispatcher = {


@@ -148,7 +148,7 @@ class DatabaseManager(object, metaclass=Singleton):
         stmt = list()
         for ln in sql_in:
             cline = ln.strip()
-            if ln.startswith('--') or len(cline) == 0:
+            if cline.startswith('--') or len(cline) == 0:
                 continue

             stmt.append(cline)


@@ -812,7 +812,7 @@ def remove_comments(api_key, submission_id=None, file_id=None):
                 headers=auth_headers
             )

-            if r.status_code != 204:
+            if r.status_code == 204:
                 comments_to_delete += r.json().get("comments", list())
                 deleted_comments += 1
         except:


@@ -527,7 +527,7 @@ def geoAreaOfPolygon(poly):
 	polyArea = 0

 	# Use polygon triangulation to cut the bounding region into a list of triangles, calculate the area of each triangle
-	lstTriangle = tripy.earclip(poly)
+	lstTriangle = tripy.earclip(cleanPoly)
 	lstArea = []
 	for i in range(len(lstTriangle)):
 		lstArea.append(geoAreaOfTriangle(lstTriangle[i][0], lstTriangle[i][1], lstTriangle[i][2]))


@@ -380,7 +380,7 @@ def analysis_worker(elem, root, y, feat_names, class_names, lock):
                                      model=voronoi_mdl_obj)
             elif hasattr(mdl_obj, 'n_leaves_'):
                 plotting.tree(root=rootname, data_in=step_in,
-                              labels=step_out, model=mdl_obj)
+                              labels=y, model=mdl_obj)
                 plotting.dendrogram(root=rootname, data_in=step_in,
                                     labels=y, model=mdl_obj)


@@ -135,7 +135,7 @@ class Cursebox(object):
             return EVENT_RIGHT
         elif ch == 3:
             return EVENT_CTRL_C
-        elif 0 >= ch < 256:
+        elif 0 <= ch < 256:
             return chr(ch)
         else:
             return EVENT_UNHANDLED


@@ -263,7 +263,7 @@ class Database(object):
             try:
                 tableFile = (self._path + "/" + aTableName + ".pq")
                 tableFileEnc = (self._path + "/" + aTableName + ".enc")
-                self._decrypt(tableFileEnc)
+                self._decrypt(tableFile)
                 dataframe = pq.read_table(tableFile).to_pandas()
                 os.remove(tableFile)
                 return dataframe


@@ -96,7 +96,7 @@ class SimpleCalculator():
             elif self.op == '+':
                 self.r1 = self.r1 + self.r2
             elif self.op == '-':
-                self.r1 = self.r1 + self.r2
+                self.r1 = self.r1 - self.r2
             elif self.op == '*':
                 self.r1 = self.r1 * self.r2
             elif self.op == '/':


@@ -150,7 +150,7 @@ class H5WriterMPI(AbstractH5Writer):

     def _write_solocache_group_to_file(self, data_dict, group_prefix="/"):
         if self._is_master() and group_prefix != "/":
-            if group_prefix in self._f:
+            if group_prefix not in self._f:
                 self._f.create_group(group_prefix)
         keys = data_dict.keys()
         keys.sort()


@@ -6,7 +6,7 @@ class EpsGreedy(object):
         self._epsilon = epsilon

     def __call__(self):
-        if np.random.uniform() > self._epsilon:
+        if np.random.uniform() < self._epsilon:
             return False
         return True


@@ -103,7 +103,7 @@ class Algorithm(object):
             if render:
                 self.mdp._render()

-            last = 0 if n_steps < self.mdp.horizon or not absorbing else 1
+            last = 0 if n_steps < self.mdp.horizon and not absorbing else 1
             sample = self.state.ravel().tolist() + action.ravel().tolist() + \
                      [reward] + next_state.ravel().tolist() + \
                      [absorbing, last]


@@ -113,7 +113,7 @@ class Core(object):
             action_idx = self.agent.draw_action(self.state,
                                                 self.agent.approximator)
             action_value = self.mdp.action_space.get_value(action_idx)
-            next_state, reward, absorbing, _ = self.mdp.step(action_idx)
+            next_state, reward, absorbing, _ = self.mdp.step(action_value)
             J += self.mdp.gamma ** n_steps * reward
             n_steps += 1


@@ -75,4 +75,4 @@ class Binarizer(Preprocessor):
             The binarized input data array.

         """
-        return (x > self._threshold).astype(np.float)
+        return (x >= self._threshold).astype(np.float)


@@ -237,7 +237,7 @@ class RDQN(DQN):
             state, action, _, _, absorbing, _ =\
                 self._replay_memory.get_idxs(idxs)

-            no_abs_idxs = idxs[np.argwhere(absorbing != 0).ravel()]
+            no_abs_idxs = idxs[np.argwhere(absorbing == 0).ravel()]
             state, action, _, _, absorbing, _ =\
                 self._replay_memory.get_idxs(no_abs_idxs)
             next_state, next_action, next_reward, _, next_absorbing, _ =\


@@ -258,7 +258,7 @@ class SARSALambdaDiscrete(TD):
         for s in self.mdp_info.observation_space.values:
             for a in self.mdp_info.action_space.values:
                 self.Q[s, a] += self.alpha(s, a) * delta * self.e[s, a]
-                self.e[s, a] = self.mdp_info.gamma * self._lambda
+                self.e[s, a] *= self.mdp_info.gamma * self._lambda

 class SARSALambdaContinuous(TD):


@@ -161,7 +161,7 @@ class DoubleFQI(FQI):
         next_state = list()
         absorbing = list()

-        half = len(x) / 2
+        half = len(x) // 2
         for i in range(2):
             s, a, r, ss, ab, _ = parse_dataset(x[i * half:(i + 1) * half])
             state.append(s)


@@ -186,7 +186,7 @@ class AveragedDQN(DQN):
         assert isinstance(self.target_approximator.model, Ensemble)

     def _update_target(self):
-        idx = self._n_updates / self._target_update_frequency\
+        idx = self._n_updates // self._target_update_frequency\
               % self._n_approximators
         self.target_approximator.model[idx].set_weights(
             self.approximator.model.get_weights())


@@ -108,7 +108,7 @@ def compute_probabilities(grid_map, cell_list, passenger_list, prob):
     passenger_states = cartesian([[0, 1]] * len(passenger_list))

     for i in range(n_states):
-        idx = i / len(cell_list)
+        idx = i // len(cell_list)
         collected_passengers = np.array(
             passenger_list)[np.argwhere(passenger_states[idx] == 1).ravel()]
         state = c[i % len(cell_list)]


@@ -54,7 +54,7 @@ class AbstractGridWorld(Environment):

     @staticmethod
     def convert_to_grid(state, width):
-        return np.array([state[0] / width, state[0] % width])
+        return np.array([state[0] // width, state[0] % width])

     @staticmethod
     def convert_to_int(state, width):


@@ -90,7 +90,7 @@ def experiment(alg):
     # evaluate initial policy
     pi.set_epsilon(epsilon_test)
     mdp.set_episode_end(ends_at_life=False)
-    for n_epoch in range(1, max_steps / evaluation_frequency + 1):
+    for n_epoch in range(1, max_steps // evaluation_frequency + 1):
         # learning step
         pi.set_epsilon(epsilon)
         mdp.set_episode_end(ends_at_life=True)


@@ -294,7 +294,7 @@ def experiment():
             agent.policy.set_q(agent.approximator)

         np.save(folder_name + '/scores.npy', scores)
-        for n_epoch in range(1, max_steps / evaluation_frequency + 1):
+        for n_epoch in range(1, max_steps // evaluation_frequency + 1):
             print_epoch(n_epoch)
             print('- Learning:')
             # learning step


@@ -51,7 +51,7 @@ class DQN(Agent):
         self._batch_size = batch_size
         self._n_approximators = n_approximators
         self._clip_reward = clip_reward
-        self._target_update_frequency = target_update_frequency / train_frequency
+        self._target_update_frequency = target_update_frequency // train_frequency
         self._max_no_op_actions = max_no_op_actions
         self._no_op_action_value = no_op_action_value


@@ -180,7 +180,7 @@ class InvertedPendulumDiscrete(Environment):
             u = 0.
         else:
             u = self._max_u
-        action += np.random.uniform(-self._noise_u, self._noise_u)
+        u += np.random.uniform(-self._noise_u, self._noise_u)
         new_state = odeint(self._dynamics, self._state, [0, self._dt],
                            (u,))


@@ -232,7 +232,7 @@ class ReplayMemory(object):
             allows it to be used.

         """
-        return self.size > self._initial_size
+        return self.size >= self._initial_size

     @property
     def size(self):


@@ -78,7 +78,7 @@ def experiment(n_epochs, n_steps, n_steps_test):
                                n_actions=mdp.info.action_space.n)

     # Agent
-    agent = DQN(TorchApproximator, pi, mdp.info,
+    agent = DQN(mdp.info, pi, TorchApproximator,
                 approximator_params=approximator_params, batch_size=batch_size,
                 n_approximators=1, initial_replay_size=initial_replay_size,
                 max_replay_size=max_replay_size,


@@ -37,7 +37,7 @@ def experiment():

     # Agent
     algorithm_params = dict(n_iterations=20)
-    agent = FQI(approximator, pi, mdp.info,
+    agent = FQI(mdp.info, pi, approximator,
                 approximator_params=approximator_params, **algorithm_params)

     # Algorithm


@@ -33,7 +33,7 @@ def experiment(algorithm_class, exp):
     # Agent
     learning_rate = ExponentialParameter(value=1., exp=exp, size=mdp.info.size)
     algorithm_params = dict(learning_rate=learning_rate)
-    agent = algorithm_class(pi, mdp.info, **algorithm_params)
+    agent = algorithm_class(mdp.info, pi, **algorithm_params)

     # Algorithm
     collect_Q = CollectQ(agent.approximator)


@@ -38,7 +38,7 @@ def experiment(algorithm_class, exp):
     # Agent
     learning_rate = ExponentialParameter(value=1, exp=exp, size=mdp.info.size)
     algorithm_params = dict(learning_rate=learning_rate)
-    agent = algorithm_class(pi, mdp.info, **algorithm_params)
+    agent = algorithm_class(mdp.info, pi, **algorithm_params)

     # Algorithm
     start = mdp.convert_to_int(mdp._start, mdp._width)


@@ -191,7 +191,7 @@ class TRPO(Agent):
             new_loss = self._compute_loss(obs, act, adv, old_log_prob)
             kl = self._compute_kl(obs, old_pol_dist)
             improve = new_loss - prev_loss
-            if kl <= self._max_kl * 1.5 or improve >= 0:
+            if kl <= self._max_kl * 1.5 and improve >= 0:
                 violation = False
                 break
             stepsize *= .5


@@ -20,7 +20,7 @@ def parse_quantity(str_value):
     """Parse a string into an astropy Quantity. Rather than trying to guess
     where the split occurs, we try every position from the back until we
     succeed."""
-    for i in range(len(str_value), -1, 0):
+    for i in range(len(str_value), 0, -1):
         try:
             value = float(str_value[:i])
             unit = units.Unit(str_value[i:])


@@ -479,7 +479,7 @@ class Weights(accel.OperationSequence):
         self.ensure_all_bound()
         # If self._fill is set, it is not necessary to clear first because
         # finalize will set all relevant values.
-        if self._fill is not None:
+        if self._fill is None:
             self.buffer('grid').zero(self.command_queue)

     def grid(self, uv, weights):


@@ -134,7 +134,7 @@ class Image(object):
                     # TODO: should use the WCS transformation
                     slices[i - 3] = 'IQUV'.find(stokes)
                 elif axis_type == 'VOPT':
-                    slices[i - 3] = channel
+                    slices[i - 3] = rel_channel
         self._render_thumb(output_dir, filename, slices, mode, stokes, channel)
         self._render_full(output_dir, filename, slices, mode, stokes, channel)


@@ -53,7 +53,7 @@ def invoke(initial, ctx):
             handler = get_handler(project_dir, module, service)
             cmd = project_config.get_command(handler, module, service, workspace)
             if not cmd:
-                raise CwsClientError(f"Undefined command {cmd}.\n")
+                raise CwsClientError(f"Undefined command {cmd_name}.\n")

             # Defines the proxy command with all user options
             def call_execute(**command_options):


@@ -9,5 +9,5 @@ def dasherize(text):
 def require_relationship(resource_list, data):
     for resource in resource_list:
         if resource not in data:
-            raise UnprocessableEntity({'pointer': '/data/relationships/{}'.format(resource)},
-                                      "A valid relationship with {} resource is required".format(resource))
+            raise UnprocessableEntity("A valid relationship with {} resource is required".format(resource),
+                                      {'pointer': '/data/relationships/{}'.format(resource)})


@@ -43,7 +43,7 @@ def render_templates(target_path, replace_values, file_types):
             template = env.get_template(f)
             rendered = template.render(replace_values)
             with open(full_path, "w") as fh:
-                print('Writing {}'.format(f))
+                print('Writing {}'.format(full_path))
                 fh.write(rendered)


@@ -756,7 +756,7 @@ def sync(args):
                 feed.fix_linkdate(entry)
             # Sort entries_to_download, but only if you want to download as
             # many as there are
-            if stop < len(entries_to_download):
+            if stop >= len(entries_to_download):
                 entries_to_download.sort(key=operator.attrgetter("linkdate"),
                                          reverse=False)
             for entry in entries_to_download:


@@ -61,7 +61,7 @@ def accepted_answer(request,slug,comment):
 	if not instance == comment.content_object:
 		raise Http404

-	if not request.user.has_perm('stack.change_question') or not request.user == instance.comment.user:
+	if not request.user.has_perm('stack.change_question') and not request.user == instance.comment.user:
 		raise Http404

 	if instance.accepted_answer:


@@ -14,7 +14,7 @@ class FuzzyXCSFLinearPredictionCreditAssignment:
         ]
         total_matching_degrees = sum(matching_degrees)
         assert total_matching_degrees > 0.0
-        for (classifier, matching_degree) in zip(matching_degrees, action_set):
+        for (classifier, matching_degree) in zip(action_set, matching_degrees):
             credit_weight = (matching_degree / total_matching_degrees)
             self._update_experience(classifier, credit_weight)
             payoff_diff = payoff - classifier.get_prediction(situation)


@@ -110,7 +110,7 @@ def update(context, answered_out, case_id):
             if delivery_date is None:
                 log.warn("sample not delivered: %s", hk_sample.lims_id)
                 context.abort()
-            delivery_dates.append(delivery_dates)
+            delivery_dates.append(delivery_date)
         latest_date = sorted(delivery_dates)[-1]
         log.debug("fillin answered out date in HK")
         hk_run.answeredout_at = datetime.combine(latest_date, datetime.min.time())


@@ -174,7 +174,7 @@ def start(lims_api, customer_id, family_name):
         log.debug("%s has status %s", sample.sample_id, sample_status)
         statuses.add(sample_status)

-    if len(is_externals) == 0:
+    if len(is_externals) == 1:
         data = dict(is_external=is_externals.pop())
     else:
         # mix of internal and external samples


@@ -90,7 +90,7 @@ def family(context: click.Context, customer: str, name: bool, samples: bool,
             families.append(family_obj)

     for family_obj in families:
-        LOG.debug(f"{family_id.internal_id}: get info about family")
+        LOG.debug(f"{family_obj.internal_id}: get info about family")
         row = [
             family_obj.internal_id,
             family_obj.name,


@@ -18,7 +18,7 @@ class BackupApi():
         """Check if there's too many flowcells already "ondisk"."""
         ondisk_flowcells = self.status.flowcells(status='ondisk').count()
         LOG.debug(f"ondisk flowcells: {ondisk_flowcells}")
-        return ondisk_flowcells < max_flowcells
+        return ondisk_flowcells > max_flowcells

     def check_processing(self, max_flowcells: int=3) -> bool:
         """Check if the processing queue for flowcells is not full."""


@@ -23,7 +23,7 @@ __version__ = "$Revision$"
 def manage_addComment(self, author, body, url='', email='', date=None, bitakora_cpt='', random_cpt='', captcha_zz=0, REQUEST=None):
     """ Called from HTML form when commenting """
     from utils import checkCaptchaValue, isCommentSpam
-    if not captcha_zz:
+    if captcha_zz:
         if not checkCaptchaValue(random_cpt, bitakora_cpt):
             if REQUEST is not None:
                 return REQUEST.RESPONSE.redirect(self.absolute_url()+u'?msg=%s&body=%s&comment_author=%s&comment_email=%s&comment_url=%s#bitakora_cpt_control' % (self.gettext('Are you a bot? Please try again...'), url_quote(body.encode('utf-8')), url_quote(author.encode('utf-8')), url_quote(email.encode('utf-8')), url_quote(url.encode('utf-8'))))


@@ -112,7 +112,7 @@ def main(argv=sys.argv[1:]):
             print(event, pprint.pformat(data), flush=True)

         if event == 'highstate-start':
-            minions += set(data['minions'])
+            minions |= set(data['minions'])
         elif event == 'highstate':
             minions.discard(data['minion'])


@@ -142,7 +142,7 @@ class Case:

         response_verification = self._response.verify(
             response,
-            ValueContext(origin_datetime=response.starts),
+            ValueContext(origin_datetime=execution.starts),
         )
         return CaseResult(
             label=self._label,


@@ -468,7 +468,7 @@ def savitzky_golay(arr, window_size, order, deriv=0, rate=1, interpolate=True):

     # allow to interpolate for half the window size
     if interpolate:
-        ser = Series(arr).interpolate(limit=half_window)
+        ser = Series(arr).interpolate(limit=window_size)
         y = array(ser)
     else:
         y = array(arr)


@@ -95,7 +95,7 @@ def _is_wc_root(root, info):
         p = os.path.dirname(root)
         return (p == root
                 or not os.path.isdir(os.path.join(p, '.svn'))
-                or _info(p).get('Repository UUID') == info['Repository UUID'])
+                or _info(p).get('Repository UUID') != info['Repository UUID'])
     return False


@@ -82,7 +82,7 @@ def markup(string):
                                         )
         newString += string.split(">", 1)[1]
         string = newString
-    return newString
+    return string

 # Print markup characters to screen


@@ -31,7 +31,7 @@ def feature_command(tgen):
     cmd_dir = tgen.make_node(tgen.worch.command_dir)
     cmd_node = cmd_dir.make_node(tgen.worch.command_cmd)
     cmd_target = \
-        map(cmd_dir.make_node, tgen.to_list(tgen.worch.command_target))
+        map(tgen.make_node, tgen.to_list(tgen.worch.command_target))
     cmd_rule = '{command_cmd_prefix}{command_cmd} {command_cmd_options} {command_cmd_postfix}'
     tgen.step('command',
               rule = tgen.worch.format(cmd_rule),


@@ -109,7 +109,7 @@ def sim_function(ig1, ig2, method='jaccard', model='ham',
         correction = correction_function(max(ig1.mut, ig2.mut))
         # ss = 1 - ((1 - ss) * max(correction, 0))
         # ss = 1 - ((1 - ss) * correction)
-        ss *= correction
+        ss += correction
     # return min(max(ss, 0), 1)
     return max(ss, 0)


@@ -109,7 +109,7 @@ def sim_function(ig1, ig2, method='jaccard', model='ham',
         correction = correction_function(max(ig1.mut, ig2.mut))
         # ss = 1 - ((1 - ss) * max(correction, 0))
         # ss = 1 - ((1 - ss) * correction)
-        ss += (1. - correction)
+        ss *= (1. - correction)
     # return min(max(ss, 0), 1)
     return max(ss, 0)


@@ -246,7 +246,7 @@ class DbMiddleware(object):
     def __init__(self, engine, connect_only, schema):
         self.engine = engine

-        if connect_only:
+        if not connect_only:
             inspection = reflection.Inspector.from_engine(self.engine)
             views = inspection.get_view_names(schema=schema)
             tables = inspection.get_table_names(schema=schema)


@@ -414,7 +414,7 @@ def print_result(peps, print_peps,threshold):
     # prints flagged peptides in console, if print_peps == True
     # peptides are flagged, if they are greater than the average of all positive scores
     scores = list(peps.values())
-    scores_in_tens = [int(round(i, -1)) if i >= threshold else -1 for i in scores]  # only round positiv scores
+    scores_in_tens = [int(round(i, -1)) if i <= threshold else -1 for i in scores]  # only round positiv scores
     freq_scores = {x: scores_in_tens.count(x) for x in scores_in_tens}  # Dictionary Comprehension

     if print_peps == 1:


@@ -46,7 +46,7 @@ class Import(Command):
         """ Import patch into the patch queue
         The patch is inserted after the current top applied patch
         """
-        if not new_name:
+        if new_name:
             dir_name = os.path.dirname(new_name)
             name = os.path.basename(new_name)
             dest_dir = self.quilt_patches + Directory(dir_name)


@@ -93,7 +93,7 @@ class Push(Command):
         applied = self.db.applied_patches()
         for patch in applied:
             if patch in patches:
-                patches.remove(applied)
+                patches.remove(patch)

         if not patches:
             raise AllPatchesApplied(self.series, self.db.top_patch())


@@ -69,7 +69,7 @@ def test_a_verifier_saves_any_failing_examples_in_its_database():
 def test_a_verifier_retrieves_previous_failing_examples_from_the_database():
     database = ExampleDatabase()
     verifier = Verifier(settings=hs.Settings(database=database))
-    verifier.falsify(lambda x: x != 11, int)
+    verifier.falsify(lambda x: x < 11, int)
     called = []

     def save_calls(t):


@@ -89,7 +89,7 @@ class TestRunner(object):
             raise RunIsComplete()
         self.examples_considered += 1
         if (
-            buffer[:self.last_data.index] ==
+            buffer[:self.last_data.index] >=
             self.last_data.buffer[:self.last_data.index]
         ):
             return False


@@ -686,7 +686,7 @@ def characters(whitelist_categories=None, blacklist_categories=None,
     if (
         whitelist_characters is not None and
         blacklist_characters is not None and
-        set(whitelist_characters).intersection(set(whitelist_characters))
+        set(blacklist_characters).intersection(set(whitelist_characters))
     ):
         raise InvalidArgument(
             'Cannot have characters in both whitelist_characters=%r, '


@@ -691,7 +691,7 @@ def characters(whitelist_categories=None, blacklist_categories=None,
         raise InvalidArgument(
             'Cannot have characters in both whitelist_characters=%r, '
             'and blacklist_characters=%r' % (
-                whitelist_characters, blacklist_categories,
+                whitelist_characters, blacklist_characters,
             )
         )


@@ -30,7 +30,7 @@ if __name__ == '__main__':

     if (
         os.environ['CIRCLE_BRANCH'] != 'master' and
-        os.environ['CI_PULL_REQUEST'] != ''
+        os.environ['CI_PULL_REQUEST'] == ''
     ):
         print('We only run CI builds on the master branch or in pull requests')
         sys.exit(0)


@@ -1119,7 +1119,7 @@ def find(specifier, condition, settings=None, random=None, database_key=None):
         if success:
             successful_examples[0] += 1

-        if settings.verbosity == Verbosity.verbose:
+        if settings.verbosity >= Verbosity.verbose:
             if not successful_examples[0]:
                 report(
                     u'Tried non-satisfying example %s' % (nicerepr(result),))


@@ -119,7 +119,7 @@ def assert_can_release():

 def has_travis_secrets():
-    return os.environ.get('TRAVIS_SECURE_ENV_VARS', None) != 'true'
+    return os.environ.get('TRAVIS_SECURE_ENV_VARS', None) == 'true'

 def build_jobs():


@@ -2209,7 +2209,7 @@ class Shrinker(object):
                 u, v = self.blocks[i]
                 b = int_from_bytes(self.shrink_target.buffer[u:v])
                 lowered = b - offset
-                if lowered <= 0:
+                if lowered < 0:
                     continue
                 attempt = bytearray(self.shrink_target.buffer)
                 attempt[u:v] = int_to_bytes(lowered, v - u)


@@ -317,7 +317,7 @@ class settings(
         bits = []
         for name, setting in all_settings.items():
             value = getattr(self, name)
-            if value != setting.default or not setting.hide_repr:
+            if value != setting.default and not setting.hide_repr:
                 bits.append('%s=%r' % (name, value))
         return 'settings(%s)' % ', '.join(sorted(bits))


@@ -439,7 +439,7 @@ class StepCounter(RuleBasedStateMachine):
         self.step_count += 1

     def teardown(self):
-        assert self.step_count == settings_step_count
+        assert self.step_count <= settings_step_count

 test_settings_decorator_applies_to_rule_based_state_machine_class = \


@@ -656,7 +656,7 @@ def sampled_from(elements):
         return sets(sampled_from(values), min_size=1).map(
             lambda s: reduce(operator.or_, s)
         )
-    return SampledFromStrategy(values)
+    return SampledFromStrategy(elements)

 @cacheable


@@ -1842,7 +1842,7 @@ def complex_numbers(
         # Order of conditions carefully tuned so that for a given pair of
         # magnitude arguments, we always either draw or do not draw the bool
         # (crucial for good shrinking behaviour) but only invert when needed.
-        if min_magnitude != 0 and draw(booleans()) and math.fabs(zi) <= min_magnitude:
+        if min_magnitude > 0 and draw(booleans()) and math.fabs(zi) <= min_magnitude:
             zr = -zr
         return complex(zr, zi)


@@ -418,7 +418,7 @@ class InfoBuilder:
         # Negate condition for else clause processing
         # We do not need to recombine it with conditions passed to our method,
         # as condition being reverted is part of combined tree
-        self.__invertCondition(currentConditions)
+        self.__invertCondition(newConditions)
         self.__generic(elseClause, deepcopy(currentConditions))

     def __makeConditionRouter(self, element):


@@ -38,7 +38,7 @@ class TestSkillUniqueness(RestrictionTestCase):
         restrictionError1 = fit.getRestrictionError(skill1, Restriction.skillUniqueness)
         self.assertIsNotNone(restrictionError1)
         self.assertEqual(restrictionError1.skill, 56)
-        restrictionError2 = fit.getRestrictionError(skill1, Restriction.skillUniqueness)
+        restrictionError2 = fit.getRestrictionError(skill2, Restriction.skillUniqueness)
         self.assertIsNotNone(restrictionError2)
         self.assertEqual(restrictionError2.skill, 56)
         fit.items.remove(skill1)


@@ -52,7 +52,7 @@ class SlotIndexRegister(RestrictionRegister):
     def registerHolder(self, holder):
         # Skip items which don't have index specifier
         slotIndex = holder.item.attributes.get(self.__slotIndexAttr)
-        if slotIndex is not None:
+        if slotIndex is None:
             return
         self.__slottedHolders.addData(slotIndex, holder)


@@ -61,7 +61,7 @@ class ResourceRegister(RestrictionRegister):
         # Can be None, so fall back to 0 in this case
         output = stats.output or 0
         # If we're not out of resource, do nothing
-        if totalUse > output:
+        if totalUse <= output:
             return
         taintedHolders = {}
         for holder in self.__resourceUsers:


@@ -151,7 +151,7 @@ class MsgHelper:
             # Unapply effects from targets
             tgt_getter = getattr(item, '_get_effects_tgts', None)
             if tgt_getter:
-                effects_tgts = tgt_getter(start_ids)
+                effects_tgts = tgt_getter(stop_ids)
                 for effect_id, tgt_items in effects_tgts.items():
                     msgs.append(EffectUnapplied(item, effect_id, tgt_items))
             # Stop effects


@@ -58,7 +58,7 @@ def encode_fp_to_snorm(x, *, dtype=np.uint8, nbits=None):
     if nbits is None:
         nbits = max_nbits
     assert (0 < nbits <= max_nbits), '`nbits` value is out of range.'
-    mask = np.invert(dtype(np.iinfo(nbits).max) << dtype(nbits))
+    mask = np.invert(dtype(np.iinfo(dtype).max) << dtype(nbits))
     return dtype(np.around(x * x.dtype.type((1 << (nbits-1)) - 1))) & mask

 def decode_snorm_to_fp(x, *, dtype=np.float32, nbits=None):


@@ -338,7 +338,7 @@ class APITestCase(unittest.TestCase):
         def record(sender, exception):
             recorded.append(exception)

-        got_request_exception.connect(record, api)
+        got_request_exception.connect(record, app)
         try:
             with app.test_request_context("/foo"):
                 api.handle_error(exception)


@@ -45,7 +45,7 @@ class MinifiedManifestStaticFilesStorage(ManifestStaticFilesStorage):
             # save gziped file as fell, we overwrite the content_file variable to save a tiny bit memory
             try:
                 content = zlib_compress(content)
-                super(MinifiedManifestStaticFilesStorage, self)._save("%s.gz" % hashed_name,ContentFile(content))
+                super(MinifiedManifestStaticFilesStorage, self)._save("%s.gz" % saved_name,ContentFile(content))
             except Exception as e:
                 raise MinifiedStorageException("Could not gzip file %s, error: %s" % (hashed_name,e,))
         return saved_name
\ No newline at end of file


@@ -133,7 +133,7 @@ class TluTuning(m26):

                     # Determine best delay setting (center of working delay settings)
                     good_indices = np.where(np.logical_and(data_array['error_rate'][:-1] == 0, np.diff(data_array['error_rate']) == 0))[0]
-                    best_index = good_indices[good_indices.shape[0] / 2]
+                    best_index = good_indices[good_indices.shape[0] // 2]
                     best_delay_setting = data_array['TRIGGER_DATA_DELAY'][best_index]
                     logging.info('The best delay setting for this setup is %d', best_delay_setting)


@@ -70,7 +70,7 @@ class Marker(object):
         label = str(self.height)
         text_width, text_height = draw.textsize(label, font=font)
         x = 0.65 * leng - 0.5 * text_width
-        y = 0.55 * leng - 0.5 * text_width
+        y = 0.55 * leng - 0.5 * text_height
         draw.rectangle(((x + 0.1 * text_width, y + 0.1 * text_height),
           (x + 0.9 * text_width, y + 0.9 * text_height)), fill=white)
         draw.text((x, y), label, fill=black, font=font)


@@ -265,7 +265,7 @@ class Creature(object):
                 skill1 -= 1
             elif border == "Wall":
                 skill1 += 1
-            elif border2 == "Slope" and not self.is_native(border):
+            elif border2 == "Slope" and not self.is_native(border2):
                 skill1 -= 1
             elif border2 == "Wall":
                 skill1 -= 1


@@ -238,7 +238,7 @@ class Creature(object):
             elif border == "Dune" and self.is_native(border):
                 dice += 2
             border2 = hex1.opposite_border(hexside)
-            if border2 == "Dune" and not self.is_native(border):
+            if border2 == "Dune" and not self.is_native(border2):
                 dice -= 1
         elif target in self.rangestrike_targets:
             dice = int(self.power / 2)


@@ -267,7 +267,7 @@ class CleverBot(DimBot.DimBot):
                     max_mean_hits = max(mean_hits, max_mean_hits)

             # Don't encourage titans to charge early.
-            if creature.name != "Titan" or game.battle_turn > 4:
+            if creature.name != "Titan" or game.battle_turn >= 4:
                 score += HIT_BONUS * max_mean_hits
                 score += KILL_BONUS * probable_kill
             score -= DAMAGE_PENALTY * total_mean_damage_taken


@@ -173,7 +173,7 @@ class GUIBattleHex(object):
                 if not os.path.exists(border_path):
                     sliceborder.slice_border_image(image_path, border_path,
                       hexsides)
-                input_surface = cairo.ImageSurface.create_from_png(image_path)
+                input_surface = cairo.ImageSurface.create_from_png(border_path)
                 input_width = input_surface.get_width()
                 input_height = input_surface.get_height()
                 output_width = myboxsize[0]


@@ -47,4 +47,4 @@ class Object2dIO(Object2dBase):
 				func = getattr(self, dataset_conf['factory-function'])
 				dataset = func()
 				dataset.name = name
-				dataset.load(data, dataset_path)
\ No newline at end of file
+				dataset.load(dataset_conf, dataset_path)
\ No newline at end of file


@@ -64,7 +64,7 @@ class PathBase(Dataset):

 	def interpolate_range(self, begin, end, interpolation_mode=None):
 		positions = [[i, self.get_position(i)] for i in range(begin, end+1) if self.get_position(i) is not None]
-		if len(positions)>2:
+		if len(positions)>=2:
 			positions = interpolate_positions(positions, begin, end, interpolation_mode)
 			for frame, pos in positions: self.set_position(frame, pos[0], pos[1])
 			self._tmp_points= []


@@ -57,7 +57,7 @@ class VideoIO(VideoBase):
 				dataset_conf 	= json.load(infile)
 				func 			= getattr(self, dataset_conf['factory-function'])
 				dataset 		= func()
-				dataset.load(data, obj_dir)
+				dataset.load(dataset_conf, obj_dir)
 				dataset.name    = name

 		super(VideoIO, self).load(data, video_path)
\ No newline at end of file


@@ -4,7 +4,7 @@ import blessings
 class Terminal(blessings.Terminal):
     def draw_block(self, block, x, y):
         for y, line in enumerate(block, start=y):
-            self.stream.write(self.move(x, y))
+            self.stream.write(self.move(y, x))
             self.stream.write(line)

 _terminal = Terminal()