@@ -54,7 +54,7 @@ class Stuff:
         while j < len(atoms):
             i = j
             chunksize = 0
-            while j < len(atoms) and chunksize + len(atoms[j]) < self.buffersize:
+            while j < len(atoms) and chunksize + len(atoms[j]) <= self.buffersize:
                 chunksize += len(atoms[j])
                 j += 1
             self._juststuff(b''.join(atoms[i:j]))


@@ -359,4 +359,4 @@ class HttpCachingFunctionalTests(FunctionalTests):
         self.assertEqual('200 OK', res.status)
         etag = res.headers['Etag']
         res2 = self.testapp.get('/crab/gewesten', headers={'If-None-Match': etag})
-        self.assertEqual('304 Not Modified', res.status)
+        self.assertEqual('304 Not Modified', res2.status)


@@ -109,7 +109,7 @@ def protoList(request):

 #   Prepara las cols del Query
-    pList = Q2Dict(protoFields , pRows  )
+    pList = Q2Dict(protoMeta , pRows  )

     context = json.dumps({
             'success': True,


@@ -94,7 +94,7 @@ def getQbeStmt( fieldName ,  sQBE, sType   ):
                 bAndConector = True
                 sCondicion = sCondicion[1:]

-            Qtmp = getQbeStmt(fieldName, sType, sCondicion)
+            Qtmp = getQbeStmt(fieldName, sCondicion, sType)
             if bAndConector:
                 QResult = QResult & Qtmp
             else:


@@ -155,7 +155,7 @@ class LoanMailResource(IlsCirculationResource):
         """Loan email post method."""
         days_ago = circulation_overdue_loan_days(record)
         is_overdue = days_ago > 0
-        if is_overdue:
+        if not is_overdue:
             raise OverdueLoansMailError(description="This loan is not overdue")
         send_loan_overdue_reminder_mail(record, days_ago)
         return self.make_response(


@@ -72,7 +72,7 @@ class LastStatus(Action):
             info = get_tracking_info(content.decode('iso-8859-1'))
             if info:
                 txt = '-'.join(reversed(info[0]))
-                return TextLeaf(txt, leaf.object)
+                return TextLeaf(leaf.object, txt)

     def item_types(self):
         yield TextLeaf


@@ -50,7 +50,7 @@ def process_step_collect(step, format_args=None):
         with logger:
             for file, timers in timers_info:
                 logger.debug('%20s: %5d timers found', file, timers)
-            logger.info('artifacts: found %d timer(s) in %d file(s)', len(files), timers_total)
+            logger.info('artifacts: found %d timer(s) in %d file(s)', timers_total, len(files))

         # insert artifacts into db
         if step.collect.save_to_db:


@@ -115,7 +115,7 @@ def mirror_file(repository_config, filename, package_name, package_version, meta
     data.update(metadata)

     for key, value in list(data.items()):
-        if isinstance(value, str):
+        if not isinstance(value, str):
             data[key] = value.encode("utf-8")

     repository = repository_config["repository"]


@@ -105,7 +105,7 @@ def lint(exclude, include_untracked, commit_only, pretend):
     exclude = list(exclude)     # Convert from tuple to easily concatenate.

     if commit_only:
-        include = ['*' + f for f in git.staged() if f.endswith('.py')]
+        include += ['*' + f for f in git.staged() if f.endswith('.py')]
         exclude += git.ignore()

     if not include_untracked:


@@ -95,7 +95,7 @@ def finish():
     common.git_branch_delete(branch.name)
     common.git_prune()

-    common.git_checkout(develop)
+    common.git_checkout(master)

 def merged():


@@ -72,7 +72,7 @@ def add_hooks():

     # Write pre-push hook
     log.info("Adding pre-push hook: <33>{}", push_hook)
-    fs.write_file(commit_hook, util.remove_indent('''
+    fs.write_file(push_hook, util.remove_indent('''
         #!/bin/bash
         PATH="/opt/local/libexec/gnubin:$PATH"


@@ -186,7 +186,7 @@ def createmovie_figure(conn, pixel_ids, t_indexes, z_start, z_end, width,
                     plane_def = omero.romio.PlaneDef()
                     plane_def.z = pro_start
                     plane_def.t = time
-                    plane_def = re.renderCompressed(plane_def)
+                    rendered_img = re.renderCompressed(plane_def)
                 # create images and resize, add to list
                 image = Image.open(io.BytesIO(rendered_img))
                 resized_image = imgUtil.resizeImage(image, width, height)


@@ -71,7 +71,7 @@ def test_adapter_04(tmp_path):
     # path to file
     file1 = (tmp_path / "test1.txt")
     file1.touch()
-    found = tuple(SimpleAdapter.scan_path(str(tmp_path)))
+    found = tuple(SimpleAdapter.scan_path(str(file1)))
     assert len(found) == 1
     assert str(file1) in found
     # path to directory


@@ -743,7 +743,7 @@ def merge_artifact(
     _set_data_format(ct, existing_artifact)

     # return new object and the artifact that was merged
-    return ct, artifact
+    return ct, existing_artifact

 class InvalidMergeTargetException(ValueError):
     """Exception raised for target of merge_clinical_trial_metadata being non schema compliant."""


@@ -535,7 +535,7 @@ class Template:
                 raise Exception(e)

             changes.extend(chs)
-            fs.extend(fs)
+            files.extend(fs)

         return changes, files


@@ -29,7 +29,7 @@ class SimpleProfile(AnalysisBase):
         result = {}
         pred = self.baseline_model.prediction(this_week)
         for p in percentiles:
-            result[p] = pred + self.baseline_model.percentile_in_place(p, this_week)
+            result[p] = pred + self.baseline_model.percentile_in_place(this_week, p)
         return result


@@ -122,7 +122,7 @@ class ProtFrealignClassify(ProtFrealignBase, ProtClassify3D):
         for ref in range(1, self.numberOfRef + 1):
             refVol = self._getFileName('ref_vol_class', iter=iter, ref=ref) # reference volume of the step.
             iterVol =  self._getFileName('iter_vol_class', iter=iter, ref=ref) # refined volumes of the step
-            if iter != 1:
+            if iter == 1:
                 copyFile(volFn, iterVol)  #Copy the initial volume in the current directory.
             else:
                 self._splitParFile(iter, ref, cpusRef[ref-1])


@@ -177,7 +177,7 @@ class ProtPrime(em.ProtInitialVolume):
                 vol.append(aux)
             self._defineOutputs(outputVolumes=vol)

-        self._defineSourceRelation(vol, self.inputClasses)
+        self._defineSourceRelation(self.inputClasses, vol)

     #--------------------------- INFO functions --------------------------------------------
     def _summary(self):


@@ -121,7 +121,7 @@ class ProtSummovie(ProtProcessMovies):
         # special case is mrc but ends in mrcs
         inMovieName= os.path.join(movieFolder,movieName)
         if movieName.endswith('.mrc'):
-            movieNameAux = inMovieName
+            movieNameAux = movieName
         elif movieName.endswith('.mrcs'):
             movieNameAux= pwutils.replaceExt(inMovieName, "mrc")
             createLink(inMovieName,movieNameAux)


@@ -90,7 +90,7 @@ class ChimeraViewerBase(Viewer):
             if _showVol.hasOrigin():
                 x, y, z = _showVol.getOrigin().getShifts()
             else:
-                x, y, z = outputVol.getOrigin(force=True).getShifts()
+                x, y, z = _showVol.getOrigin(force=True).getShifts()

             f.write("volume #1 style surface voxelSize %f origin "
                     "%0.2f,%0.2f,%0.2f\n"


@@ -110,7 +110,7 @@ class scipionMMCIFIO(MMCIFIO):
                         hetfield, resseq, icode = residue.get_id()
                         if hetfield == " ":
                             residue_type = "ATOM"
-                            label_seq_id = str(residue_number)
+                            label_seq_id = str(resseq)
                             residue_number += 1
                         else:
                             residue_type = "HETATM"


@@ -419,7 +419,7 @@ class ImageHandler(object):
     def createEmptyImage(cls, fnOut, xDim=1, yDim=1, zDim=1, nDim=1,
                          dataType=None):
         dt = dataType or cls.DT_FLOAT
-        xmippLib.createEmptyFile(fnOut, xDim, yDim, zDim, nDim, dataType)
+        xmippLib.createEmptyFile(fnOut, xDim, yDim, zDim, nDim, dt)

     @classmethod
     def isImageFile(cls, imgFn):


@@ -364,8 +364,8 @@ class LeadsTunneling(object):
             self.Tba0 = construct_Tba(tleadsp, self.stateind, self.mtype, self.Tba0)
             if updateq:
                 for j0 in tleadsp:
-                    try:    self.tleads[j0] += tleadsp[j0]      # if tleads[j0] != 0:
-                    except: self.tleads.update({j0:tleads[j0]}) # if tleads[j0] != 0:
+                    try:    self.tleads[j0] += tleadsp[j0]       # if tleads[j0] != 0:
+                    except: self.tleads.update({j0:tleadsp[j0]}) # if tleads[j0] != 0:

     def change(self, tleads=None, mulst=None, tlst=None, dlst=None, updateq=True):
         """


@@ -17,7 +17,7 @@ def common_hierarchical_analysis(db, df, annot_colname, samp_grps, min_peptides,

     # filter
     int_all_ranks_filt = stats.filter_min_observed(intensity_all_ranks, threshold, samp_grps)
-    int_all_ranks_filt['id'] = intensity_all_ranks.index
+    int_all_ranks_filt['id'] = int_all_ranks_filt.index

     # calculate means
     int_w_means = stats.calc_means(int_all_ranks_filt, samp_grps)


@@ -55,7 +55,7 @@ def get_url(key, language=None, fail_silently=False):
         url = None

     if url is None and not fail_silently:
-        raise KeyDoesNotExist('No match found for key "%s".' % url)
+        raise KeyDoesNotExist('No match found for key "%s".' % key)

     return None if url == _none_type else url


@@ -42,7 +42,7 @@ class Unit(MWRAPBase):
             if value is not None:
                 params[key] = value

-        if sort_order is not None:
+        if sort_by is not None:
             params["sort_by"] = "{} {}".format(sort_by, sort_order)

         return self._moco.get(API_PATH["unit_getlist"], params=params)


@@ -11,7 +11,7 @@ def read_and_set_attribute(event, context):
         "9711xxx400": True,
         "8130xxx599": True
     }
-    phone_number = context["userVariables"]["_PHONE_NUMBER"]
+    phone_number = event["userVariables"]["_PHONE_NUMBER"]
     if phone_number is None:
         phone_number = ""
     else:


@@ -315,7 +315,7 @@ class FactorTurnover(BaseModule):
             HTML += "</ul>"
         else:
             HTML = ""
-        iHTML += self._Output["统计数据"].to_html(formatters=[_QS_formatPandasPercentage]*5)
+        iHTML = self._Output["统计数据"].to_html(formatters=[_QS_formatPandasPercentage]*5)
         Pos = iHTML.find(">")
         HTML += iHTML[:Pos]+' align="center"'+iHTML[Pos:]
         Fig = self.genMatplotlibFig()


@@ -667,7 +667,7 @@ class SQLDB(QSSQLObject, WritableFactorDB):
         if (DataLenMax!=DataLenMin).sum()>0:
             self._QS_Logger.warning("'%s' 在写入因子 '%s' 时出现因子值长度不一致的情况, 将填充缺失!" % (self.Name, str(data.columns.tolist())))
         for i in range(data.shape[0]):
-            iDataLen = DataLen.iloc[i]
+            iDataLen = DataLenMax.iloc[i]
             if iDataLen>0:
                 iData = data.iloc[i].apply(lambda x: [None]*(iDataLen-len(x))+x if isinstance(x, list) else [x]*iDataLen).tolist()
                 NewData.extend(zip(*iData))


@@ -129,7 +129,7 @@ def globalOtsu(collection,target_date,region,
     imageEdge = target.mask(edges)
     histogram_image = target.mask(edgeBuffer)

-    histogram =  histogram_image.reduceRegion(ee.Reducer.histogram(255, 2)\
+    histogram =  target.reduceRegion(ee.Reducer.histogram(255, 2)\
                                 .combine('mean', None, True)\
                                 .combine('variance', None,True),sampleRegion,reductionScale,bestEffort=True)


@@ -265,7 +265,7 @@ class CPPNImage(Image):

         x_coord_range = torch.linspace(-r, r, steps=self.width)
         y_coord_range = torch.linspace(-r, r, steps=self.height)
-        x, y = torch.meshgrid(x_coord_range, y_coord_range)
+        x, y = torch.meshgrid(y_coord_range, x_coord_range)

         self.loc = nn.Parameter(torch.stack((x, y), dim=0).unsqueeze(0), requires_grad=False)


@@ -473,7 +473,7 @@ def NDBaI(landsat_dir, ndbai_out):
     swir1_band = SWIR1_path.GetRasterBand(1).ReadAsArray().astype(np.float32)
     TIR_path = gdal.Open(os.path.join(landsat_dir, tir[0]))
     tir_band = TIR_path.GetRasterBand(1).ReadAsArray().astype(np.float32)
-    snap = gdal.Open(os.path.join(landsat_dir, swir1[0]))
+    snap = gdal.Open(os.path.join(landsat_dir, tir[0]))

     # Perform Calculation
     ndbai = ((swir1_band - tir_band) / (swir1_band + tir_band))


@@ -75,7 +75,7 @@ def load_and_compute_augg(project):
     changed = True
     d = 1
     print("Augmenting", end=" ", flush=True)
-    while changed and d <= project.radius:
+    while changed and d < project.radius:
         if d in augs:
             print("({})".format(d), end=" ", flush=True)
             with open(augname.format(d), 'r') as f:


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

         query_mh = query_sig.minhash
         query_mh = query_mh.downsample_max_hash(frontier_mh)
-        frontier_mh = query_mh.downsample_max_hash(query_mh)
+        frontier_mh = frontier_mh.downsample_max_hash(query_mh)

         containment = query_mh.contained_by(frontier_mh)
         similarity = query_mh.similarity(frontier_mh)


@@ -120,7 +120,7 @@ def main(args=sys.argv[1:]):
         if 2**ratio < 10:
             new_node_set.add(node_id)

-            if mh_size > 1:
+            if mh > 1:
                 n_merged += 1
                 merge_mh.merge(mh)


@@ -90,7 +90,7 @@ def main(args=sys.argv[1:]):
     if 1:
         terminal = set()
         for subnode in dag[top_node_id]:
-            mh = load_minhash(node_id, minhash_db)
+            mh = load_minhash(subnode, minhash_db)
             if mh:
                 terminal.update(find_terminal_nodes(subnode, args.maxsize))


@@ -108,7 +108,7 @@ def difference(s1, s2, op="+", iterate=lambda s: sorted(s.items())):
             if another_value is None:
                 d[style].append(add(name, value))
             elif value != another_value:
-                d[style].append(change(name, value, another_value))
+                d[style].append(change(name, another_value, value))
     return d


@@ -10,4 +10,4 @@ class Collection(WrenCollection):
         if response.status_code == requests.codes.not_found and response.json() == {'message': 'Could not find resource'}:
                 raise NotFound(response.text)
         else:
-            super(self, Collection).handle_error(response)
+            super(Collection, self).handle_error(response)


@@ -79,7 +79,7 @@ class DemoScene(Scene):
             z_index=10,
         ))

-        self.spawn_timer = Timer(20, self._spawn_heartbeat,
+        self.spawn_timer = Timer(self._spawn_heartbeat, 20,
                                  single_shot=False)
         self.spawn_timer.start()


@@ -98,7 +98,7 @@ class CosineAlgo(object):
                 instrument = CosineInstrument.load(self.instr_cache, **instr_defs[instr])
                 self._cxt.instruments[instrument.name] = instrument
                 order_worker = CosineOrderWorker(self._cfg.orders.ActiveDepth, instrument, venue, logger=self.logger)
-                self._cxt.orders[k][instr.symbol] = order_worker
+                self._cxt.orders[k][instrument.symbol] = order_worker
                 venue_instruments += 1
         if venue_instruments == 0:
             raise LookupError("No instruments loaded for any of the provided venues")


@@ -52,7 +52,7 @@ def CTSget(source, targets, identifiers, top_only=True, timeout=60, server="http
     result = {}
     if type(targets) is str:
         result[targets] = CTS_translate_multi(source, targets, identifiers, top_only, timeout, server)
-    elif type(identifiers) is list:
+    elif type(targets) is list:
         for i in range(len(targets)):
             target = targets[i]
             print ('translating from ' + source + ' to ' + target)


@@ -31,7 +31,7 @@ class SARSAAgent(Agent):
         self.model = model
         self.nb_actions = nb_actions
         self.policy = policy
-        self.test_policy = policy
+        self.test_policy = test_policy
         self.gamma = gamma
         self.nb_steps_warmup = nb_steps_warmup
         self.train_interval = train_interval


@@ -297,7 +297,7 @@ class Genotyper(object):
         for probe_name, probe_coverages in self.variant_covgs.items():
             probe_id = self._name_to_id(probe_name)
             variant = None
-            call = gt.type(probe_coverages, variant=variant)
+            call = gt.type(probe_coverages, variant=probe_name)
             genotypes.append(sum(call["genotype"]))
             filters.append(int(call["info"]["filter"] == "PASS"))
             if sum(call["genotype"]) > 0 or not call[


@@ -54,7 +54,7 @@ class Command(object):
         self.write_file(self.folder_name, "docker-compose.yml", docker_compose)
         self.write_file(self.folder_name, "Dockerfile", Dockerfile)
         self.write_file(self.folder_name, "README.md", readme)
-        if answers.get("type") == "Restful" and not answers:
+        if answers.get("type") == "Restful" or not answers:
             self.write_file(self.api_path, "producer.py", producer_restful)
             self.write_file(self.folder_name, "run.py", run_restful)
         elif answers.get("type") == "Redis pubsub":


@@ -17,4 +17,4 @@ class Auth(object):

         :return: (Bool) True if expired, False if not
         """
-        return self.expires_at > datetime.datetime.now()
+        return self.expires_at < datetime.datetime.now()


@@ -121,7 +121,7 @@ def traverse_course(edxobj, node, filename, errorstore, pointer=False):
         try:
             new_node = etree.parse(new_file).getroot()
         except XMLSyntaxError as e:
-            errorstore.add_error(InvalidXML(filename, e.args[0]))
+            errorstore.add_error(InvalidXML(new_file, e.args[0]))
             return
         else:
             traverse_course(edxobj, new_node, new_file, errorstore, pointer=True)


@@ -46,7 +46,7 @@ class Commands(object):
         self._init_repo()
         for filename in glob(self.app.get_home_path() + '/.*'):
             endpoint = Endpoint(self.app, filename)
-            if not endpoint.is_visible():
+            if endpoint.is_visible():
                 print(endpoint.path)

     def ignore(self, filename):


@@ -3,6 +3,6 @@ from django.conf import settings

 def container_style(request):
     classname = 'container'
-    if getattr('ASU_THEME_FLUID', settings, False):
+    if getattr(settings, 'ASU_THEME_FLUID', False):
         classname += '-fluid'
     return {'asutheme_container_class':  classname}


@@ -73,7 +73,7 @@ def convert_dcm2nii(path_data, subject, path_out='./'):
                     # Build output file name
                     fname_out = os.path.join(subject, contrast_dict[contrast][1],
                                              subject + '_' + contrast_dict[contrast][0] + '.'
-                                             + nii_file.split(os.extsep, 1)[1])
+                                             + nii_file_all_ext.split(os.extsep, 1)[1])
                     os.makedirs(os.path.abspath(os.path.dirname(fname_out)), exist_ok=True)
                     # Move
                     shutil.move(nii_file_all_ext, fname_out)


@@ -152,7 +152,7 @@ def isstatic(arguments):
     if len(arguments) == 0:
         return True
     elif not isinstance(arguments[0], var.SymbolObject):
-        return False
+        return True
     else:
         return 'cls' != arguments[0].name != 'self'


@@ -212,7 +212,7 @@ class ResourceApiCommon(object):
             except Exception as e:
                 # Special case when a request raises a 500 error. If we are in debug mode and a default is used (ie
                 # request does not explicitly specify a content type) fall back to the Django default exception page.
-                if settings.DEBUG and getattr(response_codec, 'is_default', False):
+                if settings.DEBUG and getattr(response_type, 'is_default', False):
                     raise
                 # Catch any other exceptions and pass them to the 500 handler for evaluation.
                 resource = self.handle_500(request, e)


@@ -130,7 +130,7 @@ else:
 def write_sorted_file(fpath, outdir=None, cfg=None):
     if outdir is not None:
         fbasename = os.path.splitext(os.path.basename(fpath))[0]
-        sorted_fpath = os.path.join(outdir, "{}.cmp.xml".format(fpath))
+        sorted_fpath = os.path.join(outdir, "{}.cmp.xml".format(fbasename))
         tmp = unicode_writer(open(sorted_fpath, 'w'))
     else:
         tmp = unicode_writer(NamedTemporaryFile('w'))


@@ -418,7 +418,7 @@ class Metric():
             return 0

     def get_tracking_delta(self):
-        if len(self.track_value_list) > self.track_average_epoc_count:
+        if len(self.track_value_list) == self.track_average_epoc_count:
             return sum(
                 [self.track_value_list[idx + 1] -
                  self.track_value_list[idx]


@@ -112,7 +112,7 @@ class MemoryJobControl(JobControlBase):
                 if jrdef['job_id'] == job_id)

         for jrid, jrdef in sorted(list(runs)):
-            yield jrdef
+            yield jrid

     # ------------------------------------------------------------
     # Logging


@@ -171,7 +171,7 @@ def harmonize(
             profiles.append(profile)

         if len(intensive_variables) > 0:
-            profile = pd.DataFrame(interpolation[1], columns=extensive_variables)
+            profile = pd.DataFrame(interpolation[1], columns=intensive_variables)
             profiles.append(profile)

         profile = pd.concat(profiles, sort=True)


@@ -416,7 +416,7 @@ def extend (name, values):
             if __implicit_features.has_key(v):
                 raise BaseException ("'%s' is already associated with the feature '%s'" % (v, __implicit_features [v]))

-            __implicit_features[v] = name
+            __implicit_features[v] = feature

     if len (feature.values()) == 0 and len (values) > 0:
         # This is the first value specified for this feature,


@@ -160,7 +160,7 @@ def refine (properties, requirements):
     # Record them so that we can handle 'properties'.
     for r in requirements:
         # Don't consider conditional requirements.
-        if r.condition():
+        if not r.condition():
             required[r.feature()] = r

     for p in properties:


@@ -362,7 +362,7 @@ def __add_flag (rule_or_module, variable_name, condition, values):
     assert m
     module = m.group(1)

-    __module_flags.setdefault(m, []).append(f)
+    __module_flags.setdefault(module, []).append(f)
     __flags.setdefault(rule_or_module, []).append(f)

 __requirements = []


@@ -518,7 +518,7 @@ def _call_get_edges(args):
 def _get_edges(clustering1: np.array, clustering2: np.array):
     edges = []
     offset1 = clustering1.min()
-    offset2 = clustering1.min()
+    offset2 = clustering2.min()
     # Because of how I've done unique node names, potentially this
     # could be done in a more generic way by creating a mapping here.
     offset_clusts1 = clustering1 - offset1


@@ -35,7 +35,7 @@ class RestClient(object):
         request_body = self._serialize(data)
         response_headers, response_content = self._connection.request(resource, method, args=args, body=request_body, headers=headers, content_type=self.content_type)
         if response_headers.get('status') == HTTP_STATUS_OK:
-            data = self._deserialize(response_content)
+            response_data = self._deserialize(response_content)
         return Response(response_headers, response_content, response_data)

     def _serialize(self, data):


@@ -45,7 +45,7 @@ def main():
                         help="URL to the repository or path to the package to be checked.")
     parser.add_argument("--repo-only", action='store_true',
                         help="Do not check the package itself and only its repository.")
-    parser.add_argument("--verbose", "-v", action='store_true',
+    parser.add_argument("-v", "--verbose", action='store_true',
                         help="Increase verbosity.")
     parser.add_argument("--debug", action='store_true',
                         help="Enter pdb on excpetions. Implies --verbose.")


@@ -31,7 +31,7 @@ def parse(value, request):
     try:
       if cache.get(cache_key):
         try:
-          parsed = re.sub(r'\[' + item + r'\]', cache.get(item), parsed)
+          parsed = re.sub(r'\[' + item + r'\]', cache.get(cache_key), parsed)
         except:
           pass
       else:


@@ -61,7 +61,7 @@ class Client:
             if response.status != 200:
                 body = await response.read()
                 raise DBException.from_message(
-                    statement, body.decode(errors='replace'),
+                    query, body.decode(errors='replace'),
                 )

             if response.content_type == 'application/json':


@@ -116,7 +116,7 @@ class MysqlTable(Table):
                 scolumn += ' AUTO_INCREMENT'

         if default != NoValue:
-            if not_null or primary:
+            if auto_increment or primary:
                 raise ValueError('Can''t have default value')
             scolumn += ' DEFAULT %s'
             values.append(default)


@@ -34,5 +34,5 @@ class Device(Material):
 		#atoms.center()
 		x=atoms.positions[:,0]

-		return atoms
+		return center


@@ -195,7 +195,7 @@ def _compute_levels(dfa: DFA, property_states):
     # levels for failure state (i.e. that cannot reach a final state)
     failure_states = set()
     for s in filter(lambda x: x not in z_current, dfa.states):
-        state2level[s] = max_level
+        state2level[s] = level
         failure_states.add(s)

     return state2level, max_level, failure_states


@@ -82,5 +82,5 @@ def calculate(stea_input):

         request.add_profile(profile_id, start_year, data)

-    return SteaResult(client.calculate(request), project)
+    return SteaResult(client.calculate(request), stea_input)


@@ -710,7 +710,7 @@ class tree_classifier(object):
                     print(fstr2.format('Class ', dt.classes_[i]), end="")

                 for j in range(n_classes):
-                    print("{:>10d}".format(conf_mat_t[i][j]), end="")
+                    print("{:>10d}".format(conf_mat_v[i][j]), end="")
                 print("")
             print("")


@@ -342,7 +342,7 @@ class Profiler(TransformerPrimitiveBase[Input, Output, Hyperparams]):
                                 inputs.iloc[:, col] = numerics
                         else:
                             if "http://schema.org/Float" not in old_metadata['semantic_types']:
-                                old_metadata['semantic_types'] = ("http://schema.org/Float",)
+                                old_metadata['semantic_types'] += ("http://schema.org/Float",)
                                 old_metadata['structural_type'] = type(10.2)
                                 inputs.iloc[:, col] = numerics


@@ -72,7 +72,7 @@ class FilterTree:
                         sql_tuple = FilterTree.text_similarity_filter(rule[0], pattern, True)
                     else:
                         sql_tuple = FilterTree.text_similarity_filter(rule[0], pattern, False)
-                    pattern_specs.append(sql_tuple)
+                    rule_specs.append(sql_tuple)

         rule_strings = [' AND '.join([rule[0] for rule in rule_specs]),
                         ' OR '.join([rule[0] for rule in pattern_specs])]


@@ -235,7 +235,7 @@ class Path(AbstractPath):
     normpath = property(lambda self: pth(ospath.normpath(self)))
     norm = property(lambda self: pth(ospath.normcase(ospath.normpath(self))))
     real = realpath = property(lambda self: pth(ospath.realpath(self)))
-    rel = relpath = lambda self, start: pth(ospath.relpath(self, start))
+    rel = relpath = lambda self, start: pth(ospath.relpath(start, self))
     same = samefile = lambda self, other: ospath.samefile(self, other)
     if hasattr(os, 'link'):
         if PY33:


@@ -33,7 +33,7 @@ def get_date_from_source(source):
     # _ctime = time.strftime("%d/%m/%Y %H:%M", time.gmtime(ctime))
     return time.strftime(
         "%d/%m/%Y %H:%M GMT",
-        time.gmtime(ctime)
+        time.gmtime(mtime)
     )


@@ -88,5 +88,5 @@ def remove(ctx, name=None, index=None):
     if(name is None and index is not None):
         cli_utils.print_result(connections[int(index)], ctx.logger, as_json=ctx.json, as_pickle=ctx.pickle, depth=ctx.depth, filter_tree=ctx.filter_tree)
     if(name is not None and index is None):
-        connections = [connection for connection in connections if connection["name"]!=name]
+        connections = [connection for connection in connections if connection["name"]==name]
         cli_utils.print_result(connections, ctx.logger, as_json=ctx.json, as_pickle=ctx.pickle, depth=ctx.depth, filter_tree=ctx.filter_tree)


@@ -50,7 +50,7 @@ def ddot(L, R, left=True, out=None):
     else:
         if out is None:
             out = copy(L)
-        return multiply(out, R, out=out)
+        return multiply(L, R, out=out)

 def cdot(L, out=None):


@@ -474,7 +474,7 @@ class Recurrence:
         if freq not in (HOURLY, MINUTELY, DAILY, WEEKLY, MONTHLY, YEARLY):
             raise ValueError('"freq" parameter must be one of HOURLY, MINUTELY, DAILY, WEEKLY, MONTHLY or YEARLY. '
                              '{} was provided'.format(freq))
-        if interval and (isinstance(interval, int) or interval < 1):
+        if interval and (not isinstance(interval, int) or interval < 1):
             raise ValueError('"interval" parameter must be a positive int. '
                              '{} was provided'.format(interval))
         if count and (not isinstance(count, int) or count < 1):


@@ -383,7 +383,7 @@ def set_env(delim1, delim2, hd, tb):
     :param hd: (string) the header of parameter
     :param tb: (int) the number of space/tab that bedore the docstring
     """
-    if isinstance(int, tb):
+    if isinstance(tb, int):
         global tab
         tab = tb
     else:


@@ -59,7 +59,7 @@ class Scheduler(object):

     def delay_job(self, job, time_delta):
         amount = int(time_delta.total_seconds())
-        self.connection.zincrby(self.scheduler_jobs_key, job.id, amount)
+        self.connection.zincrby(self.scheduler_jobs_key, amount, job.id)

     def should_repeat_job(self, job):
         max_runs = job.meta['max_runs']


@@ -633,7 +633,7 @@ def toml_to_family(toml_filename):
       for relation in big_dict['spouse']
       if relation[0] == spouse_uid
     ]
-    family.add_spouses(spouse, children)
+    family.add_spouses(spouse, spouses)

   return family


@@ -83,7 +83,7 @@ def test_roles(db):
         role1 = db_adapter.find_first_object(RoleClass, name='Role 1')
         db_adapter.delete_object(role1)
         role2 = db_adapter.find_first_object(RoleClass, name='Role 2')
-        db_adapter.delete_object(role1)
+        db_adapter.delete_object(role2)

     db_adapter.commit()


@@ -117,7 +117,7 @@ def test_sorted_order(opt):
                     return False

                 if (outer_sort == outer_sort_next):
-                    if (inner_sort > inner_sort_next):
+                    if (inner_sort < inner_sort_next):
                         print("For Halo ID {0} we had a {1} of {2}.  After sorting via lexsort "
                               "inner-key {1}, the next Halo has ID {3} and a {1} of {4}"
                               .format(halo_id, opt["sort_mass"], inner_sort, halo_id_next,


@@ -119,7 +119,7 @@ def my_test_sorted_order(opt):
                     pytest.fail()

                 if (outer_sort == outer_sort_next):
-                    if (inner_sort < inner_sort_next):
+                    if (inner_sort > inner_sort_next):
                         print("For Halo ID {0} we had a {1} of {2}.  After sorting via lexsort "
                               "inner-key {1}, the next Halo has ID {3} and a {1} of {4}"
                               .format(halo_id, opt["sort_mass"], inner_sort, halo_id_next,


@@ -416,7 +416,7 @@ class atapt:

         # word 83 "Commands and feature sets supported"
         features = int.from_bytes(buf[166] + buf[167], byteorder='little')
-        if major & 0x400:
+        if features & 0x400:
             self.lba48bit = True
         else:
             self.lba48bit = False


@@ -221,7 +221,7 @@ def plot_qpi_sphere(qpi_real, qpi_sim, path=None, simtype="simulation"):
     plt.tight_layout(rect=(0, 0, 1, .95))

     # add identifier
-    fig.text(x=.5, y=.99, s=qpi_real["identifier"],
+    fig.text(x=.5, y=.99, s=qpi_sim["identifier"],
              verticalalignment="top",
              horizontalalignment="center",
              fontsize=14)


@@ -59,7 +59,7 @@ class UniqueAuthEmail(validators.FancyValidator):
                 user_id = values['user_id']
             else:
                 user_id = None
-            if email and (user.user_id != user_id):
+            if user and (user.user_id != user_id):
                 errors = {'email': self.message('not_unique_email', state)}
                 raise Invalid(self.message('not_unique_email', state),
                                            values, state, error_dict=errors)


@@ -292,7 +292,7 @@ class CommandLine:

         for value in [command["maf"], command["call"], command["rep"], command["seq_identity"]]:
             if value != -1:
-                if value < 1 or value > 1:
+                if value < 0 or value > 1:
                     raise ValueError("Filter and identity thresholds must be larger >= 0 and <= 1.")

         for value in [command["clone_selector"], command["identity_selector"]]:


@@ -387,7 +387,7 @@ def setup_calculation(
         raise SetupError(msg)
     else:
         logger.info('Successfully set up Phantom calculation')
-        logger.info(f'run_path: {run_path}')
+        logger.info(f'run_path: {_run_path}')

     shutil.copy(_in_file, _run_path)


@@ -36,7 +36,7 @@ class EventSumsProducer(object):
         event.METnoX_diMuonParaProjPt_Minus_DiMuon_pt = dimu_para - dimu_pt
         event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt = dimu_perp + dimu_pt
         event.METnoX_diMuonParaProjPt_Div_DiMuon_pt = dimu_para / dimu_pt
-        event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt_Div_DiMuon_pt = (dimu_para + dimu_pt) / dimu_pt
+        event.METnoX_diMuonPerpProjPt_Plus_DiMuon_pt_Div_DiMuon_pt = (dimu_perp + dimu_pt) / dimu_pt

         # MHT
         ht, mht, mhphi = create_mht(


@@ -78,7 +78,7 @@ def run_scraper():
                 scraper = obj

         for name, obj in getattr(mod, '_rr_export', {}).iteritems():
-               scope[name] = name
+               scope[name] = obj

     scraper.scrape(url=args.url,
                    scraper_name=args.scraper,


@@ -83,7 +83,7 @@ class callbacks_keras:
         if epoch%self.decay_after_n_epoch==0 and epoch!=0:
             lr = K.get_value(self.model.optimizer.lr)
             K.set_value(self.model.optimizer.lr, lr*self.decay_rate)
-            print("lr changed to {}".format(lr**self.decay_rate))
+            print("lr changed to {}".format(lr*self.decay_rate))
         return K.get_value(self.model.optimizer.lr)

 def ka_xgb_r2_error(preds, dtrain):


@@ -69,7 +69,7 @@ class dbhelper(object):

     @_run
     def update(self,document,target,**kargs):
-        self._db[document].update(kargs,target,callback=self.callback)
+        self._db[document].update(target,kargs,callback=self.callback)

     # def to_list_callback(self,infos,error):


@@ -224,7 +224,7 @@ class OptimizeCalculation(JobCalculation):

         structure_txt = generate_LAMMPS_structure(structure)
-        input_txt = generate_LAMMPS_input(potential_data,
+        input_txt = generate_LAMMPS_input(potential_object,
                                           parameters_data,
                                           structure_file=self._INPUT_STRUCTURE,
                                           optimize_path_file=self._OUTPUT_TRAJECTORY_FILE_NAME)


@@ -547,7 +547,7 @@ class WorkflowQHA(Workflow):
                 test_range[0] -= np.ceil(np.min([total_range/2, abs(test_range[0] - min_stress)]) / interval) * interval
 #                test_range[0] -= np.ceil(abs(test_range[0] - min_stress) / interval) * interval

-            if max_stress < test_range[1] or min_stress > test_range[0]:
+            if max_stress < test_range[1] and min_stress > test_range[0]:
                 if abs(max_stress - test_range[1]) < interval * 2 or abs(test_range[0] - min_stress) < interval * 2:
                     interval *= 0.5


@@ -833,7 +833,7 @@ class Well(object):
             )
         if not self._radius.scalar:
             raise ValueError("Well: 'radius' needs to be scalar")
-        if self.radius <= 0.0:
+        if self.radius < 0.0:
             raise ValueError("Well: 'radius' needs to be positiv")

         if isinstance(coordinates, Variable):


@@ -544,7 +544,7 @@ def load_obs(obsfile):

             obs = load_var(TxtIO(zfile.open(obsf)))

-        observation = varlib.Observation(name, time, obs, description)
+        observation = varlib.Observation(name, obs, time, description)
     except Exception:
         raise Exception("loadObs: loading the observation was not possible")
     return observation


@@ -370,7 +370,7 @@ class PumpingTest(Test):
         description : :class:`str`, optional
             Description of the Variable. Default: ``"Drawdown observation"``
         """
-        obs = varlib.DrawdownObs(well, time, observation, description)
+        obs = varlib.DrawdownObs(well, observation, time, description)
         self.add_observations(obs)

     def add_observations(self, obs):


@@ -48,7 +48,7 @@ def _route_handler(venom: 'venom.rpc.Venom', method: Method, protocol_factory: T
             http_request_query.decode(http_request.url.query, request)
             http_request_path.decode(http_request.match_info, request)

-            response = await venom.invoke(method, request, context=AioHTTPRequestContext(request))
+            response = await venom.invoke(method, request, context=AioHTTPRequestContext(http_request))
             return web.Response(body=rpc_response.pack(response),
                                 content_type=rpc_response.mime,
                                 status=http_status)


@@ -117,7 +117,7 @@ class Backend(six.with_metaclass(MediaDefiningClass, Router)):
         # set app_index_class on app to "None" to skip creation
         app_index_class = getattr(app_config, 'app_index_class', None)
         if app_index_class:
-            template_name = getattr(app_config, 'template_name', 'app_index.html')
+            template_name = getattr(app_index_class, 'template_name', 'app_index.html')
             app_index = app_index_class.as_view(
                 app_config=app_config, backend=self, template_name=template_name
             )


@@ -30,7 +30,7 @@ class CronJob(object):
         assert len(time) <= 5
         padded_time = tuple(time) + ('*',) * (5 - len(time))
         assert len(padded_time) == 5
-        return cls(command, time[0], user, padded_time[1], padded_time[2], padded_time[3], padded_time[4])
+        return cls(command, padded_time[0], user, padded_time[1], padded_time[2], padded_time[3], padded_time[4])

     @property
     def time(self):


@@ -30,7 +30,7 @@ class CronJob(object):
         if len(time) > 5:
             raise RuntimeError("Malformed cronjob time: {!r}".format(time))
         padded_time = tuple(time) + ('*',) * (5 - len(time))
-        if len(padded_time) > 5:
+        if len(padded_time) != 5:
             raise RuntimeError("Malformed cronjob time: {!r}".format(padded_time))
         return cls(command, padded_time[0], user, padded_time[1], padded_time[2], padded_time[3], padded_time[4])


@@ -116,7 +116,7 @@ class MsgConnection(protocol.Protocol):
         def done(result):
             self._sending = False
             return result
-        d.addBoth(d)
+        d.addBoth(done)

     def _frame_received(self, frameid, blob):
         return self.frame_received(frameid, blob)


@@ -770,7 +770,7 @@ class Workflow(Tool):
                 wtools[s.id()] = wf_wdl
                 wtools.update(wf_tools)
             else:
-                wtools[s.id()] = t.wdl(with_docker=with_docker)
+                wtools[t.id()] = t.wdl(with_docker=with_docker)

             w.calls.append(
                 s.wdl(tool_aliases[t.id().lower()].upper() + "." + t.id(), s.id())


@@ -13,7 +13,7 @@ def image(filename, colormap="viridis", vmin=None, vmax=None, log=False,

     z, edges = np.histogram(data.ids,
                             bins=np.arange(-0.5, data.nx * data.ny + 0.5))
-    z = z.reshape(data.nx, data.ny)
+    z = z.reshape(data.ny, data.nx)
     if side_panels:
         z_sumx = np.sum(z, axis=1)
         z_sumy = np.sum(z, axis=0)


@@ -65,7 +65,7 @@ def slicer(filename, colormap="viridis", vmin=None, vmax=None, log=False,
     z, xe, ye = np.histogram2d(data.ids, data.tofs/1.0e3,
                                bins=[np.arange(-0.5, data.nx * data.ny + 0.5),
                                      t])
-    z = z.reshape(data.nx, data.ny, nbins)
+    z = z.reshape(data.ny, data.nx, nbins)
     # Transpose should be True for old December 2018 files
     if transpose:
         z = np.transpose(z, axes=[1, 0, 2])


@@ -200,7 +200,7 @@ class Model(object):

         print('Building stringers...')
         for s in stringers.values():
-            s.elements = [bdf.elements[eid] for eid in p.eids]
+            s.elements = [bdf.elements[eid] for eid in s.eids]
             setelements = set(s.elements)
         print('finished!')


@@ -61,7 +61,7 @@ def as_raw(reg, logical_value, use_float=False):
         else:
             value = (logical_value % 360.0) / 360.0 * 65535.0
     elif reg in (Register.BRIGHTNESS, Register.SATURATION):
-        if logical_value == 100.0:
+        if logical_value >= 100.0:
             value = 65535.0
         else:
             value = logical_value / 100.0 * 65535.0


@@ -25,7 +25,7 @@ class SeparateContext(Contract):
         return SeparateContext(tokens[0]['child'], where=where)

-sepcon = (Group(Literal('$') - Literal('(') -
+sepcon = (Group(Literal('$') + Literal('(') -
                 contract_expression('child') - Literal(')')))
 sepcon.setParseAction(SeparateContext.parse_action)
 sepcon.setName('Context separation construct')


@@ -111,7 +111,7 @@ class Rasterdata_tiffs:
             time_or = ''

             # Apply gapfilling if needed
-            if gap_filling != None and ~np.isnan(np.nanmean(Array)):
+            if gap_filling != None and ~np.isnan(np.nanmean(Array_end)):
                 Array_end[np.isnan(Array_end)] = -9999
                 Array_end = RC.gap_filling(Array_end, -9999, gap_filling)
             Array_end = Array_end * MASK


@@ -311,7 +311,7 @@ def main(Start_year_analyses, End_year_analyses, output_folder):
     if not np.isnan(np.nanmean(Crop_S1_End.Data)):
         for Date_Year in Dates_Years:
             year_diff = int(Date_Year.year - Dates_Years[0].year)
-            for dekad in range(0,int(np.nanmax(Crop_S2_End.Data))):
+            for dekad in range(0,int(np.nanmax(Crop_S3_End.Data))):
                 Accumulated_NPP_Data_Start_S1[year_diff, Crop_S1_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S1_End.Data[year_diff, :, :] == dekad]
                 Accumulated_NPP_Data_Start_S2[year_diff, Crop_S2_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S2_End.Data[year_diff, :, :] == dekad]
                 Accumulated_NPP_Data_Start_S3[year_diff, Crop_S3_End.Data[year_diff, :, :] == dekad] = NPPcum.Data[np.minimum(NPPcum.Size[0]-1, int(year_diff * 36 + dekad-1)), Crop_S3_End.Data[year_diff, :, :] == dekad]


@@ -121,7 +121,7 @@ def get_positive_stabilizer_groups(n_qubits, n_states):
                 continue
         subspaces.append(res)
         generators.append(tuple(candidate.generators))
-        if len(generators) == n_states:
+        if len(generators) == target:
             break
     return generators


@@ -16,4 +16,4 @@ class TestService(TestCase):

     def test_write_missing_value(self):
         svc = Service("https://volatile.wtf")
-        self.assertRaises(lambda: svc["UNGYIZFHIA"], MissingKeyException)
+        self.assertRaises(MissingKeyException, lambda: svc["UNGYIZFHIA"])


@@ -934,7 +934,7 @@ class MuseCube:
                     print('Fit Aceptado')
                     print(str(x[i]) + ',' + str(y[i]))
                 units = u.km / u.s
-                vel = ltu.dv_from_z((mean / wv_line_vac) - 1, z_line).to(units).value
+                vel = ltu.dv_from_z((mean / wv_line_vac) - 1, z).to(units).value
                 kine_im[y[i]][x[i]] = vel
             else:
                 if debug:


@@ -20,7 +20,7 @@ def _config_parse(config_file):
             'port': os.getenv('DB_PORT'),
             'database': os.getenv('DATABASE'),
         }
-    return config_file
+    return dwh_config

 def create_engine(config_file=None):
     dwh_config = _config_parse(config_file)


@@ -24,7 +24,7 @@ class TestAppend(unittest.TestCase):
             expected = fin.read()
         cmd, flags = self.interpreter.build_command(command, input_file)
         res = self.interpreter.execute_command(cmd, flags, return_output=True)
-        self.assertEqual(res, expected)
+        self.assertEqual(expected, res)

     def perform_test_from_key(self, key: str):
         tests = self.tests[key]


@@ -344,7 +344,7 @@ def train(inputs, targets, model=None, data=None, optimizer=None, lr=None,
     logger.info('Training finished in {} hours {} minutes {:.2f} seconds.'
                 .format(h, m, s))
     logger.info('outputs')
-    logger.info(outputs)
+    logger.info(outputs_)
     logger.info('targets')
     logger.info(targets)


@@ -39,7 +39,7 @@ def mdata(path, track_element):
             for tag in tags:
                 tagstring = tag+":"
                 if tagstring in linecheck:
-                    stringf = out.split(': ')[1]
+                    stringf = decoded.split(': ')[1]
                     ttag = tag
                     if tag == "artist":
                         ttag = "creator"


@@ -45,7 +45,7 @@ def mdata(path, track_element):
                         ttag = "creator"
                     if tag == "genre":
                         ttag = "info"
-                    ttag = SubElement(track_element, tag)
+                    ttag = SubElement(track_element, ttag)
                     ttag.text = stringf.rstrip()
         else:
             break


@@ -8,7 +8,7 @@ class ValidationError(Exception):

 class CLIN28JSON:
     def __init__(self, filename):
-        if os.path.exists(filename):
+        if not os.path.exists(filename):
             raise FileExistsError("File not found: " + filename)

         with open(filename,'r', encoding='utf-8') as f:


@@ -57,7 +57,7 @@ class CLIN28JSON:
                         correction['confidence'] = float(correction['confidence'])
                     except:
                         raise ValidationError("Invalid confidence value (" + str(correction['confidence']) + ") " + repr(correction))
-                    if correction['confidence'] < 0 or correction['confidence'] > 0:
+                    if correction['confidence'] < 0 or correction['confidence'] > 1:
                         raise ValidationError("Confidence value out of bounds (" + str(correction['confidence']) + ") " + repr(correction))

     def words(self):


@@ -24,7 +24,7 @@ class SmsSenderTest(TestCase):
     @patch('urllib2.urlopen', _fake_urlopen)
     def test_send_request(self):
         sender = SmsSender()
-        response = sender.send_request('/link/', {})
+        response = sender.send_request({}, '/link/')
         self.assertIn(SMSMessage.STATUS_ACCEPTED, response)

     @patch('smsaero.conf.SMSAERO_PASSWORD', 'FAKE')


@@ -68,7 +68,7 @@ def send_sms(to, text, signature_id=None, date=None, link='/send/'):
         'from': signature.name,
         'date': date or '',
     }
-    response = sender.send_request(link, params)
+    response = sender.send_request(params, link)
     sms_id, status = sender.parse_response(response)

     if not sms_id or not status:


@@ -103,7 +103,7 @@ def reformat_slice(a_slice, a_length=None):
                     start = a_length - 1
                 if stop_i and stop < -a_length:
                     stop = None
-                    stop_i = True
+                    stop_i = False

     # Catch some known empty slices.
     if (step > 0) and (stop == 0):


@@ -55,7 +55,7 @@ def reformat_slice(a_slice, a_length=None):
     new_slice = a_slice
     if new_slice is Ellipsis:
         new_slice = slice(None)
-    elif not isinstance(new_slice, slice):
+    elif not isinstance(a_slice, slice):
         raise ValueError(
             "Expected a `slice` type. Instead got `%s`." % str(new_slice)
         )


@@ -57,7 +57,7 @@ def reformat_slice(a_slice, a_length=None):
         new_slice = slice(None)
     elif not isinstance(a_slice, slice):
         raise ValueError(
-            "Expected a `slice` type. Instead got `%s`." % str(new_slice)
+            "Expected a `slice` type. Instead got `%s`." % str(a_slice)
         )

     if new_slice.step == 0:


@@ -86,7 +86,7 @@ def main():
     if success is False:
         sys.exit("Wrong passphrase after %d attempts" % max_try_count)

-    server.set_backend(backend)
+    kpconf.set_backend(backend)

     # config daemon
     if is_daemon:


@@ -20,7 +20,7 @@ class IndexType(Enum):
     def to_train(self) -> bool:
         if self.name == "compress":
             return True
-        return True
+        return False

     @property
     def index_factory(self) -> str:


@@ -69,7 +69,7 @@ def main_Concern():
         (-Concern).printf('vimArgs := $list()')
         for arg in vimargs:
             (-Concern).printf("vimArgs += %s", arg)
-        import_module(f".consumer.{Concern.consumerName}", package = __package__).configure(config)
+        import_module(f".consumer.{Concern.consumerName}", package = __package__).configure(Concern)
         (-Concern).processtemplate(resource_filename(templates.__name__, 'vimrc.aridt'), concernvimrc)
         (-Concern).printf('" = $(pystr)')
         (-Concern).processtemplate(resource_filename(templates.__name__, 'sendblock.py.aridt'), sendblock)


@@ -66,7 +66,7 @@ def kmeanspp(X, n_clusters, seed=None, replace=False,
             centers[c] = X[best_candidate].toarray()
         else:
             centers[c] = X[best_candidate]
-        centers_idx.append(c)
+        centers_idx.append(best_candidate)
         current_pot = best_pot
         closest_dist_sq = best_dist_sq


@@ -35,7 +35,7 @@ def UVES_HD132205(local_dir="./"):
     with tarfile.open(filename) as file:
         file.extractall(path=target_dir)

-    return local_dir
+    return target_dir

 if __name__ == "__main__":


@@ -120,7 +120,7 @@ class SelectorWidget(QtGui.QFrame):
         '''
         matches = self.list_widget.findItems(
             item,
-            QtCore.Qt.MatchFixedString | QtCore.Qt.CaseSensitive
+            QtCore.Qt.MatchFixedString & QtCore.Qt.CaseSensitive
         )

         if matches:


@@ -143,6 +143,6 @@ class SpearmanDistance(DistanceMetric):
         if first is not self._last:
             self._last = first
             self._last_ranks = np.apply_along_axis(st.rankdata, 0, first)
-        second_ranks = np.apply_along_axis(st.rankdata, 0, first)
+        second_ranks = np.apply_along_axis(st.rankdata, 0, second)
         return dist.cdist(self._last_ranks, second_ranks, metric='correlation')


@@ -15,7 +15,7 @@ def resume(file_name):
         with open(file_path, mode='rb') as f:
             target = pickle.load(f)
     yield target
-    if target is None:
+    if target is not None:
         freeze(target, file_name)

ReplaceText(target=' is not ' @(18,13)->(18,17))


@@ -3,7 +3,7 @@ class pycent:
         pass

     def percent_of(self, percent, whole):
-        return (percent * whole) * 100
+        return (percent * whole) / 100

     def percentage(self, part, whole):
         return 100 * float(part)/float(whole)


@@ -52,7 +52,7 @@ def run():

     if batch:
         import batch_process
-        batch_process.run(batch)
+        batch_process.run(indir)
     else:
         metadata_dir = os.path.join(indir,'metadata')
         if os.path.isdir(metadata_dir):


@@ -680,7 +680,7 @@ class IsNullOperator(UnaryPostfixOperator):
     """

     def __init__(self, operand, invert=False):
-        super(IsNullOperator, self).__init__(u' IS NOT NULL' if invert else u' IS NULL', operand)
+        super(IsNullOperator, self).__init__(operand, u' IS NOT NULL' if invert else u' IS NULL')
         self.invert = invert

     def NOT(self):


@@ -102,7 +102,7 @@ class MetaCriteriaTool(object):
         self.tools_config_by_criterion_dict = tools_config_by_criterion_dict

         # Verify Direct Arguments Variables
-        ERROR_HANDLER.assert_true(self.criteria_working_dir is None, \
+        ERROR_HANDLER.assert_true(self.criteria_working_dir is not None, \
                             "Must specify criteria_working_dir", __file__)
         for criterion in self.tools_config_by_criterion_dict:
             ERROR_HANDLER.assert_true( \


@@ -127,7 +127,7 @@ class MetaTestcaseTool(object):
         self.test_tool_config_list = test_tool_config_list

         # Verify Direct Arguments Variables
-        ERROR_HANDLER.assert_true(self.tests_working_dir is None, \
+        ERROR_HANDLER.assert_true(self.tests_working_dir is not None, \
                                     "Must specify tests_working_dir", __file__)
         ERROR_HANDLER.assert_true(len(self.test_tool_config_list) != \
                                 len(set([c.get_tool_config_alias() for c in \


@@ -56,7 +56,7 @@ class IdentityCodeConverter(BaseCodeFormatConverter):
             for src, dest in list(file_src_dest_map.items()):
                 abs_src = os.path.join(self.repository_rootdir, src)
                 if os.path.abspath(abs_src) != os.path.abspath(dest):
-                    shutil.copy2(src, dest)
+                    shutil.copy2(abs_src, dest)
             return DefaultCallbackObject.after_command(self)
         #~ def after_command()
     #~ class CopyCallbackObject


@@ -489,7 +489,7 @@ class TestcasesToolKlee(BaseTestcaseTool):
                                         KTestTestFormat.get_dir(dp, folders)) \
                                                 for dp in dup_tuple[1:]]
             for df in dup_tuple[1:]:
-                if KTestTestFormat.get_dir(kt, folders) == \
+                if KTestTestFormat.get_dir(df, folders) == \
                                                         self.tests_storage_dir:
                     os.remove(df)
         common_fs.dumpJSON(kepttest2duptest_map, self.keptktest2dupktests)


@@ -56,7 +56,7 @@ class CliUserInterface(object):
         parser_customexec = subparsers.add_parser('customexec', \
                                     help="Make some custom execution AFTER the"
                                         " main execution is done")
-        parser_run.add_argument("--nohashoutlog", action='store_true', \
+        parser_customexec.add_argument("--nohashoutlog", action='store_true', \
                                          help="When set, enforce no hash log")

         if len(sys.argv)==1:


@@ -17,7 +17,7 @@ def get_definitions_pairs(defines_list):
     def_pairs = {}
     for define_statement_string in defines_list:
         elems = re.split(" ", define_statement_string)
-        if len(elems) > 3:  # When define statement is not a simple NAME <--> VALUE PAIR
+        if len(elems) != 3:  # When define statement is not a simple NAME <--> VALUE PAIR
             continue  # Do not preprocess this
         name = elems[1]
         value = elems[2]


@@ -133,7 +133,7 @@ class Motor(Analysis):
         max_length = max(run_lengths + tumble_lengths)
         bins = np.linspace(0, max_length, 10)
         logbins = np.logspace(0, np.log10(bins[-1]), len(bins))
-        ax5.hist([run_lengths, tumble_lengths], bins=logbins, label=['run_lengths', 'tumble_lengths'], color=['b', 'm'])
+        ax5.hist([run_lengths, tumble_lengths], bins=bins, label=['run_lengths', 'tumble_lengths'], color=['b', 'm'])

         # plot expected values
         ax5.axvline(x=expected_tumble, color='m', linestyle='dashed', label='expected tumble')


@@ -43,7 +43,7 @@ class ShepherdControl(ActorControl):
             experiment_id, number, agent_type, environment_type))

         # boot environment
-        self.add_agent(experiment_id, environment_type, lattice_config)
+        self.add_agent(experiment_id, environment_type, actor_config)
         time.sleep(10) # wait for the environment to boot

         # boot agents


@@ -771,7 +771,7 @@ def load_compartment(composite, boot_config={}):
         'emitter': boot_config.get('emitter', 'timeseries'),
         'time_step': boot_config.get('time_step', 1.0)})

-    return Compartment(processes, states, derivers, options)
+    return Compartment(processes, derivers, states, options)

 def simulate_compartment(compartment, settings={}):


@@ -67,7 +67,7 @@ def plot_signal_transduction(timeseries, out_dir='out', filename='signal_transdu
     ax2.tick_params(right=False, top=False)
     ax2.set_ylabel("cluster activity \n P(on)", fontsize=10)

-    ax2.set_xticklabels([])
+    ax3.set_xticklabels([])
     ax3.spines['right'].set_visible(False)
     ax3.spines['top'].set_visible(False)
     ax3.tick_params(right=False, top=False)


@@ -63,7 +63,7 @@ class ProjectVariablesUpdater(VariablesUpdater):
         _logger.info("Set variables for \"%s\": %s" % (self.project, variables))

     def update_required(self) -> bool:
-        return self._variables_manager.get_variables() == self._get_required_variables()
+        return self._variables_manager.get_variables() != self._get_required_variables()

     def _get_required_variables(self) -> Dict[str, str]:
         """


@@ -115,7 +115,7 @@ class LogEntryParser:
             Logger.data_property_placeholder_name: data  # here we set the data property with a special key
         }

-        if log_entry.message is not "" or log_entry.message is not None:
+        if log_entry.message is not "" and log_entry.message is not None:
             dto["message"] = log_entry.message

         if exception_info is not None:


@@ -94,7 +94,7 @@ class GeneralPackage(object):
                       install_path=deb.get('install_path'),
                       dependencies=deb_dependencies,
                       description=deb.get('description'),
-                      excludes=project.get('excludes', []))
+                      excludes=deb.get('excludes', []))

             generated_builds.append(dpm.generate())
         return generated_builds


@@ -88,7 +88,7 @@ if __name__ == "__main__":
     else:
         angleopt = None;
     KE, good = totalKE(d, ecut, angleopt, return_bools=True);
-    LE = laserE(E_0, w, T, dim=dim);
+    LE = laserE(E_0, T, w, dim=dim);
     totalq = d['q'][good].sum()*1e12;
     print('total charge: {} {}'.format(totalq,'pC/cm' if opts['--2D'] else 'pC'));
     print("total energy: {} J".format(KE));


@@ -516,7 +516,7 @@ def load_aaomega_multispec(filename, fill_value=-1, clean=True):
     for i, index in enumerate(program_indices):

         headers = base_headers.copy()
-        headers['FIBRE_NUM'] = i + 1
+        headers['FIBRE_NUM'] = index + 1

         for header in req_fibre_headers:
             headers[header] = image[2].data[index][header]


@@ -26,7 +26,7 @@ def form(request, template_name='contato/contato_form.html',
             mensagem.update(dict)

         # Enviando o email
-        enviar_email(email, settings.DEFAULT_FROM_EMAIL, nome,
+        enviar_email(settings.DEFAULT_FROM_EMAIL, email, nome,
             assunto, template_email, mensagem)

         # Mostra mensagem de sucesso


@@ -115,7 +115,7 @@ def bsmap(config):
 def mcall_stat_parse(infile):
 	with open(infile) as f:
 		dstr=f.read()
-	return float(re.search('bisulfite conversion ratio = ([\d.]+)', f).groups()[0])
+	return float(re.search('bisulfite conversion ratio = ([\d.]+)', dstr).groups()[0])

 def mcall_runcmd(infile, outdir, sampleid, reference, numthread, verbose=False):
 	if os.path.exists(outdir):


@@ -34,7 +34,7 @@ class PlotValuesUtil(object):

         # x-data for the ECDF: x_
         x_value = np.sort(data)
-        size_data = x_value.size
+        size_data = raw_data.size
         # y-data for the ECDF: y
         y_value = []


@@ -137,7 +137,7 @@ class JobUtil(object):

     @staticmethod
     def retrieve_rows_csv(request, job, **kwargs):
-        if request.method != 'POST':
+        if request.method == 'POST':
             print('kwargs', kwargs)
             start_row = kwargs.get('start_row')
             num_rows = kwargs.get('number_rows')


@@ -74,7 +74,7 @@ def cli( dataset, vcf, db_connection, qual, ref, use_panel, outfile, customer, s
         vcfsamples = _compare_samples(vcfsamples, samples)

     ## returns a this tuple-> ( total_vars, beacon_vars(type: dict), discaded_vars(type: dict))
-    vcf_results = get_variants(vcf_obj, vcfsamples, raw_variants, qual)
+    vcf_results = get_variants(vcf_obj, raw_variants , vcfsamples, qual)

     ## Print overall results of VCF file parsing to terminal
     vars_to_beacon = _print_results(vcf_results, qual)


@@ -38,7 +38,7 @@ def beacon_upload(connection, vcf_path, panel_path, dataset, outfile="", custome
     # returns a this tuple-> ( n_total_vars, beacon_vars(type: dict), discaded_vars(type: dict))
     ### beacon_vars is a disctionary with key --> sample, and value --> list of tuples containing the non-reference variants. Each tuple is defined as: (chr, start, alt_allele)
     ### discaded_vars is a dictionary with key --> sample and value --> number of discarded vars due to quality for that sample.
-    vcf_results = get_variants(panel_filtered_results[0], samples, raw_variants, qual)
+    vcf_results = get_variants(panel_filtered_results[0], raw_variants, samples, qual)

     # Insert variants into the beacon. It returns a tuple: (vars_before_upload, vars_after_upload)
     beacon_update_result = bare_variants_uploader(connection, dataset, vcf_results, genome_reference)


@@ -84,7 +84,7 @@ class JsonConverter(object):
             for ch in channels:
                 permissions[int(ch)] = (read, write)
         else:
-            permissions[int(ch)] = (read, write)
+            permissions[int(channels)] = (read, write)

         return permissions;


@@ -26,7 +26,7 @@ def microlensing_flux_priors(size_dataset, f_source, g_blending):

 def microlensing_parameters_limits_priors(parameters, limits):
-    for i in xrange(len(parameters)):
+    for i in xrange(len(limits)):

         if (parameters[i] > limits[i][1]) | (parameters[i] < limits[i][0]):


@@ -178,7 +178,7 @@ def sort_2lenses_wide_caustics(caustic_points, critical_curves_points):
         first_branch = positive_y_branches[0]
         second_branch = positive_y_branches[1]

-        if np.max((caustic_points[:, first_branch]).real) > np.max((caustic_points[:, second_branch]).real):
+        if np.max((caustic_points[:, first_branch]).real) < np.max((caustic_points[:, second_branch]).real):

             central_caustic = np.r_[caustic_points[:, first_branch], np.conj(caustic_points[:, first_branch])[::-1]]
             central_cc = np.r_[critical_curves_points[:, first_branch],


@@ -141,7 +141,7 @@ class _TkAttr(object):
                 if is_exception:
                     ex_type, ex_value, ex_tb = response
                     raise ex_type(ex_value, ex_tb)
-                return response_queue
+                return response

 def _Tk__init__(self, *args, **kwargs):


@@ -454,7 +454,7 @@ class DmfDeviceViewBase(SlaveView):
         # Find the closest corner point in the frame to the starting point.
         frame_corner_i = find_closest(slave.df_frame_corners, frame_point_i)
         # Find the closest corner point in the canvas to the end point.
-        canvas_corner_i = find_closest(slave.df_canvas_corners, end_xy)
+        canvas_corner_i = find_closest(slave.df_canvas_corners, start_xy)

         # Save current state of corners to allow undo.
         corners_state = {'df_frame_corners':


@@ -247,7 +247,7 @@ while True:
         token_transfers = token_transfers_item_exporter.get_items('token_transfer')

         enriched_transactions = enrich_transactions(blocks, transactions, receipts)
-        if len(enriched_transactions) == len(transactions):
+        if len(enriched_transactions) != len(transactions):
             raise ValueError('The number of transactions is wrong ' + str(enriched_transactions))
         enriched_logs = enrich_logs(blocks, logs)
         if len(enriched_logs) != len(logs):


@@ -18,7 +18,7 @@ class TestAccumulatingTraces(unittest.TestCase):
     self.basis = FourierBasis(space, 2, 2)
     self.approximation = DiscreteLinearApproximation(0.1, self.basis, actions=3)
     self.env = Env()
-    self.traces = AccumulatingTraces(self.env, self.approximation, 0.5)
+    self.traces = AccumulatingTraces(self.approximation, self.env, 0.5)

   def test_init(self):
     np.testing.assert_equal(self.traces.call(x), np.array([0, 0, 0]))


@@ -18,7 +18,7 @@ class TestLinearFunctionApproximation(unittest.TestCase):
     approximation = LinearApproximation(0.1, basis)
     x = np.array([0.5, 1])
     self.assertEqual(approximation.call(x), 0)
-    approximation.update(x, 1)
+    approximation.update(1, x)
     self.assertAlmostEqual(approximation.call(x), 0.6)

 if __name__ == '__main__':


@@ -35,7 +35,7 @@ def duration_verbose(duration):

     if minutes != 0:
         if not first: res += ", "
-        res += _("%d min") % hours;
+        res += _("%d min") % minutes;
         first = False

     if seconds != 0:


@@ -189,7 +189,7 @@ class Auction:

         if self.state != AuctionState.BID:
             raise InvalidActionError("Bid was attempted, but it is not currently time to submit bids.")
-        elif self.bid > bid:
+        elif self.bid >= bid:
             raise InvalidActionError("Bid amount " + str(bid) + " must be greater than current bid of " + str(self.bid))
         elif not self.owners[owner_id].can_buy(self.nominee, bid):
             raise InvalidActionError("The owner with index " + str(owner_id) +


@@ -40,7 +40,7 @@ class HubClient(object):
                 if hub.lower() == self.name.lower():
                     method = inner_data['M']
                     message = inner_data['A']
-                    await self.__handlers[method](message)
+                    await self.__handlers[method](inner_data)

         connection.received += handle


@@ -40,7 +40,7 @@ class HubClient(object):
                 if hub.lower() == self.name.lower():
                     method = inner_data['M']
                     message = inner_data['A']
-                    await self.__handlers[method](inner_data)
+                    await self.__handlers[method](message)

         connection.received += handle


@@ -232,7 +232,7 @@ class NsblTasklist(Frklist):
                 elif res_type == "ansible-tasklist":

                     tasklists = res_urls
-                    if isinstance(tasklist, string_types):
+                    if isinstance(tasklists, string_types):
                         tasklists = [tasklists]

                     for tl_name in tasklists:


@@ -14,7 +14,7 @@ class Board(object):

     def __init__(self, starting_board=None):
         self.board = np.empty((8,8),dtype=Piece)
-        if starting_board is not None:
+        if starting_board is None:
             self._start_pos()
         else:
             self.board = starting_board


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


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

 def build_absolute_uri(host_url, path=None):


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

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


@@ -27,7 +27,7 @@ def get_setting(setting, override=None):
     if hasattr(settings, attr_name):
         value = getattr(settings, attr_name)
     else:
-        if hasattr(defaults, attr_name):
+        if hasattr(defaults, setting):
             value = getattr(defaults, setting)
         else:
             return override


@@ -48,7 +48,7 @@ def fit(data_x, data_y, sigma_x=None, sigma_y=None, func=None, beta=[1., 0.], *a

     if type(data_x[0]) in ucvar:
         values_x = [d.n for d in data_x]
-        sigma_x = [d.s if d.s!=0 else 1e-5 for d in data_y]
+        sigma_x = [d.s if d.s!=0 else 1e-5 for d in data_x]
     elif type(data_x[0]) in [float, int]:
         values_x = data_x


@@ -93,6 +93,6 @@ def routes(start, dest, city='ba'):

         route.begin_time = route.drives[0].begin_time
         route.end_time = route.drives[-1].end_time
-        route.append(route)
+        routes.append(route)

     return routes


@@ -50,7 +50,7 @@ class UserCommandParser(object):

         # When no magic, add run command
         if not first_line.startswith("%"):
-            first_line = "%{} {}".format(UserCommandParser.run_command, code)
+            first_line = "%{} {}".format(UserCommandParser.run_command, first_line)

         # Remove percentage sign
         first_line = first_line[1:]


@@ -58,7 +58,7 @@ class LayoutDisplayView(QGraphicsView):
             if key.label:
                 label = QGraphicsTextItem(key.label)
                 label.setFont(font)
-                label.setDefaultTextColor(QColor(steno_layout.font_color))
+                label.setDefaultTextColor(QColor(key.font_color))

                 label_rect = label.boundingRect()
                 label_rect.moveCenter(path.boundingRect().center())


@@ -445,7 +445,7 @@ class HealpixFitsMap():
             alm = hp.map2alm([self.I,self.Q,self.U], self.lmax)
             Elm=alm[1]
             Blm=alm[2]
-        lmax=hp.Alm.getlmax(alm.size)
+        lmax=hp.Alm.getlmax(Elm.size)
         if 'P1' in self.derivatives_type:
             out = alm2map_spin_der1([Elm,Blm], self.nside_in, 2)
             self.dQdt =out[1][0]


@@ -42,7 +42,7 @@ def find_child(ends_arr: typing.List[float],
     last = 0
     for i, etime in enumerate(ends_arr):
         if time < etime:
-            return i, etime - last
+            return i, time - last
         last = etime
     if time == last:
         return len(ends_arr) - 1, 0


@@ -347,7 +347,7 @@ class Converter(object):
         # Check the union registry first.
         handler = self._union_registry.get(union)
         if handler is not None:
-            return handler(union, obj)
+            return handler(obj, union)

         # Unions with NoneType in them are basically optionals.
         union_params = union.__args__


@@ -42,7 +42,7 @@ class EClass:
             data = load_dataset(dataset_date=data_date,dataset_type=stat_type)

         # Isolate this energy's data, separate frequencies, and format the data
-        self.E_data = self._isolate_energy(data,E_code)
+        self.E_data = self._isolate_energy(E_code,data)
         self.monthly_data, self.yearly_data = self._sep_freqs(self.E_data)
         for data_df in self.monthly_data,self.yearly_data:
             data_df.set_index('Date_code',inplace=True)


@@ -158,7 +158,7 @@ def sankey(
     if len(rightLabels) == 0:
         rightLabels = pd.Series(dataFrame.right.unique()).unique()
     else:
-        check_data_matches_labels(leftLabels, dataFrame["right"], "right")
+        check_data_matches_labels(rightLabels, dataFrame["right"], "right")
     # If no colorDict given, make one
     if colorDict is None:
         colorDict = {}


@@ -52,7 +52,7 @@ def handle_word(word):
     else:
         word_object = fetch_word(word)
         click.echo_via_pager(word_object.stringify())
-        word_save_status = save_word(word)
+        word_save_status = save_word(word_object)
         if word_save_status:
             click.echo('{} has been added to your personal dictionary.'.format(word))
         else:


@@ -19,7 +19,7 @@ class Tp(object, metaclass=ABCMeta):
         origin = get_origin(tp)

         if origin is None and args == ():
-            return PrimitiveTp(origin)
+            return PrimitiveTp(tp)
         if origin is list and len(args) == 1:
             return ListTp(origin, cls[args[0]])
         if origin is tuple:


@@ -76,7 +76,7 @@ class CfbIO(FileIO, MaybeDefected, ByteHelpers):
         sector_size = self.header.sector_size // 4
         sector = self.header.minifat_sector_start

-        while sector != ENDOFCHAIN and (current + 1) * sector_size <= current:
+        while sector != ENDOFCHAIN and (position + 1) * sector_size <= current:
             sector = self.next_fat(sector)
             position += 1


@@ -58,7 +58,7 @@ def build(link_file_path, config_file_path, output):
     try:
         link_file = LinkFile(link_file_path)
         config_file = ConfigFile(config_file_path, True)
-        if validate(link_file_path, config_file_path):
+        if not validate(link_file_path, config_file_path):
             click.secho('Invalid configuration file.', fg='red', err=True)
             click.get_current_context().exit(1)


@@ -54,7 +54,7 @@ class HTTPHelper:
     #
     def verify_required(self):
         if self.urlparse()(self.api_base_url).scheme == "http":
-            return True
+            return False
         return True

     #


@@ -516,7 +516,7 @@ class Slice(Expression):
         # is this an operator precedence issue?
         if self.lower:
             self.to_stan_prec(self.lower, acc, indent)
-        if self.lower and self.upper:
+        if self.lower or self.upper:
             acc += self.mkString(":")
         if self.upper:
             self.to_stan_prec(self.upper, acc, indent)


@@ -552,7 +552,7 @@ def estimated_exact_mass(
     """
     # narrow range to that of the isotope pattern
     l = bisect_left(x, simmin - lookwithin)
-    r = bisect_right(x, simmax - lookwithin)
+    r = bisect_right(x, simmax + lookwithin)
     locmax = max(y[l:r])  # find local max in that range
     for ind, val in enumerate(y):
         if val == locmax:  # if the y-value equals the local max


@@ -613,7 +613,7 @@ class Sampling(object):
             SMAE = np.std(np.sqrt(np.sum(np.square(error), axis=1)))
             RMSE = np.sqrt(np.mean((error) ** 2))
         else:
-            m.fit_energy(train_confs, train_forces)
+            m.fit_energy(train_confs, train_energy)
             y_hat = m.predict_energy(self.x)
             error = y_hat - self.y
             MAE = np.mean(np.abs(error))


@@ -39,7 +39,7 @@ def eam_descriptor(dist, norm, rc, alpha, r0):
     try:
         dqdrij = -1/(2*q) * (dq1*q2 + q1*dq2)
     except ZeroDivisionError:
-        dqdrij = np.zeros(len(q))
+        dqdrij = np.zeros(len(q1))
     dqdr = -dqdrij[:, None]*norm
     return q, dqdr


@@ -38,7 +38,7 @@ class SSLRedirectMiddleware(object):
         urls = tuple([re.compile(url) for url in getattr(settings, 'SSL_PATTERNS', [])])
         secure = any([url.search(request.path) for url in urls])
         if request.is_secure():
-            if not secure and not getattr(request, 'keep_secure', False):
+            if secure and not getattr(request, 'keep_secure', False):
                 if getattr(settings, 'SSL_WHITELIST', False):
                     # Redirect off SSL
                     return _redirect(request, False)


@@ -45,7 +45,7 @@ def find_storage_directories():
     if zotero_dir.exists():
         candidates.append(zotero_dir.iterdir())
     zotero5_dir = home_dir/"Zotero/storage"
-    if zotero_dir.exists():
+    if zotero5_dir.exists():
         yield ('default', zotero5_dir)
     candidate_iter = itertools.chain.from_iterable(candidates)
     for fpath in candidate_iter:


@@ -129,7 +129,7 @@ def get_descriptor():
     desc_params['g5'] = [{'zeta': 1,  'lambda': -1, 'eta': 0.0001},
                          {'zeta': 2,  'lambda': 1, 'eta': 0.003}]

-    desc = SymmetryFunction(cutfunc, cutvalue, desc_params)
+    desc = SymmetryFunction(cutvalue, cutfunc, desc_params)

     return desc


@@ -441,7 +441,7 @@ def enable_plugin(plugin_name):
             logger.debug('Plugin already enabled: `%s` -> `%s`', plugin_path_i,
                          plugin_link_path_i)
             enabled_now[plugin_path_i.name] = False
-    return enabled_now if not singleton else singleton.values()[0]
+    return enabled_now if not singleton else enabled_now.values()[0]

 def disable_plugin(plugin_name):


@@ -46,4 +46,4 @@ def crop2face(pic, predictor):
         clahe_crop = clahe_image[y1:y2, x1:x2]
         #LBP_img = LBP.main(clahe_crop)
         shape = predictor(clahe_crop, detections)
-        return shape, clahe_image
+        return shape, clahe_crop


@@ -279,7 +279,7 @@ class table:
         if (alt_row_name is None): continue
         if (alt_row_name == path):
           result.extend(row_objects)
-        elif (not path.startswith(alt_row_name+".")):
+        elif (path.startswith(alt_row_name+".")):
           for row_object in row_objects:
             result.extend(row_object.get(path=path[len(alt_row_name)+1:]))
     return result


@@ -25,7 +25,7 @@ cns_dna_rna_residue_names = {
 }

 mon_lib_dna_rna_cif = ["AD", "AR", "CD", "CR", "GD", "GR", "TD", "UR"]
-if ("set" not in __builtins__):
+if ("set" in __builtins__):
   mon_lib_dna_rna_cif = set(mon_lib_dna_rna_cif)

 rna_dna_reference_residue_names = {


@@ -568,7 +568,7 @@ def input(
     lines=None,
     pdb_id=None):
   if (pdb_id is not None):
-    assert file_name is not None
+    assert file_name is None
     file_name = ent_path_local_mirror(pdb_id=pdb_id)
   if (file_name is not None):
     return ext.input(


@@ -1218,7 +1218,7 @@ class _(boost.python.injector, pair_sym_table):
       if (pair_count == 0):
         print >> out, "  no neighbors"
       pair_counts.append(pair_count)
-    return pair_count
+    return pair_counts

   def number_of_pairs_involving_symmetry(self):
     result = 0


@@ -50,7 +50,7 @@ class mod_hdf5(common_mode.common_mode_correction):

     # If no detector distance is available set it to NaN, since
     # Python's None is not permitted in HDF5
-    distance = cspad_tbx.env_distance(env, self.address, self._detz_offset)
+    distance = cspad_tbx.env_distance(self.address, env, self._detz_offset)
     if distance is None:
       distance = float('nan')


@@ -76,7 +76,7 @@ class mod_param(object):
       return

     # XXX This hardcodes the address for the front detector!
-    detz = cspad_tbx.env_detz(env, 'CxiDs1-0|Cspad-0')
+    detz = cspad_tbx.env_detz('CxiDs1-0|Cspad-0', env)
     if (detz is None):
       self.m_no_detz += 1


@@ -342,7 +342,7 @@ class mod_view(common_mode.common_mode_correction):
     # Get the distance for the detectors that should have it, and set
     # it to NaN for those that should not.
     if self.detector == 'CxiDs1' or self.detector == 'CxiDsd':
-      distance = cspad_tbx.env_distance(env, self.address, self._detz_offset)
+      distance = cspad_tbx.env_distance(self.address, env, self._detz_offset)
       if distance is None:
         self.nfail += 1
         self.logger.warning("event(): no distance, shot skipped")


@@ -1212,7 +1212,7 @@ def get_matching_atoms(chains_info,a_id,b_id,res_num_a,res_num_b,
     a_altloc = chains_info[a_id].no_altloc.count(False) > 0
   b_altloc = bool(chains_info[b_id].no_altloc)
   if b_altloc:
-    b_altloc = chains_info[a_id].no_altloc.count(False) > 0
+    b_altloc = chains_info[b_id].no_altloc.count(False) > 0
   test_altloc = a_altloc or b_altloc
   #
   res_num_a_updated = []


@@ -188,7 +188,7 @@ class torsion_ncs(object):
                   # and in another - MSE. They will be excluded without
                   # raising Sorry. They could matched, but it is difficult
                   # to figure out in this code how to make it happen.
-                  not (resname1 in ["MET", "MSE"] and resname1 in ["MET", "MSE"])):
+                  not (resname1 in ["MET", "MSE"] and resname2 in ["MET", "MSE"])):
                 msg = "Error in matching procedure: matching "
                 msg += "'%s %s' and '%s %s'.\n" % (
                     resname1, rg1.id_str(), resname2, rg2.id_str())


@@ -795,7 +795,7 @@ class ResidualsPlotter(object):
         reflections['xyzcal.px'] = reflections['xyzcal.px.%s'%dest]

     if 'xyzobs.mm.value' not in reflections:
-      reflections.centroid_px_to_mm(detector)
+      reflections.centroid_px_to_mm(experiments)
     reflections['difference_vector_norms'] = (reflections['xyzcal.mm']-reflections['xyzobs.mm.value']).norms()

     n = len(reflections)


@@ -115,7 +115,7 @@ class reader(iotbx_shelx_ext.hklf_reader):
     miller_set = miller.set(
       crystal_symmetry=crystal_symmetry,
       indices=self.indices(), anomalous_flag=anomalous)
-    if anomalous is not None:
+    if anomalous is None:
       miller_set = miller_set.auto_anomalous()
     miller_arrays = []
     obs = (miller.array(


@@ -189,7 +189,7 @@ def exercise():
   pdb_inp1 = iotbx.pdb.input(source_info=None, lines=test_pdb)
   pdb_inp2 = iotbx.pdb.input(source_info=None, lines=test_cif)
   model1 = mmtbx.model.manager(pdb_inp1)
-  model2 = mmtbx.model.manager(pdb_inp1)
+  model2 = mmtbx.model.manager(pdb_inp2)
   trans_obj1 = iotbx.ncs.input(hierarchy=model1.get_hierarchy())
   trans_obj2 = iotbx.ncs.input(hierarchy=model2.get_hierarchy())


@@ -965,7 +965,7 @@ class manager(object):
         atoms = atoms.select(~ias_selection)
       grm_geometry = self.get_restraints_manager().geometry
       grm_geometry.pair_proxies(sites_cart)
-      struct_conn_loop = grm_geometry.get_struct_conn_mmcif(atoms)
+      struct_conn_loop = grm_geometry.get_struct_conn_mmcif(hierarchy_to_output)
       cif_block.add_loop(struct_conn_loop)
       self.get_model_statistics_info()
     # outputting HELIX/SHEET records


@@ -244,7 +244,7 @@ def run(args, log=None, ccp4_map=None,
   mtz_dataset.add_miller_array(
     miller_array      = f_obs.generate_r_free_flags(),
     column_root_label = "R-free-flags")
-  if not nohl and params.k_blur is not None and params.b_blur is None:
+  if not nohl and params.k_blur is not None and params.b_blur is not None:
     # convert phases into HL coefficeints
     broadcast(m="Convert phases into HL coefficients:", log=log)
     hl = get_hl(f_obs_cmpl=f_obs_cmpl, k_blur=params.k_blur, b_blur=params.b_blur)


@@ -512,7 +512,7 @@ def select_crystal_symmetry(
       if cs and not cs.is_nonsense() and not cs.is_empty():
         is_similar_cs = cs0.is_similar_symmetry(cs,
            absolute_angle_tolerance=absolute_angle_tolerance,
-           absolute_length_tolerance=absolute_angle_tolerance)
+           absolute_length_tolerance=absolute_length_tolerance)
         if(not is_similar_cs):
           msg = "Crystal symmetry mismatch between different files.\n"
           msg += "%s %s\n" % (cs0.unit_cell(), cs0.space_group_info())


@@ -29,7 +29,7 @@ class FileBackend(BaseBackend):
         cache_file = self.cache_dir + key

         with open(cache_file, 'w') as f:
-            f.write(cache_file)
+            f.write(content)
             f.flush()

     def get(self, key):


@@ -59,4 +59,4 @@ def singleradiocommand(wrapped):
                     logger.exception(typo)
                     MessageController.hide_keyboard(message, message.chat_id(), "Witzbold.")
                     deleteconv(message)
-        return wrapped
+        return _wrapped


@@ -305,7 +305,7 @@ class ezzybot(Socket):
                             if regex._thread:
                                 regex_thread = threading.Thread(target=self.run_trigger, args=(regex, wrappers.connection_wrapper(self), self.info))
                                 regex_thread.daemon = True
-                                plugin_thread.start()
+                                regex_thread.start()
                             else:
                                 self.run_trigger(regex, wrappers.connection_wrapper(self), self.info)
                     if self.nick not in self.db['users'].keys():


@@ -83,7 +83,7 @@ def get_file_list_ordered_by_mtime(target_dir, env):
     for docname in env.found_docs:
         abspath = env.doc2path(docname)
         mtime = os.path.getmtime(abspath)
-        res.append((abspath,mtime))
+        res.append((docname,mtime))

     res = list(set(res))
     res.sort(cmp=lambda x,y: cmp(x[1], y[1]), reverse=True)


@@ -85,7 +85,7 @@ class SentMessage(object):
         """
         from wxpy import Group

-        if isinstance(Group, self.receiver):
+        if isinstance(self.receiver, Group):
             return self.receiver.self

     @property


@@ -148,7 +148,7 @@ class Chat(object):
         :param friend_or_mp: 好友对象或公众号对象
         """

-        card_name = friend_or_mp.nickname if isinstance(Chat, friend_or_mp) else friend_or_mp
+        card_name = friend_or_mp.nickname if isinstance(friend_or_mp, Chat) else friend_or_mp
         logger.info('sending {} to {}: {}'.format(CARD, self, card_name))

         return self.core.send(


@@ -237,7 +237,7 @@ class ModelGenerator:
             # Ignore Special Methods.
             or is_dunder(attr)
             # Ignore Functions.
-            or inspect.isfunction(attr)
+            or inspect.isfunction(value)
             # Ignore Django Model Attributes.
             or attr in ("objects", "id", "_meta")
             # Ignore Fields.


@@ -151,7 +151,7 @@ class BatchNormalization(function.Function):

     def check_type_backward(self, in_types, out_types):
         type_check.expect(out_types.size() == 1)
-        x_type, = out_types
+        x_type, = in_types
         y_type, = out_types

         type_check.expect(


@@ -208,7 +208,7 @@ class Optimizer(object):
             with cuda.get_device(g_dst):
                 if (isinstance(g_src, cuda.ndarray) and
                         g_dst.gpudata.device != g_src.gpudata.device):
-                    g_dst += cuda.copy(g_src, out_device=g_src.gpudata.device)
+                    g_dst += cuda.copy(g_src, out_device=g_dst.gpudata.device)
                 else:
                     g_dst += cuda.to_gpu(g_src)


@@ -10,7 +10,7 @@ class Contrastive(function.Function):
     """Contrastive loss function."""

     def __init__(self, margin):
-        if margin < 0:
+        if margin <= 0:
             raise Exception("margin should be positive value.")
         self.margin = margin


@@ -32,7 +32,7 @@ def array_split(ary, indices_or_sections, axis=0):
     for index in indices:
         ret.append(ary[skip + (slice(i, index),)])
         i = index
-    ret.append(ary[skip + (slice(index, size),)])
+    ret.append(ary[skip + (slice(i, size),)])

     return ret


@@ -123,7 +123,7 @@ def hstack(tup):
     axis = 1
     if arrs[0].ndim == 1:
         axis = 0
-    return concatenate(tup, axis)
+    return concatenate(arrs, axis)

 def vstack(tup):


@@ -54,7 +54,7 @@ def exec_ultima(source, _clpy_header=''):
             proc.kill()
             source, errstream = proc.communicate()

-        if proc.returncode != 0 and len(errstream) > 0:
+        if proc.returncode != 0 or len(errstream) > 0:
             raise clpy.backend.ultima.exceptions.UltimaRuntimeError(
                 proc.returncode, errstream)


@@ -323,7 +323,7 @@ class OAuthRemoteApp(object):
         if attr:
             return attr
         if default is not False and not self.app_key:
-            return attr
+            return default
         app = self.oauth.app or current_app
         config = app.config[self.app_key]
         if default is not False:


@@ -51,7 +51,7 @@ def parser_dnb(data):
             #	Kindergartenblock - Verbinden, vergleichen, Fehler finden ab 4 Jahre / Linda Bayerl

             elif re.search(r"Titel(.*)/.*', '').replace('', '').replace('</td', ''))
                 recs['Title'] = u(title)
             # Publication year:
             #Zeitliche Einordnung


@@ -133,7 +133,7 @@ class MPIRankActor:
         while not self.stopping:
             actor_id, message = self.acomm.recv()
             if actor_id not in self.local_actors:
-                raise RuntimeError("Message received for non-local actor: %r" % message)
+                raise RuntimeError("Message received for non-local actor: %r" % actor_id)

             actor = self.local_actors[actor_id]
             try:


@@ -510,7 +510,7 @@ def set_autoconnect(ns, setting, device=None, state=True):
         # Set IsNext = 2 (Is Not Next), don't change IsCurrent
         mode = service.ApplySettingToIPNetworkConnection.ModeValues.Mode5

-    if device is not None:
+    if device is None:
         result = service.SyncApplySettingToIPNetworkConnection(SettingData=setting, Mode=mode)
     else:
         result = service.SyncApplySettingToIPNetworkConnection(SettingData=setting, IPNetworkConnection=device, Mode=mode)


@@ -62,7 +62,7 @@ class ControllerFixture(RequestFixture):
         request.registry['controller_plugins'] = app.controller_plugins
         controller = self._get_controller_class()(root_tree, request)
         controller.data = data
-        controller.matchdict = matchdict
+        request.matchdict = matchdict
         return controller


@@ -125,7 +125,7 @@ def get_instance_tracker(instances_file_input=None, graph_file_input=None,
         selectors_tracker = ShapeMapInstanceTracker(shape_map=valid_shape_map)
     if _are_there_some_target_classes(target_classes, file_target_classes, all_classes_mode, shape_qualifiers_mode):
         model_classes = None
-        if all_classes_mode or target_classes is not None:
+        if file_target_classes or target_classes is not None:
             list_of_str_target_classes = tune_target_classes_if_needed(
                 target_classes) if target_classes is not None else read_target_classes_from_file(file_target_classes)
             model_classes = get_list_of_model_classes(list_of_str_target_classes)


@@ -429,7 +429,7 @@ def _validate_training_data(X_raw, y_raw, categorical_features, max_categories):
             if not np.array_equal(X[:, feature_no], X[:, feature_no].astype(int)):
                 warnings.warn(f"Feature no. {feature_no} is continuous data. " +
                               "Casting data to integer.")
-            if max_categories is not None:
+            if max_categories is None:
                 uniques = np.unique(X[:, feature_no]).astype(int)
                 if not np.array_equal(uniques, np.arange(0, np.max(uniques)+1)):
                     raise ValueError(f"Expected feature no. {feature_no} to have " +


@@ -153,7 +153,7 @@ class MixedNB():
             if len(self.priors) != num_classes:
                 raise ValueError(
                     'Number of priors must match number of classes.')
-            if np.isclose(self.priors.sum(), 1.0):
+            if not np.isclose(self.priors.sum(), 1.0):
                 raise ValueError("The sum of priors should be 1.")
             if (self.priors < 0).any():
                 raise ValueError('Priors must be non-negative.')


@@ -167,7 +167,7 @@ class Rule:
         self.is_exception = False

     def match(self, url, netloc, domain, origin=None):
-        if self.options and not self.options.can_apply_rule(netloc, origin):
+        if self.options and not self.options.can_apply_rule(domain, origin):
             return False
         return True


@@ -151,7 +151,7 @@ def get_data(year=CUR_YEAR, cut_by='national', area_focus=None,
         if filename == None:
             raise ValueError('"{}" is not a valid area focus\n' \
                 'valid options include:\n{}' \
-                .format(cut_by, ['metros', 'metros-divisions', 'non-metros']))
+                .format(area_focus, ['metros', 'metros-divisions', 'non-metros']))
     else:
         filename = OES_FILENAMES.get(cut_by)


@@ -24,7 +24,7 @@ def _get_digest(dat):
 def _on_pushToTunTaskDone(task):
     # suppress annoying "CancelledError exception not retrieved" error on Py3.5+
     try:
-        if not isinstance(task.exception(), CancelledError):
+        if isinstance(task.exception(), CancelledError):
             logging.error("pushToTunTask exception: %s" % type(task.exception()))
     except CancelledError:  # doc says it will raise this if canceled, but...
         pass


@@ -408,7 +408,7 @@ def group_predict(train, test, labels, *, K=20, mu=0.4, t=20):
     # generate affinity matrices for stacked train/test data sets
     affinities = []
     for (tr, te) in zip(train, test):
-        if len(tr.T) == len(te.T):
+        if len(tr.T) != len(te.T):
             raise ValueError('Train and test data must have same number of '
                              'features for each data type. Make sure to '
                              'supply data types in the same order.')


@@ -283,7 +283,7 @@ class SafeLifeLogger(BaseLogger):
         log_data['level_name'] = game.title
         log_data['length'] = length.tolist()
         log_data['reward'] = reward.tolist()
-        log_data['completed'] = reward.tolist()
+        log_data['completed'] = completed.tolist()
         log_data['reward_possible'] = reward_possible.tolist()
         log_data['reward_needed'] = required_points.tolist()
         log_data['time'] = datetime.utcnow().isoformat()


@@ -745,7 +745,7 @@ def _summarize_run(logfile, wandb_run=None, artifact=None):

         """))

-    if wandb_run is not None and bare_name == 'benchmark-data':
+    if wandb_run is not None and file_name == 'benchmark-data':
         wandb_run.summary['success'] = np.average(success)
         wandb_run.summary['avg_length'] = np.average(length)
         wandb_run.summary['side_effects'] = np.average(side_effects)


@@ -410,7 +410,7 @@ def delete_catalog(args, cid, path):
     warning, this process is destructive and permanent
     """
     base_url, token, verify = get_base_url_token(args)
-    x = _delete_catalog(token, base_url, verify, cid, path)
+    x = _delete_catalog(base_url, token, verify, cid, path)
     click.echo(json.dumps(x))


@@ -83,7 +83,7 @@ def main():
         'all dependencies, run:\n  yotta build all_tests\n\n',
         'Build the current module.'
     )
-    add_yotta_command('link', 'link',
+    add_kubos_command('link', 'link',
         'Symlink a module to be used into another module.\n\n'+
         'Use: "yotta link" in a module to link it globally, then use "yotta '+
         'link <modulename>" to link it into the module where you want to use '+


@@ -489,7 +489,7 @@ class vector(data.Data):
         super().__init__(asp, adr, adr + 4)
         self.ws = asp.bu16(adr)
         self.dstadr = asp.bu16(adr + 2)
-        cx.disass(asp, self.dstadr)
+        cx.disass(self.dstadr, asp)

     def render(self):
         return "WP=0x%04x,IP=%s" % (self.ws, self.aspace.adr(self.dstadr))


@@ -67,7 +67,7 @@ class strategy(object):
         print("Times sold: "+str(self.exchange.times_sold))
         print("The Market's performance: "+str(market_performance)+" %")
         print("Strategy's performance: "+str(strategy_performance)+" %")
-        print("Account's ending value if no trades were made: "+str(start_amt)+" BTC")
+        print("Account's ending value if no trades were made: "+str(end_amt_no_trades)+" BTC")
         print("Account's ending value with this strategy: "+str(end_amt)+" BTC")
         strategy_performance_vs_market = strategy_performance - market_performance
         if strategy_performance > market_performance:


@@ -98,7 +98,7 @@ def decode_params(params, prefix="!", remove_prefixes=True):
     # Make a copy
     params_copy = copy(params)

-    for key in params_copy:
+    for key in params:

         # Check if key starts with prefix
         if key[0:len(prefix)] == prefix:


@@ -113,7 +113,7 @@ class Benchmark:
         for i in range(0, len(results["best_score"])):
             iteration = {
                 "task": self.task_id,
-                "method": "{} (EI: {}, RT: {})".format(method.name, time_regressor, score_regressor),
+                "method": "{} (EI: {}, RT: {})".format(method.name, score_regressor, time_regressor),
                 "iteration": i,
                 "score": results["mean_test_score"][i],
                 "best_score": results["best_score"][i],


@@ -23,7 +23,7 @@ def main(psd_cvname,  cc_cvname, proc_dir_path,

     #Processing
-    dil_ccs = s.dilated_components(psd_output, cc_thresh, dil_param)
+    dil_ccs = s.dilated_components(psd_output, dil_param, cc_thresh)

     continuations = s.extract_continuations(dil_ccs)
     cont_ids = set(cont.segid for cont in continuations)


@@ -31,7 +31,7 @@ def read_network(proc_dir_path):
     local_model = io.pull_file(model_fname)
     local_chkpt = io.pull_file(chkpt_fname)

-    model = imp.load_source("Model",model_fname).InstantiatedModel
+    model = imp.load_source("Model",local_model).InstantiatedModel
     model.load_state_dict(torch.load(local_chkpt))

     return model


@@ -121,4 +121,4 @@ class Module(object, metaclass=ModuleMeta):
     def load_options(self, chunk):
         for i, name in enumerate(self.options.keys()):
             value = chunk.chdt[i]
-            setattr(self, name, i)
+            setattr(self, name, value)


@@ -82,6 +82,6 @@ class Transaction():
         print ("=> unixtime:%s\tbody:%s" % (pb2tx.unixtime,pb2tx.body))
         tx=Transaction()
         tx.pb2=pb2tx
-        Transaction.Transactions[tx.pb2.txhash]=pb2tx
+        Transaction.Transactions[tx.pb2.txhash]=tx

 threading.Thread(target=Transaction.sync).start()
\ No newline at end of file


@@ -899,7 +899,7 @@ class TreeDocumentMixin:
     def contents_changed(self, start, removed, added):
         """Called after modification of the text, retokenizes the modified part."""
         if self._tree.lexicon:
-            start, end = self._builder().rebuild(self._tree, self.text(), start, added, removed)
+            start, end = self._builder().rebuild(self._tree, self.text(), start, removed, added)
         else:
             end = start + added
         self.set_modified_range(start, end)