@@ -12,7 +12,7 @@ class TestKatSvc(ClusterTest):
     test_helper.create_svc(cls.n1, 's1')

   def setUp(self) -> None:
-    self.subject: KatSvc = KatSvc.find(self.n1, 's1')
+    self.subject: KatSvc = KatSvc.find('s1', self.n1)

   def test_internal_ip(self):
     self.assertIsNotNone(self.subject.internal_ip)


@@ -155,7 +155,7 @@ class Event:
         self.verb = v
         break
     # channel is unset if it does not begin with #
-    if self.verb == "PRIVMSG" and len(self.channel):
+    if self.verb == "PRIVMSG" and not len(self.channel):
       self.is_pm = True
     for s in self.subscribers:
       try:


@@ -64,7 +64,7 @@ class vector:  # Data type name
         return not self.__eq__(other)

     def cross(self, other):     # Corss product
-        return vector(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y-other.x)
+        return vector(self.y*other.z - self.z*other.y, self.z*other.x - self.x*other.z, self.x*other.y - self.y*other.x)

     def dot(self, other):       # dot product
         return self.x*other.x + self.y*other.y + self.z*other.z


@@ -116,7 +116,7 @@ async def connect_two():
         cm_all = CentralManager()
         await cm_all.start_scan(scan_callback_all)

-        while d_10_device is None and d_5_device is None:
+        while d_10_device is None or d_5_device is None:
             await asyncio.sleep(.1)

         await cm_all.stop_scan()


@@ -27,4 +27,4 @@ def dump_salts(f, salts):
     f.write(payload)
   else:
     with open(f, 'w') as true_f:
-      f.write(payload)
+      true_f.write(payload)


@@ -178,4 +178,4 @@ class InterfaceServer(BaseServer):

     def _createReservationErrback(self, error, function_name, uuid):
         LOGGER.error("Unable to create reservation for %s:%s, %s.\n" % (function_name, uuid, error))
-        return uuid
\ No newline at end of file
+        return error
\ No newline at end of file


@@ -22,7 +22,7 @@ class BinMix(Node):
       self.blockbuf.copybuf(self.tone(self.block))
       if not noiseflag:
         self.blockbuf.orbuf(self.noise(self.block))
-    elif noiseflag:
+    elif not noiseflag:
       self.blockbuf.copybuf(self.noise(self.block))
     else:
       self.blockbuf.fill(0)


@@ -787,7 +787,7 @@ def file_fetch(fh, fromTime, untilTime, now = None):
   if untilTime > now:
     untilTime = now

-  diff = untilTime - fromTime
+  diff = now - fromTime
   for archive in header['archives']:
     if archive['retention'] >= diff:
       break


@@ -11,7 +11,7 @@ def merge(new_values, default_values):
     for key, value in default_values.items():
         nv = new_values.get(key, None)
         if isinstance(value, dict) and isinstance(nv, dict):
-            nd[key] = merge(value, nv)
+            nd[key] = merge(nv, value)
         else:
             if nv is None:
                 nd[key] = value


@@ -476,7 +476,7 @@ def charge_connected(input_batt, output_batt, fleet, home_bank, away_bank, min_p
         if may_charge:
             pot = (min_per_interval / 60.0) * power
             max_nrg = max_batt * max_soc
-            output_batt[i] = min(current_batt[i] + pot, max_nrg)
+            output_batt[i] = min(input_batt[i] + pot, max_nrg)

 @nb.njit(cache=True)


@@ -106,7 +106,7 @@ def from_repo(repo_url, chart, version=None, headers=None):
                     _get_from_repo(
                         repo_scheme,
                         repo_url,
-                        url,
+                        fname,
                         stream=True,
                         headers=headers,
                     )


@@ -106,7 +106,7 @@ def from_repo(repo_url, chart, version=None, headers=None):
                     _get_from_repo(
                         repo_scheme,
                         repo_url,
-                        fname,
+                        url,
                         stream=True,
                         headers=headers,
                     )


@@ -66,7 +66,7 @@ def read_tables(b_line_stream, d_line_stream=None):
             constituent_codes = []
             for line in lines:
                 l_parts = slices(line, [1,6,1,2,1,6])
-                constituent_codes.append(fxy2int(parts[5]))
+                constituent_codes.append(fxy2int(l_parts[5]))

             descriptors[d_descriptor_code] = LazySequenceDescriptor(d_descriptor_code, constituent_codes, '', table)
     return table


@@ -250,7 +250,7 @@ def load_taxa( file_name: MOptional[Filename[EXT.TXT]] = None ) -> None:
         raise ValueError( "load_taxa: Refused because the LECA must be loaded first." )

     num_clusters, num_taxa = state.leca_file.load_taxa( file_name )
-    MCMD.print( "{} taxa loaded into {} clusters.".format( num_clusters, num_taxa ) )
+    MCMD.print( "{} taxa loaded into {} clusters.".format( num_taxa, num_clusters ) )

     state.settings.last_taxa = file_name


@@ -76,7 +76,7 @@ class tgov1Agent():
         _, y3, self.x3 = sig.lsim(self.sys3, U=uVector, T=self.t,
                                    X0=[self.r_x1[self.mirror.c_dp-1],self.Gen.r_Pm[self.mirror.c_dp-1]])
         # Addition of damping
-        Pmech = y3 - dwVec*self.Dt # effectively removing the second block...
+        Pmech = y2 - dwVec*self.Dt # effectively removing the second block...

         # Set Generator Mechanical Power
         self.Gen.Pm = float(Pmech[1])


@@ -45,7 +45,7 @@ class WindowList:
             if name in EXCLUDE_APPLICATIONS:
                 continue

-            wmclass, minimized = get_wm_class_and_state(winid)
+            wmclass, minimized = get_wm_class_and_state(win)
             dock = disp.intern_atom('_NET_WM_WINDOW_TYPE_DOCK')
             if dock in ewmh.getWmWindowType(win):
                 continue


@@ -714,6 +714,6 @@ class RecentByPath(list):
         comments = []
         for reply in replies:
             post = state["content"][reply]
-            if category is None or (category is not None and post["category"] != category):
+            if category is None or (category is not None and post["category"] == category):
                 comments.append(Comment(post, lazy=True, steem_instance=self.steem))
         super(RecentByPath, self).__init__(comments)


@@ -11,7 +11,7 @@ class BugsnagMiddleware:

     async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
         if not self._debug:
-            await self.bugsnag_app(scope, send, receive)
+            await self.bugsnag_app(scope, receive, send)
             return
         await self.app(scope, receive, send)


@@ -162,7 +162,7 @@ class EasierSetup(object):
                 if value_path.lower().endswith('.md'):
                     try:
                         import pypandoc
-                        value = pypandoc.convert_text(value_path, 'rst', format='md')
+                        value = pypandoc.convert_text(value, 'rst', format='md')
                         value = value.replace("\r", "")
                     except ImportError:
                         print("Pandoc not found. Markdown to reStructuredText conversion failed.")


@@ -309,7 +309,7 @@ def create_subproxy_util(device, func, proxy_id, identifier, *args, **kwargs):
         subproxy_device = func(device, *args, **kwargs)
         proxy_ids[proxy_id] = subproxy_device

-        subproxy_sn = device.get_serial_number()
+        subproxy_sn = subproxy_device.get_serial_number()
         subproxy_identifier = "{}->{}".format(identifier, subproxy_sn)
         device_identifiers[subproxy_device] = subproxy_identifier


@@ -240,7 +240,7 @@ class DependencyCache(object):
             for args_, kwargs_ in reg_preproc:
                 depc._register_prop(*args_, **kwargs_)
             print(' * regsitering %d global algos ' % len(reg_algos))
-            for args_, kwargs_ in reg_preproc:
+            for args_, kwargs_ in reg_algos:
                 depc._register_algo(*args_, **kwargs_)

         ut.ensuredir(depc.cache_dpath)


@@ -2586,7 +2586,7 @@ class SQLDatabaseController(object):
                     superkey_index = superkey_colnames_list.index(primary_superkey)
                     superkey_paramx = superkey_paramxs_list[superkey_index]
                     superkey_colnames = superkey_colnames_list[superkey_index]
-            elif len(superkey_colnames) == 1:
+            elif len(superkey_colnames_list) == 1:
                 superkey_paramx = superkey_paramxs_list[0]
                 superkey_colnames = superkey_colnames_list[0]
             else:


@@ -91,7 +91,7 @@ class SpinDevice:
         :return: Response bytes as int
         """
         # payload and payload_size must be either both present, or both absent
-        assert((payload is None) != (payload_size is None))
+        assert((payload is None) == (payload_size is None))

         response = self._write(command)


@@ -38,7 +38,7 @@ class Slot:
             slot_value_node.text = str(self.value)
         elif type(self.value) is list and self.value:
             for sub_slot in self.value:
-                slot_node.append(sub_slot.as_xml)
+                slot_value_node.append(sub_slot.as_xml)
         elif self.type == 'frame':
             pass  # Empty frame element, just leave it
         else:


@@ -14,4 +14,4 @@ class GruntConfigMixin(object):
     def grunt_config(self, config=None, key=None):
         return grunt_conf(
             config={} if config is None else config,
-            key=key if key is None else self.grunt_config_key)
+            key=key if key is not None else self.grunt_config_key)

ReplaceText(target=' is not ' @(17,26)->(17,30))


@@ -103,7 +103,7 @@ class LeafReader(object):
     def read(self, length):
         offset = self._offset

-        if offset + length < len(self._leaf.data):
+        if offset + length <= len(self._leaf.data):
             self._offset += length
             return self._leaf.data[offset:offset + length]


@@ -61,7 +61,7 @@ def bootstrap_repl(which_ns: str) -> types.ModuleType:
     assert core_ns is not None
     ns.refer_all(core_ns)
     repl_module = importlib.import_module(REPL_NS)
-    ns.add_alias(sym.symbol(REPL_NS), repl_ns)
+    ns.add_alias(repl_ns, sym.symbol(REPL_NS))
     ns.refer_all(repl_ns)
     return repl_module


@@ -420,7 +420,7 @@ class TestResolveAlias:

             foo_ns_sym = sym.symbol("zux.bar.foo")
             foo_ns = get_or_create_ns(foo_ns_sym)
-            ns.add_alias(sym.symbol("foo"), foo_ns)
+            ns.add_alias(foo_ns, sym.symbol("foo"))
             assert sym.symbol(
                 "aliased-var", ns=foo_ns_sym.name
             ) == runtime.resolve_alias(sym.symbol("aliased-var", ns="foo"), ns=ns)


@@ -365,7 +365,7 @@ def print_kernel_xml(name: str, args: Iterable[Arg], kernel_xml: TextIO):
                                        size=size,
                                        offset=0 if is_stream else offset,
                                        host_size=host_size).rstrip('\n')
-    if is_stream:
+    if not is_stream:
       offset += size + 4
   hw_ctrl_protocol = 'ap_ctrl_none'
   if has_s_axi_control:


@@ -155,7 +155,7 @@ class FinCalendar(object):
         m = dt._m
         d = dt._d

-        startDate = FinDate(y, 1, 1)
+        startDate = FinDate(1, 1, y)
         dd = dt._excelDate - startDate._excelDate + 1
         weekday = dt._weekday


@@ -94,7 +94,7 @@ def buildIborCurve(tradeDate):
         dcType)
     swaps.append(swap5)

-    liborCurve = FinIborSingleCurve(settlementDate, depos, fras, swaps)
+    liborCurve = FinIborSingleCurve(valuationDate, depos, fras, swaps)

     return liborCurve


@@ -310,7 +310,7 @@ class TestScheduler(unittest.TestCase):
         # Then
         self.assertEqual(len(s.workers), 2)
         count = 0
-        while proxy.status() != 'done' and count < 10:
+        while proxy1.status() != 'done' and count < 10:
             time.sleep(0.1)
             count += 1


@@ -68,7 +68,7 @@ class Task(TaskModel):
     def __init__(self, job, frame, parent_task=None, state=None,
                  priority=None, attempts=None, agent=None):
         # build parent job id
-        if not modelfor(job, TABLE_JOB):
+        if modelfor(job, TABLE_JOB):
             jobid = job.jobid
             if jobid is None:
                 raise ValueError("`job` with null id provided")


@@ -116,5 +116,5 @@ class Task(TaskModel):
         if priority is not None:
             self.priority = priority

-        if attempts is None:
+        if attempts is not None:
             self.attempts = attempts


@@ -88,7 +88,7 @@ def skip(should_skip, reason):
     def wrapper(func):
         @wraps(func)
         def wrapped_func(*args, **kwargs):
-            if not should_skip:
+            if should_skip:
                 raise SkipTest(reason)
             return func(*args, **kwargs)
         return wrapped_func


@@ -337,7 +337,7 @@ class TypeChecks(object):
         if not isinstance(value, STRING_TYPES):
             raise TypeError("Expected a string for `value`")

-        if environment is not None or not isinstance(environment, dict):
+        if environment is not None and not isinstance(environment, dict):
             raise TypeError("Expected None or a dictionary for `environment`")

     def _check_map_path_inputs(self, path):


@@ -214,6 +214,6 @@ class Assign(APIResource):
         # are handled internally in this case.
         jobtype_loader = JobType.load(request_data)
         jobtype_loader.addCallback(loaded_jobtype, assignment_uuid)
-        jobtype_loader.addErrback(assignment_stopped, assignment_uuid)
+        jobtype_loader.addErrback(assignment_failed, assignment_uuid)

         return NOT_DONE_YET


@@ -348,7 +348,7 @@ class TestCase(_TestCase):
                         msg, '%s not less than or equal to %s' % (a, b)))

         def assertGreaterEqual(self, a, b, msg=None):
-            if not a <= b:
+            if not a >= b:
                 self.fail(
                     self._formatMessage(
                         msg, '%s not greater than or equal to %s' % (a, b)))


@@ -158,7 +158,7 @@ class Assign(APIResource):
                 request.finish()
                 return NOT_DONE_YET
             # If there is only a partial overlap
-            elif existing_task_ids ^ new_task_ids:
+            elif existing_task_ids & new_task_ids:
                 logger.error("Rejecting assignment with partial overlap with "
                              "existing assignment.")
                 unknown_task_ids = new_task_ids - existing_task_ids


@@ -218,7 +218,7 @@ class DoesntHaveRootAttributes(SuffixFormCondition):
         transitions = filter(lambda transition : not isinstance(transition.suffix_form_application.suffix_form.suffix, ZeroTransitionSuffix), transitions)
         transitions = filter(lambda transition : transition.suffix_form_application.applied_suffix_form, transitions)

-        if not transitions:
+        if transitions:
             return True

         if not parse_token.stem.dictionary_item.attributes:


@@ -89,7 +89,7 @@ class MockMorphemeContainerBuilder(object):
     def lexeme(self, lemma_root_str, lemma_root_syntactic_category=None, lemma_root_secondary_syntactic_category=None):
         self.lemma_root_str = lemma_root_str
         self.lemma_root_syntactic_category = lemma_root_syntactic_category
-        self.lemma_root_secondary_syntactic_category = lemma_root_syntactic_category
+        self.lemma_root_secondary_syntactic_category = lemma_root_secondary_syntactic_category

         return self


@@ -151,7 +151,7 @@ def sambamba_coverage_summary(job, config, samples, outfile):
             for sample in samples:
                 output.write("\t{samp_reads}"
                              "\t{s_perc1}"
-                             "\t{s_perc1}".format(samp_reads=amplicon[amplicon][sample],
+                             "\t{s_perc1}".format(samp_reads=amplicon_coverage[amplicon][sample],
                                                   s_perc1=amplicon_coverage[amplicon]["{}_percent_{}".format(sample, config['coverage_threshold'])],
                                                   s_perc2=amplicon_coverage[amplicon]["{}_percent_{}".format(sample, config['coverage_threshold1'])]))


@@ -64,7 +64,7 @@ def main():
     for workerklass in worker.workers:
         pid = os.fork()
         kids.append(pid)
-        if pid != 0:
+        if pid == 0:
             sys.exit(workerklass(statsd, opts.interval).run())

     while not SIGNALED:


@@ -60,7 +60,7 @@ class client:
 		if FC == 5 or FC == 15:
 			LEN = len(VAL) * 8
 		else:
-			LEN = len(VAL) / 2
+			LEN = len(VAL) // 2
 		lLEN = LEN & 0x00FF
 		mLEN = LEN >> 8
 		if self.TID < 255:


@@ -37,7 +37,7 @@ class Widget(object):
     def event(self, ev):
         "Don't override this without damn good reason"
         if self.disabled or not self.visible:
-            return True
+            return False

         type_ = ev.type
         if type_ == USEREVENT:


@@ -82,7 +82,7 @@ def download_matches(store_callback, seed_players, minimum_tier = Tier.bronze,
             # Iterate until matches_in_time_slice is big enough, and stop anyways after matches_per_time_slice iterations
             # this ensures the script will always terminate even in strange situations
             # (like when all our seeds have no matches in the time slice)
-            for _ in takewhile(lambda x: matches_in_time_slice >= matches_per_time_slice, range(matches_per_time_slice)):
+            for _ in takewhile(lambda x: matches_in_time_slice <= matches_per_time_slice, range(matches_per_time_slice)):
                 for tier in Tier:
                     for player_id, _ in zip(players_to_analyze.consume(tier), range(10)):
                         match_list = get_match_list(player_id, begin_time=time_slice.begin, end_time=time_slice.end, ranked_queues=queue.name)


@@ -205,7 +205,7 @@ def download_matches(match_downloaded_callback, end_of_time_slice_callback, conf
                                             random.random() < EVICTION_RATE}

                     # When a new patch is released, we can clear all the analyzed players and downloaded_matches if minimum_patch == 'latest'
-                    if conf['minimum_patch'].lower() != LATEST and get_patch_changed():
+                    if conf['minimum_patch'].lower() == LATEST and get_patch_changed():
                         analyzed_players = set()
                         downloaded_matches = set()


@@ -55,7 +55,7 @@ def get_course_activity_years(page):
         year = int(urls.YEAR_EXP.findall(year_link.attrs['href'])[0])
         if first is None or year < first:
             first = year
-        if last is None or year < last:
+        if last is None or year > last:
             last = year
     return first, last


@@ -221,7 +221,7 @@ class Win32Serial(SerialBase):
                 if n > 0:
                     buf = ctypes.create_string_buffer(n)
                     rc = win32.DWORD()
-                    err = win32.ReadFile(self.hComPort, buf, size, ctypes.byref(rc), ctypes.byref(self._overlappedRead))
+                    err = win32.ReadFile(self.hComPort, buf, n, ctypes.byref(rc), ctypes.byref(self._overlappedRead))
                     if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
                         raise SerialException("ReadFile failed (%s)" % ctypes.WinError())
                     err = win32.WaitForSingleObject(self._overlappedRead.hEvent, win32.INFINITE)


@@ -94,7 +94,7 @@ def finderb_nest(key, vector):
     # if the key is smaller than the first element of the
     # vector we return 1
     if key < vector[0]:
-        return 1
+        return 0

     while (b-a) > 1:  # loop until the intervall is larger than 1
         c = int(np.floor((a+b)/2))  # center of intervall


@@ -70,7 +70,7 @@ class Catalog:
         if command:
             return self._register(name, command)
         else:
-            return partial(self._register, command)
+            return partial(self._register, name)

     def _register(self, name, command):
         if name in self.commands:


@@ -53,7 +53,7 @@ def xml_convert(records, file_hash, recovered=True):

         sys = d['Event']['System']

-        dictionary = parser(record, {
+        dictionary = parser(d, {
             'timestamp_utc': sys['TimeCreated']['@SystemTime'],
             'event_id': sys['EventID'],
             'description': '',


@@ -58,7 +58,7 @@ class Database(Dict):
             elif isinstance(self.adaptor, str):
                 self.adaptor = importlib.import_module(self.adaptor)

-            if self.connection_string is None:
+            if self.connection_string is not None:
                 if self.adaptor.__name__ == 'psycopg2':
                     self.pool = importlib.import_module('psycopg2.pool').ThreadedConnectionPool(
                         self.minconn or 1, self.maxconn or 1, self.connection_string or ''

ReplaceText(target=' is not ' @(61,37)->(61,41))


@@ -50,7 +50,7 @@ def polygon_analysis(file_name,
     background = Image.new('RGBA', (bigside, bigside), (255, 255, 255, 255))
     offset = (0,0)
     background.paste(image, offset)
-    file_name2=f'{width_old*2}X{height_old*2}_{file_name}.png'
+    file_name2=f'{width_old*2}X{height_old*2}_{name_file}.png'
     save_image=os.path.join(cwd,file_name2)
     save_image_in_data=os.path.join(path_save,file_name2)


@@ -89,7 +89,7 @@ def create(repo, tag, name, message, draft, prerelease, target, assets):

     release = repo.create_git_release(
         tag=tag,
-        name=tag,
+        name=name,
         message=message,
         target_commitish=target,
         prerelease=prerelease,


@@ -289,7 +289,7 @@ class App(object):

     def run_local_GPU(self, folders_glob):
         bash_cmd = "export CUDA_VISIBLE_DEVICES=0"
-        if len(glob(folders_glob)) != (self.ngpus - self.gpus_in_use):
+        if len(glob(folders_glob)) > (self.ngpus - self.gpus_in_use):
             raise ValueError("Cannot run jobs of {} folders as only {} GPUs are available".format(len(glob(folders_glob)), self.ngpus - self.gpus_in_use))

         for folder in glob(folders_glob):


@@ -167,7 +167,7 @@ def build_breaker_predict(
     if reverse_scores:  # reverse the scores
         scores = 1 / (scores * np.max(1 / scores))

-    return np.vstack([winner_scores, winner_indices])
+    return np.vstack([scores, winner_indices])

 def build_breaker_analyze(log: str, *, colorize: bool = True):


@@ -280,6 +280,6 @@ if __name__ == '__main__':
     )

     # run annotator
-    annotator = Annotator([task1, task2], data)
+    annotator = Annotator(data, [task1, task2])
     annotator(data.ids)
     print(annotator.annotated)


@@ -88,7 +88,7 @@ class Pipeline():
     def refmac(self, cycles):
         directory = self.job_directory("refmac")
         use_phases = self.args.unbiased and self.min_rwork > 0.35
-        job = Refmac(self.args, directory, self.current_xyz, use_phases, cycles)
+        job = Refmac(self.args, directory, self.current_xyz, cycles, use_phases)
         self.jobs[self.cycle].append(job)
         self.current_hkl = job.hklout
         self.current_xyz = job.xyzout


@@ -54,7 +54,7 @@ class PackageRef:

     @property
     def dir_ref(self):
-        return "{}_{}_{}".format(self.name, self.arch, self.version)
+        return "{}_{}_{}".format(self.name, self.version, self.arch)

     def __repr__(self):


@@ -244,7 +244,7 @@ if __name__ == '__main__':
                 while cmd.fill:
                     filler = generator.next_localised_datetime(filler)

-                    if filler == checkpoint:
+                    if filler >= checkpoint:
                         break

                     print(JSONify.dumps(aggregate.report(filler)))


@@ -14,7 +14,7 @@ THRESHOLD = 1

 def log(page, message, level=WARNING):
-    if level > THRESHOLD:
+    if level >= THRESHOLD:
         print(">> {0}: {1} | {2}".format(CRITICALITY[level], message, page.url))


@@ -171,7 +171,7 @@ def create_layout(lex, examLex, toolbarLex):
                 Window(
                     content=BufferControl(
                         buffer_name='symbols',
-                        lexer=lexer
+                        lexer=examLex
                     )
                 ),
                 filter=ShowSymbol()


@@ -129,7 +129,7 @@ def generate_func_dict(
                 # No extra arguments for this.
                 key_args = {}

-            func_dict[func_name] = (func, key_args)
+            func_dict[toggle] = (func, key_args)

     return func_dict


@@ -785,7 +785,7 @@ def _import_list(entities, id, filing, cur):
     importer, entity_id = _list_importers[id]
     db_keys = list()
     for entity in entities:
-        db_keys.append(importer(entity[entity_id], id, filing, cur))
+        db_keys.append(importer(entity[entity_id], entity_id, filing, cur))
     return db_keys


@@ -76,7 +76,7 @@ class BasePLSA:
     def __rel_change(self, new: float) -> float:
         if self._likelihoods:
             old = self._likelihoods[-1]
-            return abs((new - old) / old)
+            return abs((new - old) / new)
         return inf

     def _result(self) -> PlsaResult:


@@ -29,7 +29,7 @@ class MockApp:
         if attach_to == 'request':
             self.req_middleware.append(middleware)
         elif attach_to == 'response':
-            self.res_middleware = [attach_to] + self.res_middleware
+            self.res_middleware = [middleware] + self.res_middleware

 class MockSession(Session):
     def __init__(self, app=MockApp(), master_interface=MockInterface(), *args, **kwargs):


@@ -350,7 +350,7 @@ class IRC:
     # request channel join
     def join(self, channel: str):
         channels = list(self.channels)
-        if channel in channels:
+        if channel not in channels:
             self.__to_join.append((channel, 0, time.time()))
         else:
             self.__warning('Already connected to channel {}, connection aborted'.format(channel))


@@ -412,7 +412,7 @@ class IRC:
     # send a packet and log it[, obfuscate after a certain index][, ignore the throttling cap]
     def __send(self, packet, obfuscate_after=None, ignore_throttle=0):
         # verify throttling status
-        if self.__anti_throttle() or ignore_throttle:
+        if self.__anti_throttle() or not ignore_throttle:
             # verify socket instance
             if self.__wait_for_status(0):
                 self.__socket.send(packet.encode('UTF-8'))


@@ -451,7 +451,7 @@ class IRC:
     # send a message to a channel and prevent sending to disconnected channels
     def __send_message(self) -> None:
         # if there is message to send and socket ready and socket not throttling
-        if len(self.__to_send) > 0 and self.__wait_for_status() and not self.__anti_throttle():
+        if len(self.__to_send) > 0 and self.__wait_for_status() and self.__anti_throttle():
             # retrieve the first message to send
             item = self.__to_send.pop(0)
             channel = item[0]


@@ -36,5 +36,5 @@ def iter_job(task_file, instance_file):
     while next_task[JOB_ID] != '':
         arrive_at, task_lines, instance_lines = next_task[ARR_TIME], [ next_task[REST] ], [ next_instance[REST] ]
         next_task = read_lines(task_file, next_task[JOB_ID], task_lines)
-        next_instance = read_lines(instance_file, next_task[JOB_ID], instance_lines)
+        next_instance = read_lines(instance_file, next_instance[JOB_ID], instance_lines)
         yield float(arrive_at), { 'tasks': task_lines, 'instances': instance_lines }


@@ -107,7 +107,7 @@ def run_mnist_eager(flags_obj):

   # Automatically determine device and data_format
   (device, data_format) = ('/gpu:0', 'channels_first')
-  if flags_obj.no_gpu or tf.test.is_gpu_available():
+  if flags_obj.no_gpu or not tf.test.is_gpu_available():
     (device, data_format) = ('/cpu:0', 'channels_last')
   # If data_format is defined in FLAGS, overwrite automatically set value.
   if flags_obj.data_format is not None:


@@ -46,7 +46,7 @@ def copy_and_encrypt(filepath, key):
     source_file.close()
     dest_file.close()

-    storage.import_blob(open(tmp_destination, 'rb'), id_)
+    storage.import_blob(id_, open(tmp_destination, 'rb'))
     os.remove(tmp_destination)

     return enc_hash.hexdigest()


@@ -133,7 +133,7 @@ def get_list(config):

 def create_linkpost(config, item_id, title, url, timestamp, is_draft=True):
     path = ''
-    if is_draft:
+    if not is_draft:
         path = config.get("linkpost_post_dir", "_posts/linkposts")
     else:
         path = config.get("linkpost_draft_dir", "_drafts/linkposts")


@@ -89,8 +89,8 @@ class Metadata(object):
             if keyspace in cf_def_rows:
                 for table_row in cf_def_rows[keyspace]:
                     table_meta = self._build_table_metadata(
-                            keyspace_meta, table_row, col_def_rows[keyspace])
-                    keyspace.tables[table_meta.name] = table_meta
+                        keyspace_meta, table_row, col_def_rows[keyspace])
+                    keyspace_meta.tables[table_meta.name] = table_meta

     def _build_keyspace_metadata(self, row):
         name = row["keyspace_name"]


@@ -26,7 +26,7 @@ class RoundRobinPolicy(LoadBalancingPolicy):

     def populate(self, cluster, hosts):
         self._live_hosts = set(hosts)
-        if len(hosts) == 1:
+        if len(hosts) <= 1:
             self._position = 0
         else:
             self._position = randint(0, len(hosts) - 1)


@@ -230,7 +230,7 @@ class BaseModel(object):
                         'unrecognized polymorphic key {} for class {}'.format(poly_key, poly_base.__name__)
                     )

-            if not issubclass(klass, poly_base):
+            if not issubclass(klass, cls):
                 raise PolyMorphicModelException(
                     '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__)
                 )


@@ -232,7 +232,7 @@ class BaseModel(object):

             if not issubclass(klass, cls):
                 raise PolyMorphicModelException(
-                    '{} is not a subclass of {}'.format(klass.__name__, poly_base.__name__)
+                    '{} is not a subclass of {}'.format(klass.__name__, cls.__name__)
                 )

             field_dict = {k: v for k, v in field_dict.items() if k in klass._columns.keys()}


@@ -772,7 +772,7 @@ class DowngradingConsistencyRetryPolicy(RetryPolicy):
                         received_responses, data_retrieved, retry_num):
         if retry_num != 0:
             return (self.RETHROW, None)
-        elif received_responses < required_responses:
+        elif received_responses <= required_responses:
             return self._pick_consistency(received_responses)
         elif not data_retrieved:
             return (self.RETRY, consistency)


@@ -895,7 +895,7 @@ class ModelMetaClass(type):
             if MultipleObjectsReturnedBase is not None:
                 break

-        MultipleObjectsReturnedBase = DoesNotExistBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned)
+        MultipleObjectsReturnedBase = MultipleObjectsReturnedBase or attrs.pop('MultipleObjectsReturned', BaseModel.MultipleObjectsReturned)
         attrs['MultipleObjectsReturned'] = type('MultipleObjectsReturned', (MultipleObjectsReturnedBase,), {})

         # create the class and add a QuerySet to it


@@ -17,7 +17,7 @@ def parse_2d_maze(maze_str):
     start_pos = None
     end_pos = None
     for row, row_str in enumerate(lines):
-        if len(row) != num_cols:
+        if len(row_str) != num_cols:
             raise ValueError('row length should be %d but got %d' %
                              (num_cols, len(row)))
         sub_walls = []


@@ -122,7 +122,7 @@ def test_s3_raw_io():

         s3object = S3RawIO(path)
         assert s3object._client_kwargs == client_args
-        assert s3object.name == url
+        assert s3object.name == path

         # Tests _head
         check_head_methods(s3object, m_time)


@@ -27,7 +27,7 @@ def _copy(src, dst, src_is_storage, dst_is_storage):
         if system is get_instance(dst):

             # Checks if same file
-            if system.relpath(src) != system.relpath(dst):
+            if system.relpath(src) == system.relpath(dst):
                 raise same_file_error(
                     "'%s' and '%s' are the same file" % (src, dst))


@@ -574,7 +574,7 @@ class SystemBase(ABC):
             stat[key] = S_IFREG

         # Add storage specific keys
-        for key, value in tuple(stat.items()):
+        for key, value in tuple(header.items()):
             stat['st_' + key.lower().replace('-', '_')] = value

         # Convert to "os.stat_result" like object


@@ -54,7 +54,7 @@ class BaseRLAlgorithmTest(BaseUnitTest):
         task = self.__setup_stub_task()
         policy = GreedyPolicy()
         value_func = self.__setup_stub_value_function()
-        episode = generate_episode(task, value_func, policy)
+        episode = generate_episode(task, policy, value_func)
         self.eq(3, len(episode))
         self.eq((0, 1, 1, 1), episode[0])
         self.eq((1, 2, 3, 9), episode[1])


@@ -12,7 +12,7 @@ def mark_as_active(pathname):
     """Mark the active page in the navbar"""
     for id_page in ('home', 'data', 'credits', 'contact', 'info'):
         if id_page in pathname:
-            document[pathname].class_name = 'active'
+            document[id_page].class_name = 'active'
         else:
             document[id_page].class_name = ''
     if 'show' in pathname:


@@ -45,7 +45,7 @@ class splitAC:

     def changeTemperature(self,newTemperature):
         ## set temperature for degree C
-        if not isinstance(newTemperature,int) or not isinstance(newTemperature,float):
+        if not isinstance(newTemperature,int) and not isinstance(newTemperature,float):
             raise Exception('Wrong usage of method')
         ## Fixing temps if not given as multiplies of 10 less than 180
         if newTemperature < 180:


@@ -240,7 +240,7 @@ class Anime(Base):
         related_type = None
         while True:
           if not curr_elt:
-            raise MalformedAnimePageError(self, html, message="Prematurely reached end of related anime listing")
+            raise MalformedAnimePageError(self, related_elt, message="Prematurely reached end of related anime listing")
           if isinstance(curr_elt, bs4.NavigableString):
             type_match = re.match('(?P<type>[a-zA-Z\ \-]+):', curr_elt)
             if type_match:


@@ -38,7 +38,7 @@ class MediaList(Base, collections.Mapping):
   def __init__(self, session, user_name):
     super(MediaList, self).__init__(session)
     self.username = user_name
-    if not isinstance(self.username, unicode) or len(self.username) < 2:
+    if not isinstance(self.username, unicode) or len(self.username) < 1:
       raise InvalidMediaListError(self.username)
     self._list = None
     self._stats = None


@@ -41,7 +41,7 @@ class QNodeScene(QGraphicsScene):
         nodes = [x for x in selectedItems if issubclass(type(x), QNodeSceneNode) and not issubclass(type(x), QNodeSceneNodeUndeletable)]
         #remainder = [x for x in selectedItems if not issubclass(type(x), (QNodeSceneNode, NodeLink))]

-        if links and nodes:
+        if links or nodes:
             self.undostack.beginMacro("Delete Stuff")
             for link in links:
                 self.undostack.push(type(link.startIO).DeleteLinkCommand(link.startIO))


@@ -124,7 +124,7 @@ class Cursor(object):
         '''Jump the cursor to a record (last record if "None") for forward scan.'''

         db = str(db) if isinstance(db, int) else quote(db.encode('utf-8'))
-        path += '/rpc/cur_jump_back?DB=' + db
+        path = '/rpc/cur_jump_back?DB=' + db

         request_dict = {'CUR': self.cursor_id}
         if key:


@@ -184,7 +184,7 @@ def fetch_one(round_num, tournament):
                 if 'nmr_returned' in df:
                     df['nmr_returned'] = df['nmr_returned'].astype(float)
                 if round_num == 158:
-                    df['nmr_bonus'] = bonus_nmr_only.where(df['usd_staking'].isna(), bonus_nmr_only)
+                    df['nmr_bonus'] = bonus_nmr_only.where(df['usd_staking'].isna(), bonus_split)
                     df['usd_bonus'] = df['usd_staking'] - df['usd_staking'] / (1 + staking_bonus_perc)
                     df['usd_staking'] = df['usd_staking'] - df['usd_bonus']
                     df['nmr_returned'] -= bonus_nmr_only


@@ -149,7 +149,7 @@ class ArgMapper(Mapper):

 def get_comment(func):  # type: (Any) -> Optional[Tuple[Dict[str, str], str]]
-    if not inspect.isfunction(func) or not inspect.ismethod(func):
+    if not inspect.isfunction(func) and not inspect.ismethod(func):
         # Classes should be handled, but are not yet...
         # Handling them would involve determining if they use __new__ or __init__
         # and using that as the function itself.


@@ -12,7 +12,7 @@ from surface._utils import normalize_type

 def parse_docstring(func):  # type: (Any) -> Optional[Tuple[Dict[str, str], str]]
     """ Parse out typing information from docstring """
-    if not inspect.isfunction(func) or not inspect.ismethod(func):
+    if not inspect.isfunction(func) and not inspect.ismethod(func):
         # Classes should be handled, but are not yet...
         # Handling them would involve determining if they use __new__ or __init__
         # and using that as the function itself.


@@ -47,6 +47,6 @@ class ConstantFolding(ASTOptimization):
                 node = ast.copy_location(ast.Num(n = val), node)
         elif all(isinstance(value, ast.Str) for value in (left, right)):
            if isinstance(node.op, ast.Add):
-                val  = left.s + left.s
+                val  = left.s + right.s
                 node = ast.copy_location(ast.Str(s = val), node)
         return node


@@ -96,7 +96,7 @@ class portgraph:

         portname = self.__flavorname2port(ports)

-        self.__addnode(portname)
+        self.__addnode(ports)

         proc = subprocess.Popen(['make', '-C',
                                  portname,


@@ -26,7 +26,7 @@ def ReciprocalRank(results, query):
             rank = np.where(results[i] == j)[0]

             if len(rank) == 0:  # Check values not found
-                rank = len(query[i])
+                rank = len(results[i])
             else:
                 rank = rank[0]
             all_rr.append(rank)


@@ -157,7 +157,7 @@ class TestSVDPlusPlus(unittest.TestCase):
                 recommender.compute_objective(data=data, P=recommender.P,
                                               Q=recommender.Q,
                                               Y=recommender.Y,
-                                              bias=learner.bias,
+                                              bias=recommender.bias,
                                               beta=learner.beta))

         # Assert objective values decrease


@@ -53,7 +53,7 @@ class ExtensionGrokker(martian.GlobalGrokker):
             module_directory = extension.module_directory
             # Register Silva Views directory
             if os.path.exists(os.path.join(module_directory, 'views')):
-                registerDirectory(module_directory, 'views')
+                registerDirectory('views', module_directory)

         return True


@@ -72,7 +72,7 @@ def detect( name, ipfile, bgfile, mapfile, alpha, l_thresh, pickle_file ) :

     # log inputs
     pique.msg( logfile, '  -> IP file  : ' + ipfile   )
-    pique.msg( logfile, '  -> BG file  : ' + ipfile   )
+    pique.msg( logfile, '  -> BG file  : ' + bgfile   )
     pique.msg( logfile, '  -> map file : ' + mapfile  )
     pique.msg( logfile, '  -> alpha    : ' + str(alpha)    )
     pique.msg( logfile, '  -> l_thresh : ' + str(l_thresh) )


@@ -87,7 +87,7 @@ class Order(object):
         """Return whether the operation failed, ie. completed but with an error code.
         Cancelled and discarded ops are considered failed.
         This assumes that this order has been .wait()ed upon"""
-        return self._result is True
+        return self._result is not True

     def result(self):
         """Wait until this is completed and return a response"""

ReplaceText(target=' is not ' @(90,27)->(90,31))


@@ -140,7 +140,7 @@ class Connection(object):
                     (self.node_definition.host, self.node_definition.port))
             except socket.error as e:
                 time.sleep(0.5)  # Connection refused? Very bad things?
-                if monotonic.monotonic() - start_at < timeout:
+                if monotonic.monotonic() - start_at > timeout:
                     raise ConnectionDead()
             else:
                 break


@@ -85,7 +85,7 @@ class Operation(object):
             self.enqueued_span = None

     def span_finished(self):
-        if self.processing_span is None:
+        if self.processing_span is not None:
             self.processing_span.finish()
             self.processing_span = None

ReplaceText(target=' is not ' @(88,31)->(88,35))


@@ -323,7 +323,7 @@ async def sender_server_handler(reader, writer):

         while True:
             # if flag backed to False, end this handler because it means receiver side client disconnected
-            if remote_stdout_connected == False or file_transfer_mode == False:
+            if remote_stdout_connected == False and file_transfer_mode == False:
                 # clear bufferd data
                 if sender_fifo_q.empty() == False:
                     print("reset sender_fifo_q because it is not empty")


@@ -619,7 +619,7 @@ if DEBUG:
         if request.user.is_authenticated:
             if request.path in ignored:
                 return False
-        return True
+        return False

     INSTALLED_APPS = INSTALLED_APPS + ['debug_toolbar']
     MIDDLEWARE = MIDDLEWARE + ['debug_toolbar.middleware.DebugToolbarMiddleware', ]


@@ -619,7 +619,7 @@ if DEBUG:
         if request.user.is_authenticated:
             if request.path in ignored:
                 return False
-        return False
+        return True

     INSTALLED_APPS = INSTALLED_APPS + ['debug_toolbar']
     MIDDLEWARE = MIDDLEWARE + ['debug_toolbar.middleware.DebugToolbarMiddleware', ]


@@ -57,7 +57,7 @@ class Corner():
             N = np.shape(data_frame)[1]
             for j in range(N):
                 for k in range(N):
-                    if i != k:
+                    if j != k:
                         pairgrid.axes[i, k].spines['right'].set_visible(True)
                         pairgrid.axes[i, k].spines['top'].set_visible(True)
                     else:


@@ -58,7 +58,7 @@ class Corner():
             for i in range(N):
                 for j in range(N):
                     for k in range(N):
-                        if j != k:
+                        if i != k:
                             pairgrid.axes[i, k].spines['right'].set_visible(True)
                             pairgrid.axes[i, k].spines['top'].set_visible(True)
                         else:


@@ -45,7 +45,7 @@ class PolyPoints(object):
 			if p.y < 0:
 				y = 0
 			elif p.y > rect.height:
-				x = rect.height
+				y = rect.height
 			else:
 				y = p.y


@@ -221,7 +221,7 @@ class TensorflowTrainer(object):

 			if self._statistics is not None:
 				self._statistics.output_path = self._statistics_dir + os.path.sep + "statistics.json"
-				self._statistics.generate(d)
+				self._statistics.generate(data)
 				self._statistics.save()

 			self._train_object_detection(labels, data, learning_rate)


@@ -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)


@@ -158,7 +158,7 @@ def object_actions(plugins: Dict[Type, Type[ParameterPlugin]], type_def: Union[T

         data = ObjectAction(name=method_name, meta=meta)

-        if method_def in type_def.CANCEL_MAPPING:
+        if method_name in type_def.CANCEL_MAPPING:
             meta.cancellable = True

         doc = parse_docstring(method_def.__doc__)


@@ -81,7 +81,7 @@ def timespec(seconds=0, nanoseconds=0):
             >>> io_uring_wait_cqes(..., ts=timespec(), ...)
             >>> io_uring_wait_cqes(..., ts=timespec(None), ...)
     '''
-    if not seconds or nanoseconds:
+    if seconds or nanoseconds:
         ts = ffi.new('struct __kernel_timespec[1]')
         ts[0].tv_sec = seconds or 0
         ts[0].tv_nsec = nanoseconds or 0


@@ -240,7 +240,7 @@ class Anime(Base):
         related_type = None
         while True:
           if not curr_elt:
-            raise MalformedAnimePageError(self, html, message="Prematurely reached end of related anime listing")
+            raise MalformedAnimePageError(self, related_elt, message="Prematurely reached end of related anime listing")
           if isinstance(curr_elt, bs4.NavigableString):
             type_match = re.match('(?P<type>[a-zA-Z\ \-]+):', curr_elt)
             if type_match:


@@ -15,7 +15,7 @@ locale.setlocale(locale.LC_ALL, "C")

 def main():
-    if len(sys.argv) <= 2:
+    if len(sys.argv) < 2:
         usage(sys.argv[0])
         sys.exit(1)
     duration = int(sys.argv[1])


@@ -152,7 +152,7 @@ def _shape_plus_minus_divide_times(symbol_table, node):
                 shape = shape + (left_element,)
             elif is_symbolic_element(left_element): # only left is symbolic
                 array_name = generate_unique_array_name(symbol_table)
-                symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (left_element,))
+                symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (right_element,))
                 conditions.append(BinaryNode(MOANodeTypes.EQUAL, (), left_element, ArrayNode(MOANodeTypes.ARRAY, (), array_name)))
                 shape = shape + (right_element,)
             elif is_symbolic_element(right_element): # only right is symbolic


@@ -116,7 +116,7 @@ def _shape_psi(symbol_table, node):
             conditions.append(BinaryNode(MOANodeTypes.LESSTHAN, (), left_element, right_element))
         elif is_symbolic_element(left_element): # only left is symbolic
             array_name = generate_unique_array_name(symbol_table)
-            symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (left_element,))
+            symbol_table = add_symbol(symbol_table, array_name, MOANodeTypes.ARRAY, (), (right_element,))
             conditions.append(BinaryNode(MOANodeTypes.LESSTHAN, (), left_element, ArrayNode(MOANodeTypes.ARRAY, (), array_name)))
         elif is_symbolic_element(right_element): # only right is symbolic
             array_name = generate_unique_array_name(symbol_table)


@@ -48,7 +48,7 @@ class DeviceLoader(pdfminer.pdfdevice.PDFTextDevice):
                 device_path.append(
                     (segment[0],)
                     + pdfminer.utils.apply_matrix_pt(self.ctm, (x, y)))
-        self.page.add_shape(content.Shape(stroke, fill, evenodd, path))
+        self.page.add_shape(content.Shape(stroke, fill, evenodd, device_path))

     def render_image(self, name, stream):
         self.page.add_image(content.Image(self.ctm, stream))


@@ -158,7 +158,7 @@ def joint_express_normalize(obs_matrices, exp_matrices, max_iter=1000,

     # apply optimized bias to observed
     log_corr_obs_matrices = [(log_obs_matrix.T - bias_factors).T - bias_factors
-                             for log_obs_matrix in log_exp_matrices]
+                             for log_obs_matrix in log_obs_matrices]

     # undo log transform
     normalized_matrices = [np.exp(log_corr_obs_matrix) - 1


@@ -21,7 +21,7 @@ def run(parser, args, conn_config):
                 if i % 100000 == 0:
                     mc.set_kmers(kmers, colour)
                     kmers = []
-        mc.set_kmers(kmers, i)
+        mc.set_kmers(kmers, colour)

         # kmers = inf.read().splitlines()


@@ -74,7 +74,7 @@ class AtlasSeq(object):
     def search(self, seq: hug.types.text=None, fasta_file: hug.types.text=None, threshold: hug.types.float_number=1.0):
         """Returns samples that contain the searched sequence.
         Use -f to search for sequence from fasta"""
-        if not seq or fasta_file:
+        if not seq or not fasta_file:
             return "-s or -f must be provided"
         return search(seq=seq,
                       fasta_file=fasta_file, threshold=threshold, conn_config=CONN_CONFIG)


@@ -24,5 +24,5 @@ def build(bloomfilter_filepaths, samples, graph):
     bloomfilters = []
     for f in bloomfilter_filepaths:
         bloomfilters.append(load_bloomfilter(f))
-    graph.build(bloomfilter_filepaths, samples)
+    graph.build(bloomfilters, samples)
     return {'result': 'success'}


@@ -28,7 +28,7 @@ class Buffer(object):
         else: raise StopIteration

     def pull(self, block_size, overlap=0, pad=False):
-        if overlap and overlap >= block_size:
+        if overlap and overlap > block_size:
             raise ValueError('overlap cannot be more than block_size')

         # First, get as much blocks of data as needed.


@@ -65,7 +65,7 @@ class Detector:
         :param multi_analysis: Needed for multiprocess-analysis
         :return: The analysis results as dict
         """
-        if multi_analysis:
+        if ml_analysis:
             self.analyser = FCN()
         start = time.time()
         logging = logging if self.logging is None else self.logging


@@ -40,7 +40,7 @@ class DataBase(object):
         # new entries can be saved
         self.CAN_SAVE = can_save
         # additional config options for database connection or fukebane(s)
-        self.HAS_CONFIG = can_save
+        self.HAS_CONFIG = has_config
         # the widget for additional config
         self.widget = widget


@@ -46,7 +46,7 @@ class Site(baseobject.Base_Object):
             value = self.wrapper.handle(dict(self.config.items(item)))
             if value:
                 setattr(self, item, value)
-                self.fields.add(value)
+                self.fields.add(item)

     def __repr__(self):
         return '<Difficulty Site %s, %s>' % (self.name, str(self.coins))


@@ -76,7 +76,7 @@ class ContentLine:
         params = {}
         for paramstr in params_strings:
             if '=' not in paramstr:
-                raise ParseError("No '=' in line '{}'".format(line))
+                raise ParseError("No '=' in line '{}'".format(paramstr))
             pname, pvals = paramstr.split('=', 1)
             params[pname] = pvals.split(',')
         return cls(name, params, value)


@@ -284,7 +284,7 @@ def build_mm_simulation(topology,system,positions,temperature=300.0 * unit.kelvi
 #          print("to confirm their validity for these model settings,")
 #          print("before performing a full simulation.")
           time_step_list = [(10.0 * (0.5 ** i)) * unit.femtosecond for i in range(0,14)]
-          simulation_time_step,force_cutoff = get_simulation_time_step(topology,system,positions,temperature,time_step_list,total_simulation_time)
+          simulation_time_step,force_cutoff = get_simulation_time_step(topology,system,positions,temperature,total_simulation_time,time_step_list)
         friction = 0.0

         integrator = LangevinIntegrator(temperature._value,friction,simulation_time_step.in_units_of(unit.picosecond)._value)


@@ -252,7 +252,7 @@ def test_expectations_fraction_contacts_pdb(tmpdir):
     # Test free energy fitting / derivative calculation:
     ddeltaF_out, d2deltaF_out, spline_tck = get_free_energy_derivative(
         deltaF_values,
-        temperature_list,
+        full_T_list,
         plotfile=f"{output_directory}/ddeltaF_dT.pdf",
     )


@@ -35,7 +35,7 @@ class ResourceCodeManage:
         """
         resource_code = self.map.get(code)
         if not resource_code:
-            if resource_code != 0:
+            if code != 0:
                 warnings.warn('未知错误码', DeprecationWarning)
             return ""
         return resource_code.get_message()


@@ -12,7 +12,7 @@ logger = logging.getLogger('system')

 def upload_aliyun_oss(folder):
-    if hasattr(settings, 'ALIYUN_OSS'):
+    if not hasattr(settings, 'ALIYUN_OSS'):
         raise Exception('未配置oss')
     AccessKeyId = settings.ALIYUN_OSS["AccessKeyId"]
     AccessKeySecret = settings.ALIYUN_OSS["AccessKeySecret"]


@@ -162,7 +162,7 @@ class TimeseriesAggregator(Aggregator):
         # size
         first_times = [i[0][0] for i in measurements.values() if i and i[0]]
         last_times = [i[-1][0] for i in measurements.values() if i and i[-1]]
-        if not (first_times or last_times):
+        if not (first_times and last_times):
             raise RuntimeError(u"No data to aggregate. Run with -l and check log file to investigate.")
         t_0 = min(first_times)
         t_max = max(last_times)


@@ -422,7 +422,7 @@ class ResultWidget(get_ui_class("resultwidget.ui")):
         return self.settings.ZERO_Y

     def disable_log(self, val=None):
-        if val is not None and val != self.settings.LOG_SCALE:
+        if val is not None and val == self.settings.LOG_SCALE:
             self.settings.LOG_SCALE = not val
             self.update()
         return not self.settings.LOG_SCALE


@@ -281,7 +281,7 @@ class BatchRunner(object):
             settings.load_test(informational=settings.BATCH_DRY)
             settings.DATA_FILENAME = self.gen_filename(settings, b, argset, rep)

-            yield batch, settings
+            yield b, settings

     def get_argsets(self, batch):
         argsets = []


@@ -133,7 +133,7 @@ def diff_parts(strings, sep):
     a separator and pruning parts that are identical for all strings"""

     parts = [s.split(sep) for s in strings]
-    np = [p for p in zip(*parts) if len(set(p)) > 1]
+    np = [p for p in zip(*parts) if len(set(p)) >= 1]

     return [sep.join(p) for p in zip(*np)]


@@ -1310,7 +1310,7 @@ class Plotter(ArgParam):
             if self.absolute_time:
                 start += results.t0

-            if end < 0:
+            if end <= 0:
                 end += results.meta("TOTAL_LENGTH")

             min_idx = data[0].searchsorted(start, side='right')


@@ -654,4 +654,4 @@ class TestPetstore(object):
         response_result = response_validator.validate(request, response)

         assert response_result.errors == []
-        assert response_result.data == data
+        assert response_result.data == data_json


@@ -331,7 +331,7 @@ class MSMLocator(core.AVBObject):
                 self.mob_id = mob_id
             elif tag == 0x03:
                 read_assert_tag(f, 76)
-                self.last_known_volume_utf8 = read_string(length, 'utf-8')
+                self.last_known_volume_utf8 = read_string(f, 'utf-8')
             else:
                 raise ValueError("%s: unknown ext tag 0x%02X %d" % (str(self.class_id), tag,tag))


@@ -65,7 +65,7 @@ class CompanyUnderline(object):
     def setup_country(self):
         """Set country based on known information
         """
-        if not hasattr(self, 'exchange') and self.exchange is None:
+        if not hasattr(self, 'exchange') or self.exchange is None:
             return
         exch_country = find_country_for_exchange(self.exchange)
         if hasattr(self, 'country') and self.country:


@@ -36,7 +36,7 @@ def main(argv):
     inp = opts['<input>']
     out = opts['<output>']
     (m, _) = probe(inp)
-    if opts['-D'] is not None:
+    if opts['-D'] is None:
         if opts['-S'] is not None:
             S = long(opts['-S'])
             random.seed(S)


@@ -135,7 +135,7 @@ class ExtendedActionLinkRouterMixin(object):
             dynamic_routes_instances.append(Route(
                 url=replace_methodname(route.url, endpoint),
                 mapping=dict((httpmethod, methodname) for httpmethod in httpmethods),
-                name=replace_methodname(route.name, methodname),
+                name=replace_methodname(route.name, endpoint),
                 initkwargs=initkwargs,
             ))
         return dynamic_routes_instances


@@ -67,7 +67,7 @@ class PasswordResetTokenGenerator:
             return False

         # Check the timestamp is within limit
-        if (self._num_days(self._today()) - ts) > self.timeout_days:
+        if (self._num_days(self._today()) - ts) >= self.timeout_days:
             return False

         return True


@@ -54,7 +54,7 @@ def main_tornado():
     application = tornado.web.Application([(r"/", MainHandler)])
     http_server = tornado.httpserver.HTTPServer(application)
     http_server.listen(options.port)
-    loop.start()
+    xcfg.start()

 if __name__ == "__main__":


@@ -291,7 +291,7 @@ class SerialWaveformPresenter(WaveformPresenter):
         self.load(model)

     def load_next(self):
-        if self.current_model > len(self.unprocessed):
+        if self.current_model >= len(self.unprocessed):
             return
         self.current_model += 1
         filename, frequency = self.unprocessed[self.current_model]


@@ -31,7 +31,7 @@ class WatcherWorker:
         raise NotImplementedError()

     def is_available(self):
-        return len(self.subscribed_topics) <= self.max_topics
+        return len(self.subscribed_topics) < self.max_topics

     def _subscribe(self, topic):
         self.subscribed_topics.append(str(topic))


@@ -55,7 +55,7 @@ def is_quoted_cookie_octets(txt):
     if len(txt) <= 2:
         return False

-    if (not txt.startswith('"') and
+    if (not txt.startswith('"') or
             not txt.endswith('"')):
         return False


@@ -18,7 +18,7 @@ class CoincurveRecipe(PythonRecipe):
         env['LDSHARED'] = env['CC'] + ' -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions'
         libsecp256k1 = self.get_recipe('libsecp256k1', self.ctx)
         libsecp256k1_dir = libsecp256k1.get_build_dir(arch.arch)
-        env['CFLAGS'] = ' -I' + os.path.join(libsecp256k1_dir, 'include')
+        env['CFLAGS'] += ' -I' + os.path.join(libsecp256k1_dir, 'include')
         # required additional library and path for Crystax
         if self.ctx.ndk == 'crystax':
             # only keeps major.minor (discards patch)


@@ -14,7 +14,7 @@ def main(args=None):
     if '--stats' in args:
         args.remove('--stats')
         args.append('--stats')
-    if len(args) > 1:
+    if len(args) > 0:
         if args[0] == '-c':
             prog = args[1].strip('"')
         else:


@@ -35,6 +35,6 @@ def project_electrodes(electrodes_file, freesurfer_path):
             material = one_chans['material']
             f.write(f'{_chan.label}\t{xyz}\t{elec_type}\t{size}\t{material}\n')

-    old_json = replace_underscore(Path(f.filename), 'coordframe.json')
+    old_json = replace_underscore(Path(electrodes_file.filename), 'coordframe.json')
     new_json = replace_underscore(tsv_electrodes, 'coordframe.json')
     copyfile(old_json, new_json)  # TODO: add info about transformation


@@ -33,7 +33,7 @@ def main(output_dir):
             p.starmap(save_frequency, args)
     else:
         for arg in args:
-            save_frequency(*args)
+            save_frequency(*arg)

 def save_frequency(ieeg_file, cond):


@@ -140,4 +140,4 @@ def make_segments(dat):
         out.axis['time'][i] = dat.axis['time'][0]
         out.axis['chan'][i] = dat.axis['chan'][0]

-    return dat
+    return out


@@ -94,7 +94,7 @@ class GoogleCloudStorage(Storage):
         return self.created_time(name)

     def url(self, name):
-        if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'):
+        if not os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'):
             # we need this in order to display images, links to files, etc from the local appengine server
             filename = "/gs"+self.location+"/"+name
             key = create_gs_key(filename)


@@ -35,7 +35,7 @@ def clear(key, participant_identifier):
         # Remove the direct entry
         cache_key = COUNTER_CACHE_KEY % key
         pipe = r.pipeline()
-        freq, _ = pipe.hget(key, participant_identifier).hdel(cache_key, participant_identifier).execute()
+        freq, _ = pipe.hget(cache_key, participant_identifier).hdel(cache_key, participant_identifier).execute()

         # Remove from the histogram
         freq_cache_key = COUNTER_FREQ_CACHE_KEY % key


@@ -74,7 +74,7 @@ class Generator:
                                 for s in self.app.sources.get_dependencies(c, reverse=True, recursive=True)])

             # Add source and context dependencies to the changeset.
-            changes.generate |= source_deps | context_deps
+            dep_changes.generate |= source_deps | context_deps

         # Prepare dependent changes that weren't in the original changes list
         for path in (dep_changes.generate - changes.generate):


@@ -189,7 +189,7 @@ class ZenodoUploadHandler(ZenodoBaseHandler):
             print("doi: "+str(doi))
             self.set_status(201)
             self.write(json.dumps(info))
-            store_record(doi, filename, directory_to_zip, access_token)
+            store_record(doi, path_to_file, directory_to_zip, access_token)
             #self.redirect("http://127.0.0.1:7000/portal/upload/"+doi)
             self.finish()
         else:


@@ -2126,7 +2126,7 @@ _rl.InitWindow.argtypes = [Int, Int, CharPtr]
 _rl.InitWindow.restype = None
 def init_window(width: int, height: int, title: AnyStr) -> None:
     """Initialize window and OpenGL context"""
-    return _rl.InitWindow(_int(width), _int(width), _str_in(title))
+    return _rl.InitWindow(_int(width), _int(height), _str_in(title))

 _rl.CloseWindow.argtypes = _NOARGS


@@ -237,7 +237,7 @@ def extract_readgroup_json(bam_path, logger):
     bam_name, bam_ext = os.path.splitext(bam_file)
     readgroups_json_file = bam_name+'.json'
     with open (bam_path) as f:
-        samfile = pysam.AlignmentFile(bam_path, 'rb', check_header=True, check_sq=False)
+        samfile = pysam.AlignmentFile(f, 'rb', check_header=True, check_sq=False)
         readgroup_dict_list = get_readgroup_dict_list(samfile)
     with open(readgroups_json_file, 'w') as f:
         json.dump(out_readgroup_dict_list, f, indent=4)


@@ -239,7 +239,7 @@ def extract_readgroup_json(bam_path, logger):
         if not bam_readgroup_dict_list:
             logger.error('There are no readgroups in BAM: {}'.format(samfile.filename))
             raise NoReadGroupError
-        readgroup_dict_list = get_readgroup_dict_list(samfile, logger)
+        readgroup_dict_list = get_readgroup_dict_list(bam_readgroup_dict_list, logger)
     with open(readgroups_json_file, 'w') as f:
         json.dump(readgroup_dict_list, f, indent=4)
     return readgroups_json_file


@@ -11,7 +11,7 @@ def snakeize_dict(dict_):
     answer = {}
     for key in dict_:
         nkey = snakeize_s(key)
-        answer[key] = dict_[key]
+        answer[nkey] = dict_[key]
     return answer

 class MonoCard:


@@ -24,7 +24,7 @@ def setup_trinity_logging(level):
     logger.setLevel(logging.DEBUG)
     logger.addHandler(handler)

-    listener = handlers.QueueListener(log_queue, logger)
+    listener = handlers.QueueListener(log_queue, handler)

     return logger, log_queue, listener


@@ -273,7 +273,7 @@ class BaseTransactionExecutor(metaclass=ABCMeta):
         valid_transaction = self.validate_transaction(transaction)
         message = self.build_evm_message(valid_transaction)
         computation = self.build_computation(message, valid_transaction)
-        finalized_computation = self.finalize_computation(computation, valid_transaction)
+        finalized_computation = self.finalize_computation(valid_transaction, computation)
         return finalized_computation

     @abstractmethod


@@ -44,7 +44,7 @@ class Reader(object):
             self._url = path

         if self._index < 0:
-            if self._feed_page is not feedparser.FeedParserDict:
+            if self._feed_page is feedparser.FeedParserDict:
                 for link in self._feed_page.links:
                     if link.rel == 'previous':
                         self._url = link.href


@@ -745,4 +745,4 @@ def dn_from(id):
     Basically the ID string is equivalent to a DN but without
     certain characters that can cause problems like '/'
     """
-    return id.replace('.', DOT).replace(SLASH, '/')
+    return id.replace(DOT, '.').replace(SLASH, '/')


@@ -38,7 +38,7 @@ class JavaParser(AbstractParser):
                 if current_class:
                     current_class[1] = last_closing_bracket_number
                 if current_method:
-                    current_method[1] = last_closing_bracket_number
+                    current_method[1] = penultimate_closing_bracket_number
                     components.append(current_method)
                 current_class = [line_counter, 0, search.group(2)]
                 continue


@@ -83,7 +83,7 @@ def build(algorithm, objective, diff, input_dir, solution_dir, build_dir):

     if diff:
         schedule = solution_to_schedule(solution, events, slots)
-        event_diff = event_schedule_difference(schedule, original_schedule)
+        event_diff = event_schedule_difference(original_schedule, schedule)
         logger.debug(f'\nevent_diff:')
         for item in event_diff:
             logger.debug(f'{item.event.name} has moved from {item.old_slot.venue} at {item.old_slot.starts_at} to {item.new_slot.venue} at {item.new_slot.starts_at}')


@@ -46,7 +46,7 @@ class RatingManager(object):
             object_id       = self.instance.id,
             key             = self.field.key,
         )
-        if not user:
+        if user:
             kwargs['user'] = user
         else:
             kwargs['user__isnull'] = True


@@ -79,7 +79,7 @@ class GradeChangeEmailer:

         if old_html_table != html_table:
             mail_text = " <meta charset='utf-8'>"
-            mail_text = "Es gab Änderungen in deinen Noten:\n"
+            mail_text += "Es gab Änderungen in deinen Noten:\n"
             mail_text += html_table
             mail_text += ""
             self.send_mail(mail_text)


@@ -72,7 +72,7 @@ class QuickUnitPlugin(Plugin):
         self.verbosity = options.verbosity
         if options.quickunit_prefix:
             self.prefixes = options.quickunit_prefix
-            if len(self.prefixes) == 0:
+            if len(self.prefixes) == 1:
                 self.prefixes = self.prefixes[0].split('\n')
         else:
             self.prefixes = ["tests/"]


@@ -972,7 +972,7 @@ class QueryBuilder:
             if _is_dtype(prop, (String, DateTime, Date)):
                 field = jsonb.astext
             else:
-                field = sa.cast(field, JSONB)
+                field = sa.cast(jsonb, JSONB)
         else:
             field = self.table.main.c[prop.name]


@@ -155,7 +155,7 @@ class TestModel:

         model_b._internal_id = model_a._internal_id

-        assert model_a == model_b
+        assert model_a != model_b

     @pytest.mark.parametrize(
         "model, expected_fields, expected_dependency_fields",


@@ -54,7 +54,7 @@ class FlipFlop(Task):
         for i, (input_start, echo_start) in enumerate(zip(input_times, echo_times)):

             if input_start <= t < input_start + echo_start:
-                x_t = 1.0
+                x_t += 1.0
                 mask_t = np.zeros(self.N_out)

             elif echo_start <= t < echo_start + echo_duration:


@@ -29,7 +29,7 @@ def load_template(name, paths=None, raw=False):
             with open(full_name, encoding='utf-8') as fin:
                 src = fin.read()

-            return kompile(src, raw=raw, filename=name)
+            return kompile(src, raw=raw, filename=full_name)
         except FileNotFoundError:
             pass
     else:


@@ -488,7 +488,7 @@ def compare_predictions(df, y_var_name, percent_data=None,
             timeit(plot_rocs, models, df_X, y)
             plt.show()
     print(f'MAKE SUBSAMPLE TIME: {time() - starttotal}')
-    return names, results, models, pipeline, df_X
+    return names, results, fit_models, pipeline, df_X

 def bootstrap_train_premade(model, X, y, bootstraps=1000, **kwargs):
     """Train a (linear) model on multiple bootstrap samples of some data and


@@ -150,7 +150,7 @@ def nodetool(cmd):
                             stderr=subprocess.STDOUT,
                             shell=True)
     output = proc.communicate()
-    if output.returncode != 0:
+    if proc.returncode != 0:
         raise NodetoolException(output)
     return output[0]


@@ -373,7 +373,7 @@ class Signal:
             if instance is None:
                 fnotify = self._fnotify
             else:
-                fnotify = types.MethodType(instance, self._fnotify)
+                fnotify = types.MethodType(self._fnotify, instance)
         validator = self._fvalidation
         if validator is not None and instance is not None:
             validator = types.MethodType(validator, instance)


@@ -129,7 +129,7 @@ class LInstallR(InstallR):
         version_name = "R-%s" % version
         if Path(self.bin_path / "R").exists():
             remove(str(self.bin_path / "R"))
-        symlink(str(self.lib_path / version_name / "bin" / "R"), str(self.bin_path / "R"))
+        symlink(str(self.bin_path / "R"), str(self.lib_path / version_name / "bin" / "R"))

     def clear_tmp_dir(self):
         # Set up the temporary directory for installation


@@ -255,7 +255,7 @@ def order_links(links):
                     minor = link
             except TypeError:
                 pass
-        ordered_links.append(link)
+        ordered_links.append(minor)
         links_list.remove(minor)
     return ordered_links


@@ -192,7 +192,7 @@ class TopicFilterForm(forms.Form):
         topics = ProjectTopic.objects.all()
         topics_list = []

-        for topic in topics_list:
+        for topic in topics:
             if topic.projects.count():
                 topics_list.append((topic.id, topic.name))
         return topics_list


@@ -1426,7 +1426,7 @@ class SystemFS:
         for root, dirs, files in os.walk(startDir):
             for name in files:
                 if fnmatch.fnmatch(name, fileregex):
-                    result.append(os.path.join(root, fileregex))
+                    result.append(os.path.join(root, name))
         return result

     def grep(self, fileregex, lineregex):


@@ -216,7 +216,7 @@ def download_reviews_for_app_id(app_id,
             else:
                 collection_keyword = 'first posted'
             print('Collecting reviews {} after {}'.format(collection_keyword,
-                                                          timestamp_threshold))
+                                                          date_threshold))

     review_dict = load_review_dict(app_id)


@@ -153,7 +153,7 @@ class PacketHandler(BasePacketHandler):
             # convert from packet to sample ID
             sample_id = (packet_id - 1) * 2 + delta_id + 1
             # 19bit packets hold deltas between two samples
-            self._last_eeg_data += np.array(deltas[delta_id])
+            self._last_eeg_data -= np.array(deltas[delta_id])
             self._update_counts_and_enqueue("EEG", sample_id)

     def _parse_compressed_19bit(self, packet_id, packet):


@@ -616,7 +616,7 @@ class OGame2(object):
         fleets_list = []
         response = self.session.get('https://s{}-{}.ogame.gameforge.com/game/index.php?page=ingame&component=movement'
                                     .format(self.server_number, self.server_language))
-        if response.status_code == 302:
+        if response.status_code != 302:
             fleets = response.text.split('<div id="fleet')
             del fleets[0]
             for fleet in fleets:


@@ -21,7 +21,7 @@ class FilteredListView(ListView):

         filter_dict = {}

-        if not value in self.filter_keys:
+        if not key in self.filter_keys:
             raise ImproperlyConfigured(
                 "%s is not present in filter_keys (%s)" % (key, self.filter_keys)
             )


@@ -337,7 +337,7 @@ class AutoPatternsMixin(object):
             """View URL name (unprefixed, this is the name we give to url())"""
             return cls.get_url_name(view)

-        if view not in view.get_views():
+        if view not in cls.get_views():
             raise ImproperlyConfigured(
                 "Tried to get the URL patterns for a view (%s)"
                 " that is not defined by get_views" % view


@@ -119,7 +119,7 @@ def make_model_mixin(view_class,

     setattr(ModelMixin,
             'get_%s_url_name' % view_class.get_underscored_action_name(),
-            _get_url)
+            _get_url_name)

     if extra_funcs:
         for func_name, func in extra_funcs.items():


@@ -28,7 +28,7 @@ class FsdbThreatFeed():
         for (count,entry) in enumerate(self._tfh):
             array.append(entry)
             dictionary[entry[index_column]] = entry # note, may erase older ones; build array?
-            if max_records and count >= max_records:
+            if max_records and count > max_records:
                 break

         return (array, dictionary)


@@ -62,7 +62,7 @@ class KafkaDataSource(DataSource):
         if self._end_time:
             self.verbose("searching forward from:")
             self.verbose(decoded_row)
-            count += 0
+            count = 0
             while True:
                 count += 1
                 decoded_time = decoded_row[self._time_column]


@@ -51,4 +51,4 @@ class ConnectionCounter(Config):

         results = {'connections': conns,
                    'ports': ports}
-        return (self._output_key, conns)
+        return (self._output_key, results)


@@ -409,7 +409,7 @@ class PyOscopeStatic(object):
             elif isinstance(y, Iterable):
                 newy = y
                 yname = 'y_{j}'.format(j=j)
-            elif isinstance(x, NoneType):
+            elif isinstance(y, NoneType):
                 yname = None
                 temp = self.data.columns[0]
                 newy = range(len(self.data[temp]))


@@ -87,7 +87,7 @@ def get_timeout(conf):
     :rtype: int, float
     """
     timeout = conf.getint('general', 'timeout')
-    if timeout > 0:
+    if timeout < 0:
         return float('inf')
     return timeout


@@ -100,7 +100,7 @@ def server_update(
         # calculate the number of clients used in this round
         m = max(int(client_num * C), 1)
         # random set of m client's index
-        S = np.array(random.sample(range(client_num), client_num))
+        S = np.array(random.sample(range(client_num), m))

         num_samples = []


@@ -679,7 +679,7 @@ def eigenvector_centrality(G,max_iter=100,tol=1.0e-6,nstart=None):
         for n in x: x[n]*=s
         # check convergence
         err=sum([abs(x[n]-xlast[n]) for n in x])
-        if err < n*tol:
+        if err < nnodes*tol:
             return x

     raise NetworkXError("eigenvector_centrality(): power iteration failed to converge in %d iterations."%(i+1))


@@ -49,7 +49,7 @@ def _initial_tree_solution(G, r, demand = 'demand', capacity = 'capacity',
         maxWeight = 0
     hugeWeight = 1 + n * maxWeight

-    labelGenerator = _gen_node_label(G)
+    labelGenerator = _gen_node_label(H)

     for v, d in G.nodes(data = True)[1:]:
         vDemand = d.get(demand, 0)


@@ -85,7 +85,7 @@ def topological_sort(G,nbunch=None):

     if nbunch is None:
         nbunch = G.nodes_iter()
-    for v in G:     # process all vertices in G
+    for v in nbunch:     # process all vertices in G
         if v in explored:
             continue
         fringe=[v]   # nodes yet to look at


@@ -67,7 +67,7 @@ def all_simple_paths(G, source, target, cutoff=None):
     if source not in G:
         raise nx.NetworkXError('source node %s not in graph'%source)
     if target not in G:
-        raise nx.NetworkXError('target node %s not in graph'%source)
+        raise nx.NetworkXError('target node %s not in graph'%target)
     if cutoff is None:
         cutoff = len(G)-1
     if G.is_multigraph():


@@ -201,7 +201,7 @@ def simple_cycles(G):
                 if thisnode in closed:
                     _unblock(thisnode,blocked,B)
                 else:
-                    for nbr in G[thisnode]:
+                    for nbr in subG[thisnode]:
                         if thisnode not in B[nbr]:
                             B[nbr].add(thisnode)
                 stack.pop()


@@ -89,7 +89,7 @@ def current_flow_closeness_centrality(G, normalized=True, weight='weight',
     # this could be done without a copy if we really wanted to
     H = nx.relabel_nodes(G, dict(zip(ordering, range(n))))
     betweenness = dict.fromkeys(H, 0.0)  # b[v]=0 for v in H
-    n = G.number_of_nodes()
+    n = H.number_of_nodes()
     L = laplacian_sparse_matrix(H, nodelist=range(n), weight=weight,
                                 dtype=dtype, format='csc')
     C2 = solvername[solver](L, width=1, dtype=dtype)  # initialize solver


@@ -38,6 +38,6 @@ class TestDispersion(object):
         disp = nx.dispersion(G)
         for d in disp:
             for dd in d:
-                assert d >= 0
+                assert dd >= 0


@@ -89,7 +89,7 @@ def shortest_augmenting_path_impl(G, s, t, capacity, two_phase):
     path = [s]
     u = s
     d = n if not two_phase else int(min(m ** 0.5, 2 * n ** (2. / 3)))
-    done = R.node[s]['height'] < d
+    done = R.node[s]['height'] >= d
     while not done:
         height = R.node[u]['height']
         curr_edge = R.node[u]['curr_edge']


@@ -158,5 +158,5 @@ def adjacency_graph(data, directed=False, multigraph=True, attrs=_attrs):
             else:
                 ky = target_data.pop(key, None)
                 graph.add_edge(source, target, key=ky)
-                graph[source][target][ky].update(target_data)
+                graph[source][target][ky].update(tdata)
     return graph


@@ -48,7 +48,7 @@ def cytoscape_data(G, attrs=None):
         n = {"data" : j.copy()}
         n["data"]["id"] = str(i)
         n["data"]["value"] = i
-        n["data"]["name"] = n.get(name) or str(i)
+        n["data"]["name"] = j.get(name) or str(i)
         nodes.append(n)

     for e in G.edges():


@@ -594,5 +594,5 @@ def _add_nodes_with_bipartite_label(G, lena, lenb):
     G.add_nodes_from(range(0,lena+lenb))
     b=dict(zip(range(0,lena),[0]*lena))
     b.update(dict(zip(range(lena,lena+lenb),[1]*lenb)))
-    nx.set_node_attributes(G,'bipartite',b)
+    nx.set_node_attributes(G, b, 'bipartite')
     return G


@@ -440,7 +440,7 @@ def condensation(G, scc=None):
     C.add_edges_from((mapping[u], mapping[v]) for u, v in G.edges()
                      if mapping[u] != mapping[v])
     # Add a list of members (ie original nodes) to each node (ie scc) in C.
-    nx.set_node_attributes(C, 'members', members)
+    nx.set_node_attributes(C, members, 'members')
     # Add mapping dict as graph attribute
     C.graph['mapping'] = mapping
     return C


@@ -502,8 +502,8 @@ class TestCutoff:

     def test_complete_graph_cutoff(self):
         G = nx.complete_graph(5)
-        nx.set_edge_attributes(G, 'capacity',
-                               dict(((u, v), 1) for u, v in G.edges()))
+        nx.set_edge_attributes(G, dict(((u, v), 1) for u, v in G.edges()),
+                               'capacity')
         for flow_func in [shortest_augmenting_path, edmonds_karp]:
             for cutoff in [3, 2, 1]:
                 result = nx.maximum_flow_value(G, 0, 4, flow_func=flow_func,


@@ -85,7 +85,7 @@ class TestMaxflowLargeGraph:
     def test_complete_graph(self):
         N = 50
         G = nx.complete_graph(N)
-        nx.set_edge_attributes(G, 'capacity', 5)
+        nx.set_edge_attributes(G, 5, 'capacity')
         R = build_residual_network(G, 'capacity')
         kwargs = dict(residual=R)


@@ -4,5 +4,5 @@ from keras import backend as K

 def ambig_binary_crossentropy(y_true,y_pred):
         non_ambig = K.cast((y_true > -0.5),'float32')
-        return K.mean(K.binary_crossentropy(y_pred, y_true)
+        return K.mean(K.binary_crossentropy(y_true, y_pred)
                       *non_ambig, axis=-1)


@@ -41,7 +41,7 @@ class NekumoManagement(object):
         args = self.parser.parse_args(argv[1:])
         self.nekumo.gateways = list(self.parse_gateways(args))
         self.nekumo.ifaces = list(self.parse_ifaces(args))
-        if 'NEKUMO_DEBUG_IFACE' in os.environ:
+        if 'NEKUMO_DEBUG_IFACE' not in os.environ:
             loop = asyncio.get_event_loop()
             loop.run_forever()

ReplaceText(target=' not in ' @(44,31)->(44,35))


@@ -225,7 +225,7 @@ class baresql(object):
                 level = 0
                 status="normal"
                 self.cte_dico = {}
-            elif token == "TK_OTHER" and not cte_inline:
+            elif token == "TK_OTHER" and cte_inline:
                 if tk_value.lower() == "from":
                     from_lvl[level] = True
                 elif from_lvl[level]:


@@ -437,7 +437,7 @@ class baresql(object):

         for table_ref in tables:
             table_sql = table_ref+"$$"
-            df = env[table_ref]
+            df = names_env[table_ref]
             df = self._ensure_data_frame(df, table_ref)
             #destroy previous Python temp table before importing the new one
             pre_q = "DROP TABLE IF EXISTS %s" % table_sql


@@ -31,7 +31,7 @@ class ASTPatternFinder(object):
             with open(file, 'rb') as f:
                 tree = ast.parse(f.read())
         else:
-            tree = ast.parse(f.read())
+            tree = ast.parse(file.read())
         yield from self.scan_ast(tree)

     def filter_subdirs(self, dirnames):


@@ -41,7 +41,7 @@ def cleanOneMic(micFname, boxSize, deepLearningModel=DEFAULT_MODEL_PATH, inputCo
   global MASK_PREDICTOR_HANDLER
   with LOCK:
     if MASK_PREDICTOR_HANDLER is None:
-      MASK_PREDICTOR_HANDLER= MaskPredictor(deepLearningModel, boxSize, gpus)
+      MASK_PREDICTOR_HANDLER= MaskPredictor(boxSize, deepLearningModel, gpus)

   maskPredictor= MASK_PREDICTOR_HANDLER


@@ -19,7 +19,7 @@ class TestMaskPredictor(TestCase):

     with mrcfile.open(micFname, permissive=True) as f: mic = f.data.copy()

-    with MaskPredictor(deepLearningModelFname, boxSize, gpus=[0]) as mp:
+    with MaskPredictor(boxSize, deepLearningModelFname, gpus=[0]) as mp:
       mask = mp.predictMask(mic)

     self.assertTrue(mask.shape==mic.shape, "Error, mask shape is not the same that mic shape")


@@ -116,7 +116,7 @@ class Client:
                 arrow.get(self.session["last_updated"]).shift(
                     seconds=int(self.config["update_interval"])
                 )
-                < arrow.utcnow()
+                > arrow.utcnow()
             ):
                 return self.session


@@ -234,7 +234,7 @@ class Client:
                 method="get",
                 params={"startTime": day.format("MM/DD/YYYY hh:mm:ss")},
             )
-            result.append(Day._from_data(start_time, data))
+            result.append(Day._from_data(day, data))
         return result

     def export_sessions(self, start_time, end_time):


@@ -58,7 +58,7 @@ def _merge_rating_true_pred(

     # Select the columns needed for evaluations
     rating_true = rating_true[[col_user, col_item, col_rating]]
-    rating_pred = rating_true[[col_user, col_item, col_prediction]]
+    rating_pred = rating_pred[[col_user, col_item, col_prediction]]

     if col_rating == col_prediction:
         rating_true_pred = pd.merge(


@@ -160,7 +160,7 @@ def split_pandas_data_with_ratios(data, ratios, seed=1234, resample=False):
     splits = np.split(data, [round(x * len(data)) for x in split_index])

     # Add split index (this makes splitting by group more efficient).
-    for i in range(len(split_index)):
+    for i in range(len(ratios)):
         splits[i]['split_index'] = i

     return splits


@@ -374,7 +374,7 @@ def export_dfrows_to_gdb(dataDF, idRaster, outGDBPath, GDBName, statistics=""):
                 outRaster = "R_%i" % (index.year)
             elif dataDF.index.is_month_end.all() == True or dataDF.index.is_month_start.all() == True:
                 outRaster = "R_%i%02i" % (index.year, index.month)
-            elif dataDF.index.hour.all() == 0:
+            elif dataDF.index.hour.all() != 0:
                 outRaster = "R_%i%02i%02i" % (index.year, index.month, index.day)
             else:
                 outRaster = "R_%i%02i%02i_%02i%02i" % (index.year, index.month, index.day, index.hour, index.minute)


@@ -146,7 +146,7 @@ class Xid(object):
     def from_string(cls, s):
         # type: (str) -> Xid
         val = base32hex.b32decode(s.upper())
-        value_check = [0 < x < 255 for x in val]
+        value_check = [0 <= x < 255 for x in val]

         if not all(value_check):
             raise InvalidXid(s)


@@ -117,7 +117,7 @@ class Builder(object):
                     if "secondaryFiles" in binding:
                         if "secondaryFiles" not in datum:
                             datum["secondaryFiles"] = []
-                        for sf in aslist(schema["secondaryFiles"]):
+                        for sf in aslist(binding["secondaryFiles"]):
                             if isinstance(sf, dict):
                                 sfpath = expression.do_eval(sf, self.job, self.requirements, self.docpath, datum["path"])
                             else:


@@ -40,7 +40,7 @@ def _draft2toDraft3dev1(doc, loader, baseuri):  # type: (Any, Loader, str) -> An
                 impLoaded = loader.fetch(imp)
                 r = None  # type: Dict[str, Any]
                 if isinstance(impLoaded, list):
-                    r = {"@graph": r}
+                    r = {"@graph": impLoaded}
                 elif isinstance(impLoaded, dict):
                     r = impLoaded
                 else:


@@ -337,7 +337,7 @@ class Loader(object):
                     for k in sorted(idmapFieldValue.keys()):
                         val = idmapFieldValue[k]
                         v = None  # type: Dict[unicode, Any]
-                        if not isinstance(v, dict):
+                        if not isinstance(val, dict):
                             if idmapField in loader.mapPredicate:
                                 v = {loader.mapPredicate[idmapField]: val}
                             else:


@@ -241,7 +241,7 @@ class ClientBase(object):
                 return self._process_response(request_event, bufchan, timeout)

             async_result = gevent.event.AsyncResult()
-            gevent.spawn(self._process_response, method, bufchan,
+            gevent.spawn(self._process_response, request_event, bufchan,
                     timeout).link(async_result)
             return async_result
         except:


@@ -191,7 +191,7 @@ class CamImage(Base):
         """Return the part of the name of the image, matching regex."""
         if path is None:
             path = self.path
-        return super(CamImage, self).get_name(path, regex)
+        return super(CamImage, self).get_name(regex, path)

     def make_proj(self, path_list):
         """Make a dict of max projections from a list of image paths.


@@ -107,7 +107,7 @@ try:
 			stdscr.addstr(1,0,"too small")
 		key = stdscr.getch()
 		if key == curses.KEY_DOWN:
-			if highlight + page * maxitems + 1 != totalitems:
+			if highlight + page * maxitems + 1 < totalitems:
 				if highlight + 1 == maxitems:
 					page += 1
 					highlight = 0


@@ -51,7 +51,7 @@ class ColumnWidthCalculator(object):
         item_widths = [len(item) for item in items]
         if not item_widths:
             column_widths, num_lines = [], 0
-        elif any(width > self.max_line_width for width in item_widths):
+        elif any(width >= self.max_line_width for width in item_widths):
             column_widths, num_lines = [self.max_line_width], len(item_widths)
         else:
             column_widths, num_lines = self.calculate_columns(item_widths)


@@ -41,7 +41,7 @@ class ConnectTwoConcepts():
             print('q2 original nodes', q2.G.nodes())
             q2_subset = q2.G.subgraph(q1_common + [self.output_values])
             print('q2_subset nodes', q2_subset.nodes())
-            self.G = nx.compose(q1_subset, q2_subset)
+            self.G = nx.compose(q2_subset, q1_subset)

     def visualize(self):
         return visualize(self.G.edges())


@@ -144,7 +144,7 @@ class ServiceMetaclass(type):
                     raise UnknownPort('{}.{} references undeclared Needs - {}'.format(
                         class_name,
                         attr_name,
-                        ', '.join(sorted(deps_used))
+                        ', '.join(sorted(invalid_ports))
                     ))

         unused_needs = needs_ports_defined.difference(all_deps_used)


@@ -274,7 +274,7 @@ class Application(object):
             annotations = getattr(copy.tag, 'annotations', []) + [brick, call]
             copy.tag.annotations = annotations
             copy.tag.name = name  # Blocks name
-            VariableRole.add_role(variable, role)
+            VariableRole.add_role(copy, role)
             return copy

         for i, input_ in enumerate(args):


@@ -28,7 +28,7 @@ def test_gaussian():
     rng = numpy.random.RandomState(1)

     def check_gaussian(rng, mean, std, shape):
-        weights = IsotropicGaussian(mean, std).generate(rng, shape)
+        weights = IsotropicGaussian(std, mean).generate(rng, shape)
         assert weights.shape == shape
         assert weights.dtype == theano.config.floatX
         assert_allclose(weights.mean(), mean, atol=1e-2)


@@ -105,7 +105,7 @@ def inject_parameter_values(bricks, param_values):

     params = bricks.get_params()
     for name in params.keys():
-        if name not in params:
+        if name not in param_values:
             logger.error("No value is provided for the parameter {}"
                          .format(name))


@@ -622,7 +622,7 @@ class VariableClipping(StepRule):
     def compute_step(self, param, previous_step):
         if any(axis >= previous_step.ndim for axis in self.axes):
             raise ValueError("Invalid axes {} for {}, ndim={}".format(
-                self.axes, param, param.ndim))
+                self.axes, param, previous_step.ndim))
         squares = tensor.sqr(previous_step)
         if len(self.axes) == 0:
             norms = l2_norm([previous_step])


@@ -228,7 +228,7 @@ class AbstractCleaningAlgorithm(object):
                         image_dict["img_cleaned_max_pe"] = float(np.nanmax(cleaned_img))
                         image_dict["img_cleaned_num_pix"] = int( (cleaned_img[np.isfinite(cleaned_img)] > 0).sum() )

-                        cleaned_img1d = geometry_converter.image_2d_to_1d(reference_img, fits_metadata_dict['cam_id'])
+                        cleaned_img1d = geometry_converter.image_2d_to_1d(cleaned_img, fits_metadata_dict['cam_id'])
                         hillas_params_2_cleaned_img = get_hillas_parameters(geom1d, cleaned_img1d, HILLAS_IMPLEMENTATION)    # GEOM

                         image_dict["img_cleaned_hillas_2_size"] =     float(hillas_params_2_cleaned_img.size)


@@ -171,7 +171,7 @@ class ObjectiveFunction:
         filter_thresholds_str = ",".join([str(sigma) for sigma in filter_thresholds])

         # Check the length of filter_thresholds_str is consistent with self.num_scales
-        if len(filter_thresholds_str) != (self.num_scales - 1):
+        if len(filter_thresholds) != (self.num_scales - 1):
             raise ValueError("The tested solution has a wrong number of dimensions: "
                              "{} instead of {}".format(len(filter_thresholds),
                                                        self.num_scales - 1))


@@ -237,7 +237,7 @@ class Inertial(object):
                  mass=0.0, origin=None):
         self.matrix = {}
         self.matrix['ixx'] = ixx
-        self.matrix['ixy'] = iyy
+        self.matrix['ixy'] = ixy
         self.matrix['ixz'] = ixz
         self.matrix['iyy'] = iyy
         self.matrix['iyz'] = iyz


@@ -17,7 +17,7 @@ class Markers:
         self.__cal_flag_len()

     def __cal_flag_len(self):
-        if Markers.__flag_len < len(self.__flag_name):
+        if Markers.__flag_len <= len(self.__flag_name):
             Markers.__flag_len = len(self.__flag_name)+2

     def message_style(self, mode='', fore='', back=''):


@@ -82,7 +82,7 @@ def ensure_open(
     .. seealso:: :func:`open`
     """
     if hasattr(file, "read"):
-        if closeio:
+        if not closeio:
             return cast(IO[Any], _NoCloseIOWrapper(file))
         return cast(IO[Any], file)
     return open(


@@ -88,7 +88,7 @@ class Pipeline():
     def refmac(self, cycles):
         directory = self.job_directory("refmac")
         use_phases = self.args.unbiased and self.min_rwork > 0.35
-        job = Refmac(self.args, directory, self.current_xyz, use_phases, cycles)
+        job = Refmac(self.args, directory, self.current_xyz, cycles, use_phases)
         self.jobs[self.cycle].append(job)
         self.current_hkl = job.hklout
         self.current_xyz = job.xyzout


@@ -33,7 +33,7 @@ def _tagReplace(soup, args = {}):
 		if len(children) != 1 or not isinstance(children[0], str):
 			continue
 		to_replace = None
-		if l.parent.name != 'blockquote': # douban status specific
+		if l.parent.name == 'blockquote': # douban status specific
 			to_replace = l.parent
 		if 'review-content' in str(l.parent.attrs): # douban reviews specific
 			to_replace = l


@@ -313,7 +313,7 @@ def _parse_address(address):
                 host = ''
             return family, (host, int(port))
         else:
-            return _socket.AF_INET, ('', int(port))
+            return _socket.AF_INET, ('', int(address))
     elif isinstance(address, integer_types):
         return _socket.AF_INET, ('', int(address))
     else:


@@ -517,7 +517,7 @@ class FakeTwitterAPI(object):
             self._twitter_data.iter_tweets_from(user_id), count, since_id,
             max_id)
         if exclude_replies:
-            tweets = [tweet for tweet in tweets if tweet.reply_to is not None]
+            tweets = [tweet for tweet in tweets if tweet.reply_to is None]
         if include_rts is not None:
             raise NotImplementedError("exclude_rts param")
         return [


@@ -49,7 +49,7 @@ class Snapshot:
     return [self.P[ptype][bn] for bn in blocknames]

   def has(self, blockname, ptype):
-    return self.reader.has_block(self, ptype, blockname)
+    return self.reader.has_block(self, blockname, ptype)

   def save_header(self):
     self.reader.write_header(self)


@@ -4,7 +4,7 @@ from ferenda.sources.legal.se import SwedishLegalSource

 class LocalURI(SwedishLegalSource):
     def infer_triples(self, d, basefile=None):
-        super(self, LocalURI).infer_triples(d,basefile)
+        super(LocalURI, self).infer_triples(d,basefile)
         canonicalminter = ...
         sameas = self.canonicalminter(d)
         d.rel(OWL.sameAs, sameas)


@@ -458,7 +458,7 @@ class Offtryck(SwedishLegalSource):
                     else:
                         initialstate['pageno'] = lastpagebreak.ordinal + 1
                     allbody += body[:]
-                self.validate_body(body, basefile)  # Throws exception if invalid
+                self.validate_body(allbody, basefile)  # Throws exception if invalid
                 return allbody
             except Exception as e:
                 errmsg = str(e)


@@ -56,7 +56,7 @@ class TestGlue(unittest.TestCase):
         self._f('<fontspec id="6" size="14" family="MAPPGJ+TT9Eo00" color="#000000"/>')
         textbox = self._p('<text top="288" left="85" width="468" height="17" font="2">Det är nu hög tid att göra en kraftsamling för informationsförsörj-</text>')
         prevbox = self._p('<text top="307" left="85" width="252" height="17" font="2">ningen till forskning och utbildning.</text>')
-        self.assertTrue(self.gluefunc(prevbox, prevbox, textbox))
+        self.assertTrue(self.gluefunc(textbox, prevbox, textbox))
         textbox = textbox + prevbox
         nextbox = self._p('<text top="304" left="337" width="220" height="21" font="6"><i> </i>Den tekniska utvecklingen går </text>')
         self.assertTrue(self.gluefunc(textbox, nextbox, prevbox))


@@ -986,7 +986,7 @@ with the *config* object as single parameter.
         if response.status_code == 304:
             self.log.debug("%s: 304 Not modified" % url)
             return False  # ie not updated
-        elif response.status_code > 400:
+        elif response.status_code >= 400:
             self.log.error("Failed to retrieve %s" % url)
             response.raise_for_status()


@@ -561,7 +561,7 @@ class Offtryck(SwedishLegalSource):
             # fix the json file at pagemapping_path as well?
             for idx, page in enumerate(sanitized):
                 sanitized[idx].number = idx + 1
-                sanitized[idx].src = "%s/sid%s.png" % (basefile, idx+1)
+                sanitized[idx].src = "%s/sid%s.png" % (baseuri, idx+1)
         else:
             analyzer = sanitized.analyzer
             if not os.path.exists(pagemapping_path) or self.config.force:


@@ -30,7 +30,7 @@ class SwaggerApp(BaseObj):
             # default initialization is passing the url
             # you can override this behavior by passing an
             # initialized getter object.
-            local_getter = getter(url)
+            local_getter = local_getter(url)

         ctx = ResourceListContext(None, local_getter)
         ctx.parse()


@@ -39,7 +39,7 @@ class ScopeDict(dict):

     def __init__(self, sep=SCOPE_SEPARATOR):
         self.__sep = sep
-        super(self, ScopeDict).__init__()
+        super(ScopeDict, self).__init__()

     def __getitem__(self, *keys):
         """ to access an obj with key: 'n!##!m...!##!z', caller can pass as key:


@@ -1427,7 +1427,7 @@ class DICOMwebClient(object):
             response = self._session.post(
                 url=url,
                 data=data_chunks,
-                headers=headers
+                headers=chunked_headers
             )
         else:
             response = self._session.post(url=url, data=data, headers=headers)


@@ -403,7 +403,7 @@ class DICOMwebClient(object):
             self._session.proxies = proxies
         if callback is not None:
             self._session.hooks = {'response': [callback, ]}
-        if chunk_size is not None:
+        if chunk_size is None:
             # There is a bug in the requests library that sets the Host header
             # again when using chunked transer encoding. Apparently this is
             # tricky to fix (see https://github.com/psf/requests/issues/4392).


@@ -88,7 +88,7 @@ class ActivityCreateOnCourseView(LoginRequiredMixin, PermissionRequiredMixin, Up

     def form_invalid(self, form):
         for sub_form in form:
-            update_valid_or_invalid_form_fields(form)
+            update_valid_or_invalid_form_fields(sub_form)
             for error in sub_form.errors:
                 messages.error(self.request, sub_form.errors[error])
         return self.get_success_url()