id
stringlengths
25
27
content
stringlengths
190
15.4k
max_stars_repo_path
stringlengths
31
217
robustness-copilot_data_601
/** * Assign the partial charges, all existing charges are cleared. * Atom types must be assigned first. * * @param mol molecule * @return charges were assigned * @see #effectiveCharges(IAtomContainer) * @see #assignAtomTypes(IAtomContainer) */ public boolean partialCharges(IAtomContainer mol){ int[][] adjList = mol.getProperty(MMFF_ADJLIST_CACHE); GraphUtil.EdgeToBondMap edgeMap = mol.getProperty(MMFF_EDGEMAP_CACHE); if (adjList == null || edgeMap == null) throw new IllegalArgumentException("Invoke assignAtomTypes first."); effectiveCharges(mol); for (int v = 0; v < mol.getAtomCount(); v++) { IAtom atom = mol.getAtom(v); String symbType = atom.getAtomTypeName(); final int thisType = mmffParamSet.intType(symbType); if (thisType == 0) continue; double pbci = mmffParamSet.getPartialBondChargeIncrement(thisType).doubleValue(); for (int w : adjList[v]) { int otherType = mmffParamSet.intType(mol.getAtom(w).getAtomTypeName()); if (otherType == 0) continue; IBond bond = edgeMap.get(v, w); int bondCls = mmffParamSet.getBondCls(thisType, otherType, bond.getOrder().numeric(), bond.getProperty(MMFF_AROM) != null); BigDecimal bci = mmffParamSet.getBondChargeIncrement(bondCls, thisType, otherType); if (bci != null) { atom.setCharge(atom.getCharge() - bci.doubleValue()); } else { atom.setCharge(atom.getCharge() + (pbci - mmffParamSet.getPartialBondChargeIncrement(otherType).doubleValue())); } } } return true; }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/Mmff.java
robustness-copilot_data_602
/** * Judge whether job's sharding items are all completed. * * @return job's sharding items are all completed or not */ public boolean isAllCompleted(){ return jobNodeStorage.isJobNodeExisted(GuaranteeNode.COMPLETED_ROOT) && configService.load(false).getShardingTotalCount() <= jobNodeStorage.getJobNodeChildrenKeys(GuaranteeNode.COMPLETED_ROOT).size(); }
/elasticjob-lite/elasticjob-lite-core/src/main/java/org/apache/shardingsphere/elasticjob/lite/internal/guarantee/GuaranteeService.java
robustness-copilot_data_603
/** * Determines if two bonds have at least one atom in common. * * @param atom first bondA1 * @param bondB second bondA1 * @return the symbol of the common atom or "" if * the 2 bonds have no common atom */ private static boolean hasCommonAtom(IBond bondA, IBond bondB){ return bondA.contains(bondB.getBegin()) || bondA.contains(bondB.getEnd()); }
/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java
robustness-copilot_data_604
/** * Creates a {@link Config} object from {@link System#getProperties()}. * * @return Configuration object. */ public static Config systemProperties(){ return ConfigFactory.parseProperties(System.getProperties(), ConfigParseOptions.defaults().setOriginDescription("system properties")); }
/jooby/src/main/java/io/jooby/Environment.java
robustness-copilot_data_605
/** * Encodes the {@code centres[]} specified in the constructor as either * clockwise/anticlockwise or none. If there is a permutation parity but no * geometric parity then we can not encode the configuration and 'true' is * returned to indicate the perception is done. If there is no permutation * parity this may changed with the next {@code current[]} values and so * 'false' is returned. * *{@inheritDoc} */ public boolean encode(long[] current, long[] next){ int p = permutation.parity(current); // if is a permutation parity (all neighbors are different) if (p != 0) { // multiple with the geometric parity int q = geometric.parity() * p; // configure anticlockwise/clockwise if (q > 0) { for (int i : centres) { next[i] = current[i] * ANTICLOCKWISE; } } else if (q < 0) { for (int i : centres) { next[i] = current[i] * CLOCKWISE; } } // 0 parity ignored return true; } return false; }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometryEncoder.java
robustness-copilot_data_606
/** * Verify the geometric stereochemistry (cis/trans) of the double bond * {@code u1=u2} is preserved in the target when the {@code mapping} is * used. * * @param u1 one index of the double bond * @param u2 other index of the double bond * @param mapping mapping of vertices * @return the geometric configuration is preserved */ private boolean checkGeometric(int u1, int u2, int[] mapping){ int v1 = mapping[u1]; int v2 = mapping[u2]; if (targetTypes[v1] != Type.Geometric || targetTypes[v2] != Type.Geometric) return false; IDoubleBondStereochemistry queryElement = (IDoubleBondStereochemistry) queryElements[u1]; IDoubleBondStereochemistry targetElement = (IDoubleBondStereochemistry) targetElements[v1]; if (!targetElement.getStereoBond().contains(target.getAtom(v1)) || !targetElement.getStereoBond().contains(target.getAtom(v2))) return false; boolean swap = false; if (!targetElement.getStereoBond().getBegin().equals(target.getAtom(v1))) { int tmp = v1; v1 = v2; v2 = tmp; swap = true; } IBond[] queryBonds = queryElement.getBonds(); IBond[] targetBonds = targetElement.getBonds(); int p = parity(queryElement.getStereo()); int q = parity(targetElement.getStereo()); int uLeft = queryMap.get(queryBonds[0].getOther(query.getAtom(u1))); int uRight = queryMap.get(queryBonds[1].getOther(query.getAtom(u2))); int vLeft = targetMap.get(targetBonds[0].getOther(target.getAtom(v1))); int vRight = targetMap.get(targetBonds[1].getOther(target.getAtom(v2))); if (swap) { int tmp = vLeft; vLeft = vRight; vRight = tmp; } if (mapping[uLeft] != vLeft) p *= -1; if (mapping[uRight] != vRight) p *= -1; return p == q; }
/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/StereoMatch.java
robustness-copilot_data_607
/** * Make the symmetric group Sym(N) for N. That is, a group of permutations * that represents _all_ permutations of size N. * * @param size the size of the permutation * @return a group for all permutations of N */ public static PermutationGroup makeSymN(int size){ List<Permutation> generators = new ArrayList<Permutation>(); // p1 is (0, 1) int[] p1 = new int[size]; p1[0] = 1; p1[1] = 0; for (int i = 2; i < size; i++) { p1[i] = i; } // p2 is (1, 2, ...., n, 0) int[] p2 = new int[size]; p2[0] = 1; for (int i = 1; i < size - 1; i++) { p2[i] = i + 1; } p2[size - 1] = 0; generators.add(new Permutation(p1)); generators.add(new Permutation(p2)); return new PermutationGroup(size, generators); }
/tool/group/src/main/java/org/openscience/cdk/group/PermutationGroup.java
robustness-copilot_data_608
/** * Take the mapped extensions and organize them by individual extension. * @param configuredExtensions Map of extension mappings * @return Map with extension as keys */ private Map<String, String[]> formatExtensions(final Map<String, String> configuredExtensions){ final Map<String, String[]> extensions = new LinkedHashMap<>(); for (final Map.Entry<String, String> entry : configuredExtensions.entrySet()) { final String ext = entry.getKey().trim(); extensions.put(ext, entry.getValue().trim().split("&")); } return extensions; }
/bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/RefetchFlushContentBuilderImpl.java
robustness-copilot_data_609
/** * Returns a new IntColumn containing a value for each value in this column, truncating if * necessary. * * <p>A narrowing primitive conversion such as this one may lose information about the overall * magnitude of a numeric value and may also lose precision and range. Specifically, if the value * is too small (a negative value of large magnitude or negative infinity), the result is the * smallest representable value of type int. * * <p>Similarly, if the value is too large (a positive value of large magnitude or positive * infinity), the result is the largest representable value of type int. * * <p>Despite the fact that overflow, underflow, or other loss of information may occur, a * narrowing primitive conversion never results in a run-time exception. * * <p>A missing value in the receiver is converted to a missing value in the result */ public IntColumn asIntColumn(){ IntColumn result = IntColumn.create(name()); for (double d : data) { if (DoubleColumnType.valueIsMissing(d)) { result.appendMissing(); } else { result.append((int) d); } } return result; }
/core/src/main/java/tech/tablesaw/api/DoubleColumn.java
robustness-copilot_data_610
/** * Insert a string (str) into the trie. * * @param trie trie node * @param str the string to insert * @param i index in the string * @return a created child node or null */ private static Trie insert(Trie trie, String str, int i){ if (trie == null) trie = new Trie(); if (i == str.length()) { trie.token = str; } else { final char c = str.charAt(i); trie.children[c] = insert(trie.children[c], str, i + 1); } return trie; }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/AbbreviationLabel.java
robustness-copilot_data_611
/** * Check whether otherPath points to a location that is a child of this location. This is true * iff each element of this path is identical to the corresponding element in otherPath and * otherPath has length precisely greater by one. * <pre> * StatePath p1 = new StatePath("foo.bar"); * StatePath p2 = new StatePath("foo.bar.baz"); * StatePath p3 = new StatePath("foo.bar.baz.other"); * * p1.isParentOf(p1) // false * p1.isParentOf(p2) // true * p1.isParentOf(p3) // false * p2.isParentOf(p1) // false * p2.isParentOf(p2) // false * p2.isParentOf(p3) // true * </pre> * * @param otherPath * @return */ public boolean isParentOf(StatePath otherPath){ if (otherPath == null) { return false; } if ((_elements.size() + 1) != otherPath._elements.size()) { return false; } for (int i = 0; i < _elements.size(); i++) { if (_elements.get(i) != otherPath._elements.get(i)) { return false; } } return true; }
/modules/dcache-info/src/main/java/org/dcache/services/info/base/StatePath.java
robustness-copilot_data_612
/** * Returns a column containing integers representing the nth group (0-based) that a date falls * into. * * <p>Example: When Unit = ChronoUnit.DAY and n = 5, we form 5 day groups. a Date that is 2 days * after the start is assigned to the first ("0") group. A day 7 days after the start is assigned * to the second ("1") group. * * @param unit A ChronoUnit greater than or equal to a minute * @param n The number of units in each group. * @param start The starting point of the first group; group boundaries are offsets from this * point */ LongColumn timeWindow(ChronoUnit unit, int n, LocalDateTime start){ String newColumnName = "" + n + " " + unit.toString() + " window [" + name() + "]"; long packedStartDate = pack(start); LongColumn numberColumn = LongColumn.create(newColumnName, size()); for (int i = 0; i < size(); i++) { long packedDate = getLongInternal(i); long result; switch(unit) { case MINUTES: result = minutesUntil(packedDate, packedStartDate) / n; numberColumn.set(i, result); break; case HOURS: result = hoursUntil(packedDate, packedStartDate) / n; numberColumn.set(i, result); break; case DAYS: result = daysUntil(packedDate, packedStartDate) / n; numberColumn.set(i, result); break; case WEEKS: result = weeksUntil(packedDate, packedStartDate) / n; numberColumn.set(i, result); break; case MONTHS: result = monthsUntil(packedDate, packedStartDate) / n; numberColumn.set(i, result); break; case YEARS: result = yearsUntil(packedDate, packedStartDate) / n; numberColumn.set(i, result); break; default: throw new UnsupportedTemporalTypeException("The ChronoUnit " + unit + " is not supported for timeWindows on dates"); } } numberColumn.setPrintFormatter(NumberColumnFormatter.ints()); return numberColumn; }
/core/src/main/java/tech/tablesaw/columns/datetimes/DateTimeMapFunctions.java
robustness-copilot_data_613
/** * Builds the data file context for a tabular column. * * @param userId the unique identifier for the user * @param entityDetail the entity for which the context is build * * @return the data file context of the tabular column * * @throws OCFCheckedExceptionBase checked exception for reporting errors found when using OCF connectors */ private RelationshipsContext buildDataFileContext(String userId, EntityDetail entityDetail) throws OCFCheckedExceptionBase{ Set<GraphContext> context = new HashSet<>(); addConnectionToAssetContext(userId, entityDetail, context); EntityDetail fileFolder = handlerHelper.addContextForRelationships(userId, entityDetail, NESTED_FILE, context); addContextForFileFolder(userId, fileFolder, context); return new RelationshipsContext(entityDetail.getGUID(), context); }
/open-metadata-implementation/access-services/asset-lineage/asset-lineage-server/src/main/java/org/odpi/openmetadata/accessservices/assetlineage/handlers/AssetContextHandler.java
robustness-copilot_data_614
/** * Look for optional path parameter and expand the given pattern into multiple pattern. * * <pre> * /path =&gt; [/path] * /{id} =&gt; [/{id}] * /path/{id} =&gt; [/path/{id}] * * /{id}? =&gt; [/, /{id}] * /path/{id}? =&gt; [/path, /path/{id}] * /path/{id}/{start}?/{end}? =&gt; [/path/{id}, /path/{id}/{start}, /path/{id}/{start}/{end}] * /path/{id}?/suffix =&gt; [/path, /path/{id}, /path/suffix] * </pre> * * @param pattern Pattern. * @return One or more patterns. */ static List<String> expandOptionalVariables(@Nonnull String pattern){ if (pattern == null || pattern.isEmpty() || pattern.equals("/")) { return Collections.singletonList("/"); } int len = pattern.length(); AtomicInteger key = new AtomicInteger(); Map<Integer, StringBuilder> paths = new HashMap<>(); BiConsumer<Integer, StringBuilder> pathAppender = (index, segment) -> { for (int i = index; i < index - 1; i++) { paths.get(i).append(segment); } paths.computeIfAbsent(index, current -> { StringBuilder value = new StringBuilder(); if (current > 0) { StringBuilder previous = paths.get(current - 1); if (!previous.toString().equals("/")) { value.append(previous); } } return value; }).append(segment); }; StringBuilder segment = new StringBuilder(); boolean isLastOptional = false; for (int i = 0; i < len; ) { char ch = pattern.charAt(i); if (ch == '/') { if (segment.length() > 0) { pathAppender.accept(key.get(), segment); segment.setLength(0); } segment.append(ch); i += 1; } else if (ch == '{') { segment.append(ch); int curly = 1; int j = i + 1; while (j < len) { char next = pattern.charAt(j++); segment.append(next); if (next == '{') { curly += 1; } else if (next == '}') { curly -= 1; if (curly == 0) { break; } } } if (j < len && pattern.charAt(j) == '?') { j += 1; isLastOptional = true; if (paths.isEmpty()) { paths.put(0, new StringBuilder("/")); } pathAppender.accept(key.incrementAndGet(), segment); } else { isLastOptional = false; pathAppender.accept(key.get(), segment); } segment.setLength(0); i = j; } else { segment.append(ch); i += 1; } } if (paths.isEmpty()) { return Collections.singletonList(pattern); } if (segment.length() > 0) { pathAppender.accept(key.get(), segment); if (isLastOptional) { paths.put(key.incrementAndGet(), segment); } } return paths.values().stream().map(StringBuilder::toString).collect(Collectors.toList()); }
/jooby/src/main/java/io/jooby/Router.java
robustness-copilot_data_615
/** * Calculate the count of atoms of the largest chain in the supplied {@link IAtomContainer}. * * @param atomContainer The {@link IAtomContainer} for which this descriptor is to be calculated * @return the number of atoms in the largest chain of this AtomContainer * @see #setParameters */ public DescriptorValue calculate(IAtomContainer atomContainer){ if (checkRingSystem) Cycles.markRingAtomsAndBonds(atomContainer); final Set<IAtom> included = new HashSet<>(); for (IAtom atom : atomContainer.atoms()) { if (!atom.isInRing() && atom.getAtomicNumber() != 1) included.add(atom); } IAtomContainer subset = subsetMol(atomContainer, included); AllPairsShortestPaths apsp = new AllPairsShortestPaths(subset); int max = 0; int numAtoms = subset.getAtomCount(); for (int i = 0; i < numAtoms; i++) { for (int j = i + 1; j < numAtoms; j++) { int len = apsp.from(i).pathTo(j).length; if (len > max) max = len; } } return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new IntegerResult(max), getDescriptorNames()); }
/descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/LargestChainDescriptor.java
robustness-copilot_data_616
/** * Checks if the message starts with the given string. * * @param msg the message to check. * @param data the string to check the message with. Shall be shorter than 256 characters. * @param includeLength true if the string in the message is prefixed with the length, false if not. * @return true if the message starts with the given string, otherwise false. */ public static boolean startsWith(Msg msg, String data, boolean includeLength){ final int length = data.length(); assert (length < 256); int start = includeLength ? 1 : 0; if (msg.size() < length + start) { return false; } boolean comparison = includeLength ? length == (msg.get(0) & 0xff) : true; if (comparison) { for (int idx = start; idx < length; ++idx) { comparison = (msg.get(idx) == data.charAt(idx - start)); if (!comparison) { break; } } } return comparison; }
/src/main/java/zmq/io/Msgs.java
robustness-copilot_data_617
/** * Evaluate the 12 descriptors used to characterize the 3D shape of a molecule. * * @param atomContainer The molecule to consider, should have 3D coordinates * @return A 12 element array containing the descriptors. * @throws CDKException if there are no 3D coordinates */ public static float[] generateMoments(IAtomContainer atomContainer) throws CDKException{ // lets check if we have 3D coordinates Iterator<IAtom> atoms; int natom = atomContainer.getAtomCount(); Point3d ctd = getGeometricCenter(atomContainer); Point3d cst = new Point3d(); Point3d fct = new Point3d(); Point3d ftf = new Point3d(); double[] distCtd = new double[natom]; double[] distCst = new double[natom]; double[] distFct = new double[natom]; double[] distFtf = new double[natom]; atoms = atomContainer.atoms().iterator(); int counter = 0; double min = Double.MAX_VALUE; double max = Double.MIN_VALUE; // eval dist to centroid while (atoms.hasNext()) { IAtom atom = atoms.next(); Point3d p = atom.getPoint3d(); double d = p.distance(ctd); distCtd[counter++] = d; if (d < min) { cst.x = p.x; cst.y = p.y; cst.z = p.z; min = d; } if (d > max) { fct.x = p.x; fct.y = p.y; fct.z = p.z; max = d; } } // eval dist to cst atoms = atomContainer.atoms().iterator(); counter = 0; while (atoms.hasNext()) { IAtom atom = atoms.next(); Point3d p = atom.getPoint3d(); double d = p.distance(cst); distCst[counter++] = d; } // eval dist to fct atoms = atomContainer.atoms().iterator(); counter = 0; max = Double.MIN_VALUE; while (atoms.hasNext()) { IAtom atom = atoms.next(); Point3d p = atom.getPoint3d(); double d = p.distance(fct); distFct[counter++] = d; if (d > max) { ftf.x = p.x; ftf.y = p.y; ftf.z = p.z; max = d; } } // eval dist to ftf atoms = atomContainer.atoms().iterator(); counter = 0; while (atoms.hasNext()) { IAtom atom = atoms.next(); Point3d p = atom.getPoint3d(); double d = p.distance(ftf); distFtf[counter++] = d; } float[] moments = new float[12]; float mean = mu1(distCtd); float sigma2 = mu2(distCtd, mean); float skewness = mu3(distCtd, mean, Math.sqrt(sigma2)); moments[0] = mean; moments[1] = sigma2; moments[2] = skewness; mean = mu1(distCst); sigma2 = mu2(distCst, mean); skewness = mu3(distCst, mean, Math.sqrt(sigma2)); moments[3] = mean; moments[4] = sigma2; moments[5] = skewness; mean = mu1(distFct); sigma2 = mu2(distFct, mean); skewness = mu3(distFct, mean, Math.sqrt(sigma2)); moments[6] = mean; moments[7] = sigma2; moments[8] = skewness; mean = mu1(distFtf); sigma2 = mu2(distFtf, mean); skewness = mu3(distFtf, mean, Math.sqrt(sigma2)); moments[9] = mean; moments[10] = sigma2; moments[11] = skewness; return moments; }
/descriptor/fingerprint/src/main/java/org/openscience/cdk/similarity/DistanceMoment.java
robustness-copilot_data_618
/** * For JPEG images, this method behaves similar to {@link Layer#write(String, double, OutputStream)}. The major * difference is that it uses progressive encoding. * * @param layer the layer with the image to write to the output stream * @param quality JPEG compression quality between 0 and 1 * @param out target output stream * @throws IOException if anything goes wrong */ public static void write(Layer layer, double quality, OutputStream out) throws IOException{ ImageWriter writer = null; ImageOutputStream imageOut = null; try { ImageWriteParam iwp = new JPEGImageWriteParam(null); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setProgressiveMode(ImageWriteParam.MODE_DEFAULT); iwp.setCompressionQuality((float) quality); writer = ImageIO.getImageWritersBySuffix("jpeg").next(); imageOut = ImageIO.createImageOutputStream(out); writer.setOutput(imageOut); BufferedImage image = getRgbImage(layer); writer.write(null, new IIOImage(image, null, null), iwp); } finally { if (writer != null) { writer.dispose(); } if (imageOut != null) { try { imageOut.close(); } catch (IOException e) { // ignore } } } }
/bundle/src/main/java/com/adobe/acs/commons/images/impl/ProgressiveJpeg.java
robustness-copilot_data_619
/** * For a given molecule, determines its fingerprints and uses them to calculate a Bayesian prediction. Note that this * value is unscaled, and so it only has relative meaning within the confines of the model, i.e. higher is more likely to * be active. * * @param mol molecular structure which cannot be blank or null * @return predictor value */ public double predict(IAtomContainer mol) throws CDKException{ if (mol == null || mol.getAtomCount() == 0) throw new CDKException("Molecule cannot be blank or null."); CircularFingerprinter circ = new CircularFingerprinter(classType); circ.setPerceiveStereo(optPerceiveStereo); circ.calculate(mol); final int AND_BITS = folding - 1; Set<Integer> hashset = new HashSet<Integer>(); for (int n = circ.getFPCount() - 1; n >= 0; n--) { int code = circ.getFP(n).hashCode; if (folding > 0) code &= AND_BITS; hashset.add(code); } double val = 0; for (int h : hashset) { Double c = contribs.get(h); if (c != null) val += c; } return val; }
/tool/model/src/main/java/org/openscience/cdk/fingerprint/model/Bayesian.java
robustness-copilot_data_620
/** * Optimised method for reading a integer from 3 characters in a string at a * specified index. MDL V2000 Molfile make heavy use of the 3 character ints * in the atom/bond and property blocks. The integer may be signed and * pre/post padded with white space. * * @param line input * @param index start index * @return the value specified in the string */ private static int readMolfileInt(final String line, final int index){ int sign = 1; int result = 0; char c; switch((c = line.charAt(index))) { case ' ': break; case '-': sign = -1; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': result = (c - '0'); break; default: return 0; } if (index + 1 == line.length()) return sign * result; switch((c = line.charAt(index + 1))) { case ' ': if (result > 0) return sign * result; break; case '-': if (result > 0) return sign * result; sign = -1; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': result = (result * 10) + (c - '0'); break; default: return sign * result; } if (index + 2 == line.length()) return sign * result; switch((c = line.charAt(index + 2))) { case ' ': if (result > 0) return sign * result; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': result = (result * 10) + (c - '0'); break; default: return sign * result; } return sign * result; }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Reader.java
robustness-copilot_data_621
/** * Process changes to the human enitity's armor, and update the entity's armor attributes * accordingly. */ private void processArmorChanges(){ GlowPlayer player = null; if (this instanceof GlowPlayer) { player = ((GlowPlayer) this); } boolean armorUpdate = false; List<EquipmentMonitor.Entry> armorChanges = getEquipmentMonitor().getArmorChanges(); if (armorChanges.size() > 0) { for (EquipmentMonitor.Entry entry : armorChanges) { if (player != null && needsArmorUpdate) { player.getSession().send(new EntityEquipmentMessage(0, entry.slot, entry.item)); } armorUpdate = true; } } if (armorUpdate) { getAttributeManager().setProperty(AttributeManager.Key.KEY_ARMOR, ArmorConstants.getDefense(getEquipment().getArmorContents())); getAttributeManager().setProperty(AttributeManager.Key.KEY_ARMOR_TOUGHNESS, ArmorConstants.getToughness(getEquipment().getArmorContents())); } needsArmorUpdate = true; }
/src/main/java/net/glowstone/entity/GlowHumanEntity.java
robustness-copilot_data_622
/** * Multiply this permutation by another such that for all i, * this[i] = this[other[i]]. * * @param other the other permutation to use * @return a new permutation with the result of multiplying the permutations */ public Permutation multiply(Permutation other){ Permutation newPermutation = new Permutation(values.length); for (int i = 0; i < values.length; i++) { newPermutation.values[i] = this.values[other.values[i]]; } return newPermutation; }
/tool/group/src/main/java/org/openscience/cdk/group/Permutation.java
robustness-copilot_data_623
/** * Builds the relational table context for a relational column. * * @param userId the unique identifier for the user * @param entityDetail the entity for which the context is build * * @return the relational table context of the relational column * * @throws OCFCheckedExceptionBase checked exception for reporting errors found when using OCF connectors */ private RelationshipsContext buildRelationalTableContext(String userId, EntityDetail entityDetail) throws OCFCheckedExceptionBase{ Set<GraphContext> context = new HashSet<>(); EntityDetail schemaType = handlerHelper.addContextForRelationships(userId, entityDetail, ATTRIBUTE_FOR_SCHEMA, context); EntityDetail deployedSchemaType = handlerHelper.addContextForRelationships(userId, schemaType, ASSET_SCHEMA_TYPE, context); EntityDetail database = handlerHelper.addContextForRelationships(userId, deployedSchemaType, DATA_CONTENT_FOR_DATA_SET, context); if (database != null) { addConnectionToAssetContext(userId, database, context); } return new RelationshipsContext(entityDetail.getGUID(), context); }
/open-metadata-implementation/access-services/asset-lineage/asset-lineage-server/src/main/java/org/odpi/openmetadata/accessservices/assetlineage/handlers/AssetContextHandler.java
robustness-copilot_data_624
/** * We create a new Plan which contains only the Leg that should be replanned and its previous and next * Activities. By doing so the PlanAlgorithm will only change the Route of that Leg. * * Use currentNodeIndex from a DriverAgent if possible! * * Otherwise code it as following: * startLink - Node1 - routeLink1 - Node2 - routeLink2 - Node3 - endLink * The currentNodeIndex has to Point to the next Node * (which is the endNode of the current Link) */ public boolean replanCurrentLegRoute(Leg leg, Person person, int currentLinkIndex, double time){ Route route = leg.getRoute(); if (!(route instanceof NetworkRoute)) { log.warn("route not instance of NetworkRoute"); return false; } return relocateCurrentLegRoute(leg, person, currentLinkIndex, route.getEndLinkId(), time); }
/matsim/src/main/java/org/matsim/withinday/utils/EditRoutes.java
robustness-copilot_data_625
/** * Scale a vector by a given factor, the input vector is not modified. * * @param vector a vector to scale * @param factor how much the input vector should be scaled * @return scaled vector */ static Vector2d scale(final Tuple2d vector, final double factor){ final Vector2d cpy = new Vector2d(vector); cpy.scale(factor); return cpy; }
/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/VecmathUtil.java
robustness-copilot_data_626
/** * Consider if a column is seen twice then that column type should be * considered an array. Because String is a default assumption when no type * is specified, any redefinition of a column to a more specific type will * be then assumed for that property altogether. * * @param a * @param b * @return */ private Optional<Class> upgradeToArray(Optional<Class> a, Optional<Class> b){ if (!a.isPresent()) { return b; } if (!b.isPresent()) { return a; } if (a.get().equals(b.get()) || b.get() == Object.class) { return getArrayType(a); } else { return getArrayType(b); } }
/bundle/src/main/java/com/adobe/acs/commons/data/Spreadsheet.java
robustness-copilot_data_627
/** * Creates a WlsClusterConfig object using an "clusters" item parsed from JSON result from WLS * REST call. * * @param clusterConfigMap Map containing "cluster" item parsed from JSON result from WLS REST * call * @param serverTemplates Map containing all server templates configuration read from the WLS * domain * @param domainName Name of the WLS domain that this WLS cluster belongs to * @return A new WlsClusterConfig object created based on the JSON result */ static WlsClusterConfig create(Map<String, Object> clusterConfigMap, Map<String, WlsServerConfig> serverTemplates, String domainName){ String clusterName = (String) clusterConfigMap.get("name"); WlsDynamicServersConfig dynamicServersConfig = WlsDynamicServersConfig.create((Map<String, Object>) clusterConfigMap.get("dynamicServers"), serverTemplates, clusterName, domainName); // set dynamicServersConfig only if the cluster contains dynamic servers, i.e., its dynamic // servers configuration // contains non-null server template name if (dynamicServersConfig.getServerTemplate() == null) { dynamicServersConfig = null; } return new WlsClusterConfig(clusterName, dynamicServersConfig); }
/operator/src/main/java/oracle/kubernetes/operator/wlsconfig/WlsClusterConfig.java
robustness-copilot_data_628
/** * Searches the provided fields weighted by their boosts, using multiple threads. * Batch version of {@link #searchFields(String, Map, int)}. * * @param queries list of queries * @param qids list of unique query ids * @param k number of hits * @param threads number of threads * @param fields map of fields to search with weights * @return a map of query id to search results */ public Map<String, Result[]> batchSearchFields(List<String> queries, List<String> qids, int k, int threads, Map<String, Float> fields){ QueryGenerator generator = new BagOfWordsQueryGenerator(); return batchSearchFields(generator, queries, qids, k, threads, fields); }
/src/main/java/io/anserini/search/SimpleSearcher.java
robustness-copilot_data_629
/** * Use this to remove a ChemObjectListener from the ListenerList of this * IChemObject. It will then not be notified of change in this object anymore. * *@param col The ChemObjectListener to be removed *@see #addListener */ public void removeListener(IChemObjectListener col){ if (chemObjectListeners == null) { return; } List<IChemObjectListener> listeners = lazyChemObjectListeners(); if (listeners.contains(col)) { listeners.remove(col); } }
/base/data/src/main/java/org/openscience/cdk/ChemObject.java
robustness-copilot_data_630
/** * Generates a checksum for a single node and its node sub-system, respecting the options. * @param aggregateNodePath the absolute path of the node being aggregated into a checksum * @param node the node whose subsystem to create a checksum for * @param options the {@link ChecksumGeneratorOptions} options * @return a map containing 1 entry in the form [ node.getPath() ] : [ CHECKSUM OF NODE SYSTEM ] * @throws RepositoryException * @throws IOException */ protected String generatedNodeChecksum(final String aggregateNodePath, final Node node, final ChecksumGeneratorOptions options) throws RepositoryException, IOException{ if (isExcludedSubTree(node, options)) { return ""; } final Map<String, String> checksums = new LinkedHashMap<>(); if (!isExcludedNodeName(node, options)) { final String checksum = generatePropertyChecksums(aggregateNodePath, node, options); if (checksum != null) { checksums.put(getChecksumKey(aggregateNodePath, node.getPath()), checksum); } } final Map<String, String> lexicographicallySortedChecksums = new TreeMap<>(); final boolean hasOrderedChildren = hasOrderedChildren(node); final NodeIterator children = node.getNodes(); while (children.hasNext()) { final Node child = children.nextNode(); if (isExcludedSubTree(child, options)) { } else if (!isExcludedNodeType(child, options)) { if (hasOrderedChildren) { final String checksum = generatedNodeChecksum(aggregateNodePath, child, options); if (checksum != null) { checksums.put(getChecksumKey(aggregateNodePath, child.getPath()), checksum); log.debug("Aggregated Ordered Node: {} ~> {}", getChecksumKey(aggregateNodePath, child.getPath()), checksum); } } else { final String checksum = generatedNodeChecksum(aggregateNodePath, child, options); if (checksum != null) { lexicographicallySortedChecksums.put(getChecksumKey(aggregateNodePath, child.getPath()), checksum); log.debug("Aggregated Unordered Node: {} ~> {}", getChecksumKey(aggregateNodePath, child.getPath()), checksum); } } } } if (!hasOrderedChildren && lexicographicallySortedChecksums.size() > 0) { checksums.putAll(lexicographicallySortedChecksums); } final String nodeChecksum = aggregateChecksums(checksums); log.debug("Node [ {} ] has a aggregated checksum of [ {} ]", getChecksumKey(aggregateNodePath, node.getPath()), nodeChecksum); return nodeChecksum; }
/bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/ChecksumGeneratorImpl.java
robustness-copilot_data_631
/** * Applies the given function to a float subtag if it is present. * * @param key the key to look up * @param consumer the function to apply * @return true if the tag exists and was passed to the consumer; false otherwise */ public boolean readFloat(@NonNls String key, FloatConsumer consumer){ if (isFloat(key)) { consumer.accept(getFloat(key)); return true; } return false; }
/src/main/java/net/glowstone/util/nbt/CompoundTag.java
robustness-copilot_data_632
/** * Finishes the calculation of the plans' scores and assigns the new scores * to the plans if desired. */ public void finish(){ if (iteration == -1) { throw new RuntimeException("Please initialize me before the iteration starts."); } controlerListenerManager.fireControlerAfterMobsimEvent(iteration, isLastIteration); scoringFunctionsForPopulation.finishScoringFunctions(); newScoreAssigner.assignNewScores(this.iteration, scoringFunctionsForPopulation, population); finished = true; }
/matsim/src/main/java/org/matsim/core/scoring/EventsToScore.java
robustness-copilot_data_633
/** * Factory method for constructing {@link ObjectReader} that will * read or update instances of a type {@code List<type>}. * Functionally same as: *<pre> * readerFor(new TypeReference&lt;List&lt;type&gt;&gt;() { }); *</pre> * * @since 2.11 */ public ObjectReader readerForListOf(Class<?> type){ return _newReader(getDeserializationConfig(), _typeFactory.constructCollectionType(List.class, type), null, null, _injectableValues); }
/src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java
robustness-copilot_data_634
/** * * Creates a new instance of Post Filter and removes * redundant mapping(s). * * @param mappings * @return Filtered non-redundant mappings */ public static List<Map<Integer, Integer>> filter(List<List<Integer>> mappings){ FinalMappings finalMappings = FinalMappings.getInstance(); if (mappings != null && !mappings.isEmpty()) { finalMappings.set(removeRedundantMapping(mappings)); mappings.clear(); } else { finalMappings.set(new ArrayList<Map<Integer, Integer>>()); } return finalMappings.getFinalMapping(); }
/legacy/src/main/java/org/openscience/cdk/smsd/filters/PostFilter.java
robustness-copilot_data_635
/** * Export an {@link OpenAPI} model to the given format. * * @param openAPI Model. * @param format Format. * @throws IOException * @return Output file. */ public Path export(@Nonnull OpenAPI openAPI, @Nonnull Format format) throws IOException{ Path output; if (openAPI instanceof OpenAPIExt) { String source = ((OpenAPIExt) openAPI).getSource(); String[] names = source.split("\\."); output = Stream.of(names).limit(names.length - 1).reduce(outputDir, Path::resolve, Path::resolve); String appname = names[names.length - 1]; if (appname.endsWith("Kt")) { appname = appname.substring(0, appname.length() - 2); } output = output.resolve(appname + "." + format.extension()); } else { output = outputDir.resolve("openapi." + format.extension()); } if (!Files.exists(output.getParent())) { Files.createDirectories(output.getParent()); } String content = format.toString(this, openAPI); Files.write(output, Collections.singleton(content)); return output; }
/modules/jooby-openapi/src/main/java/io/jooby/openapi/OpenAPIGenerator.java
robustness-copilot_data_636
/** * Creates a sorted list of lanes for a link. * @param link * @param lanesToLinkAssignment * @return sorted list with the most upstream lane at the first position. */ public static List<ModelLane> createLanes(Link link, LanesToLinkAssignment lanesToLinkAssignment){ List<ModelLane> queueLanes = new ArrayList<>(); List<Lane> sortedLanes = new ArrayList<>(lanesToLinkAssignment.getLanes().values()); sortedLanes.sort(Comparator.comparingDouble(Lane::getStartsAtMeterFromLinkEnd).thenComparing((l1, l2) -> { boolean l1Outgoing = l1.getToLinkIds() != null && !l1.getToLinkIds().isEmpty(); boolean l2Outgoing = l2.getToLinkIds() != null && !l2.getToLinkIds().isEmpty(); if (l1Outgoing && !l2Outgoing) return -1; else if (l2Outgoing && !l1Outgoing) return 1; else return 0; })); Collections.reverse(sortedLanes); List<ModelLane> laneList = new LinkedList<>(); Lane firstLane = sortedLanes.remove(0); if (firstLane.getStartsAtMeterFromLinkEnd() != link.getLength()) { throw new IllegalStateException("First Lane Id " + firstLane.getId() + " on Link Id " + link.getId() + "isn't starting at the beginning of the link!"); } ModelLane firstQLane = new ModelLane(firstLane); laneList.add(firstQLane); Stack<ModelLane> laneStack = new Stack<>(); while (!laneList.isEmpty()) { ModelLane lastQLane = laneList.remove(0); laneStack.push(lastQLane); queueLanes.add(lastQLane); List<Id<Lane>> toLaneIds = lastQLane.getLaneData().getToLaneIds(); double nextMetersFromLinkEnd = 0.0; double laneLength = 0.0; if (toLaneIds != null && (!toLaneIds.isEmpty())) { for (Id<Lane> toLaneId : toLaneIds) { Lane currentLane = lanesToLinkAssignment.getLanes().get(toLaneId); nextMetersFromLinkEnd = currentLane.getStartsAtMeterFromLinkEnd(); ModelLane currentQLane = new ModelLane(currentLane); laneList.add(currentQLane); lastQLane.addAToLane(currentQLane); } laneLength = lastQLane.getLaneData().getStartsAtMeterFromLinkEnd() - nextMetersFromLinkEnd; lastQLane.setEndsAtMetersFromLinkEnd(nextMetersFromLinkEnd); } else { laneLength = lastQLane.getLaneData().getStartsAtMeterFromLinkEnd(); lastQLane.setEndsAtMetersFromLinkEnd(0.0); } lastQLane.setLength(laneLength); } while (!laneStack.isEmpty()) { ModelLane qLane = laneStack.pop(); if (qLane.getToLanes() == null || (qLane.getToLanes().isEmpty())) { for (Id<Link> toLinkId : qLane.getLaneData().getToLinkIds()) { qLane.addDestinationLink(toLinkId); } } else { for (ModelLane subsequentLane : qLane.getToLanes()) { for (Id<Link> toLinkId : subsequentLane.getDestinationLinkIds()) { qLane.addDestinationLink(toLinkId); } } } } Collections.sort(queueLanes, new Comparator<ModelLane>() { @Override public int compare(ModelLane o1, ModelLane o2) { if (o1.getEndsAtMeterFromLinkEnd() < o2.getEndsAtMeterFromLinkEnd()) { return -1; } else if (o1.getEndsAtMeterFromLinkEnd() > o2.getEndsAtMeterFromLinkEnd()) { return 1; } else { return 0; } } }); return queueLanes; }
/matsim/src/main/java/org/matsim/lanes/LanesUtils.java
robustness-copilot_data_637
/** * Helper method that removes empty hooks from passed array and packs it into new collection. * * @param hooks hooks to be reduced * @return no empty hooks */ public static List<Hook> eliminateEmptyHooks(Hook[] hooks){ return Arrays.asList(hooks).stream().filter(Hook::hasContent).collect(Collectors.toList()); }
/src/main/java/net/masterthought/cucumber/util/Util.java
robustness-copilot_data_638
/** * Check if a public key is in the certificate store. * @param publicKey needs to be a 32 byte array representing the public key */ public boolean containsPublicKey(byte[] publicKey){ Utils.checkArgument(publicKey.length == 32, "publickey needs to have a size of 32 bytes. got only " + publicKey.length); return containsPublicKey(ZMQ.Curve.z85Encode(publicKey)); }
/src/main/java/org/zeromq/ZCertStore.java
robustness-copilot_data_639
/** * Verifies that clazz implements Callable<? extends Serializable> and casts it to that type. * * @param clazz The clazz of the command object * @return clazz cast to Callable<? extends Serializable> */ private Class<? extends Callable<? extends Serializable>> cast(Class<?> clazz){ if (EXPECTED_TYPE.isSupertypeOf(clazz)) { return (Class<? extends Callable<? extends Serializable>>) clazz.asSubclass(Callable.class); } throw new RuntimeException("This is a bug. Please notify support@dcache.org (" + clazz + " does not implement Callable<? extends Serializable>)."); }
/modules/common-cli/src/main/java/org/dcache/util/cli/AnnotatedCommandScanner.java
robustness-copilot_data_640
/** * Compare the values of the supplied object with those stored in the current object. * * @param objectToCompare supplied object * @return boolean result of comparison */ public boolean equals(Object objectToCompare){ if (this == objectToCompare) { return true; } if (objectToCompare == null || getClass() != objectToCompare.getClass()) { return false; } Annotation that = (Annotation) objectToCompare; return confidenceLevel == that.confidenceLevel && numAttachedAnnotations == that.numAttachedAnnotations && Objects.equals(annotationType, that.annotationType) && Objects.equals(summary, that.summary) && Objects.equals(expression, that.expression) && Objects.equals(explanation, that.explanation) && Objects.equals(analysisStep, that.analysisStep) && Objects.equals(jsonProperties, that.jsonProperties) && annotationStatus == that.annotationStatus && Objects.equals(reviewDate, that.reviewDate) && Objects.equals(steward, that.steward) && Objects.equals(reviewComment, that.reviewComment) && Objects.equals(additionalProperties, that.additionalProperties); }
/open-metadata-implementation/frameworks/open-discovery-framework/src/main/java/org/odpi/openmetadata/frameworks/discovery/properties/Annotation.java
robustness-copilot_data_641
/** * Methods that takes a ring of which all bonds are aromatic, and assigns single * and double bonds. It does this in a non-general way by looking at the ring * size and take everything as a special case. * * @param ring Ring to dearomatize * @return False if it could not convert the aromatic ring bond into single and double bonds */ public static boolean deAromatize(IRing ring){ boolean allaromatic = true; for (int i = 0; i < ring.getBondCount(); i++) { if (!ring.getBond(i).getFlag(CDKConstants.ISAROMATIC)) allaromatic = false; } if (!allaromatic) return false; for (int i = 0; i < ring.getBondCount(); i++) { if (ring.getBond(i).getFlag(CDKConstants.ISAROMATIC)) ring.getBond(i).setOrder(IBond.Order.SINGLE); } boolean result = false; IMolecularFormula formula = MolecularFormulaManipulator.getMolecularFormula(ring); // Map elementCounts = new MFAnalyser(ring).getFormulaHashtable(); if (ring.getRingSize() == 6) { if (MolecularFormulaManipulator.getElementCount(formula, new Element("C")) == 6) { result = DeAromatizationTool.deAromatizeBenzene(ring); } else if (MolecularFormulaManipulator.getElementCount(formula, new Element("C")) == 5 && MolecularFormulaManipulator.getElementCount(formula, new Element("N")) == 1) { result = DeAromatizationTool.deAromatizePyridine(ring); } } if (ring.getRingSize() == 5) { if (MolecularFormulaManipulator.getElementCount(formula, new Element("C")) == 4 && MolecularFormulaManipulator.getElementCount(formula, new Element("N")) == 1) { result = deAromatizePyrolle(ring); } } return result; }
/legacy/src/main/java/org/openscience/cdk/tools/DeAromatizationTool.java
robustness-copilot_data_642
/** * Encodes the given string in such a way that it no longer contains * characters that have a special meaning in xml. * * @see <a href="http://www.w3.org/International/questions/qa-escapes#use">http://www.w3.org/International/questions/qa-escapes#use</a> * @param attributeValue * @return String with some characters replaced by their xml-encoding. */ private String encodeAttributeValue(final String attributeValue){ if (attributeValue == null) { return null; } int len = attributeValue.length(); boolean encode = false; for (int pos = 0; pos < len; pos++) { char ch = attributeValue.charAt(pos); if (ch == '<') { encode = true; break; } else if (ch == '>') { encode = true; break; } else if (ch == '\"') { encode = true; break; } else if (ch == '&') { encode = true; break; } } if (encode) { StringBuilder bf = new StringBuilder(attributeValue.length() + 30); for (int pos = 0; pos < len; pos++) { char ch = attributeValue.charAt(pos); if (ch == '<') { bf.append("&lt;"); } else if (ch == '>') { bf.append("&gt;"); } else if (ch == '\"') { bf.append("&quot;"); } else if (ch == '&') { bf.append("&amp;"); } else { bf.append(ch); } } return bf.toString(); } return attributeValue; }
/matsim/src/main/java/org/matsim/core/events/algorithms/EventWriterXML.java
robustness-copilot_data_643
/** * Returns the highest index at which the specific IAtomContainer appears in the list or -1 if is not found. * * A given IAtomContainer will occur in the list if the title matches the stored title for * the conformers in this container and if the coordinates for each atom in the specified molecule * are equal to the coordinates of the corresponding atoms in a conformer. * * @param o The IAtomContainer whose presence is being tested * @return The index where o was found */ public int lastIndexOf(Object o){ IAtomContainer atomContainer = (IAtomContainer) o; if (!atomContainer.getTitle().equals(title)) return -1; if (atomContainer.getAtomCount() != coordinates.get(0).length) return -1; boolean coordsMatch; for (int j = coordinates.size() - 1; j >= 0; j--) { Point3d[] coords = coordinates.get(j); coordsMatch = true; for (int i = 0; i < atomContainer.getAtomCount(); i++) { Point3d p = atomContainer.getAtom(i).getPoint3d(); if (!(p.x == coords[i].x && p.y == coords[i].y && p.z == coords[i].z)) { coordsMatch = false; break; } } if (coordsMatch) return j; } return -1; }
/base/data/src/main/java/org/openscience/cdk/ConformerContainer.java
robustness-copilot_data_644
/** * The only time a dataset can be in review is when it is in draft. * @return if the dataset is being reviewed */ public boolean isInReview(){ if (versionState != null && versionState.equals(VersionState.DRAFT)) { return getDataset().isLockedFor(DatasetLock.Reason.InReview); } else { return false; } }
/src/main/java/edu/harvard/iq/dataverse/DatasetVersion.java
robustness-copilot_data_645
/** * Converts a limited set of String representations to their corresponding Objects * <p/> * Supports * * Double * * Long * * Integer * * Boolean (true/false) * * Dates in string format of ISODateTimeFormat * <p/> * Else, null is returned. * * @param data the String representation of the data * @param klass the target class type of the provided data * @param <T> the target class type of the provided data * @return the derived object representing the data as specified by the klass */ public static T toObjectType(String data, Class<T> klass){ if (Double.class.equals(klass)) { try { return klass.cast(Double.parseDouble(data)); } catch (NumberFormatException ex) { return null; } } else if (Long.class.equals(klass)) { try { return klass.cast(Long.parseLong(data)); } catch (NumberFormatException ex) { return null; } } else if (Integer.class.equals(klass)) { try { return klass.cast(Long.parseLong(data)); } catch (NumberFormatException ex) { return null; } } else if (StringUtils.equalsIgnoreCase("true", data)) { return klass.cast(Boolean.TRUE); } else if (StringUtils.equalsIgnoreCase("false", data)) { return klass.cast(Boolean.FALSE); } else if (JSON_DATE.matcher(data).matches()) { long epochSeconds = OffsetDateTime.parse(data).toInstant().toEpochMilli(); return klass.cast(new Date(epochSeconds)); } else { return klass.cast(data); } }
/bundle/src/main/java/com/adobe/acs/commons/util/TypeUtil.java
robustness-copilot_data_646
/** * Report the current values of all metrics in the registry. */ public void report(){ synchronized (this) { report(registry.getGauges(filter), registry.getCounters(filter), registry.getHistograms(filter), registry.getMeters(filter), registry.getTimers(filter)); } }
/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java
robustness-copilot_data_647
/** * Compare two {@link IChemObject} classes and return the difference as an {@link IDifference}. * * @param first the first of the two classes to compare * @param second the second of the two classes to compare * @return an {@link IDifference} representation of the difference between the first and second {@link IChemObject}. */ public static IDifference difference(IChemObject first, IChemObject second){ if (!(first instanceof IAtomType && second instanceof IAtomType)) { return null; } IAtomType firstElem = (IAtomType) first; IAtomType secondElem = (IAtomType) second; ChemObjectDifference totalDiff = new ChemObjectDifference("AtomTypeDiff"); totalDiff.addChild(StringDifference.construct("N", firstElem.getAtomTypeName(), secondElem.getAtomTypeName())); totalDiff.addChild(BondOrderDifference.construct("MBO", firstElem.getMaxBondOrder(), secondElem.getMaxBondOrder())); totalDiff.addChild(DoubleDifference.construct("BOS", firstElem.getBondOrderSum(), secondElem.getBondOrderSum())); totalDiff.addChild(IntegerDifference.construct("FC", firstElem.getFormalCharge(), secondElem.getFormalCharge())); totalDiff.addChild(AtomTypeHybridizationDifference.construct("H", firstElem.getHybridization(), secondElem.getHybridization())); totalDiff.addChild(IntegerDifference.construct("NC", firstElem.getFormalNeighbourCount(), secondElem.getFormalNeighbourCount())); totalDiff.addChild(DoubleDifference.construct("CR", firstElem.getCovalentRadius(), secondElem.getCovalentRadius())); totalDiff.addChild(IntegerDifference.construct("V", firstElem.getValency(), secondElem.getValency())); totalDiff.addChild(IsotopeDiff.difference(first, second)); if (totalDiff.childCount() > 0) { return totalDiff; } else { return null; } }
/misc/diff/src/main/java/org/openscience/cdk/tools/diff/AtomTypeDiff.java
robustness-copilot_data_648
/** * Return a new table (shallow copy) that contains all the columns in this table, in the order * given in the argument. Throw an IllegalArgument exception if the number of names given does not * match the number of columns in this table. NOTE: This does not make a copy of the columns, so * they are shared between the two tables. * * @param columnNames a column name or array of names */ public Table reorderColumns(String... columnNames){ Preconditions.checkArgument(columnNames.length == columnCount()); Table table = Table.create(name); for (String name : columnNames) { table.addColumns(column(name)); } return table; }
/core/src/main/java/tech/tablesaw/api/Table.java
robustness-copilot_data_649
/** * Creates a {@link WaitStrategy} from a string. * <p> * The following strategies are supported: * <ul> * <li><code>blocking</code> - {@link BlockingWaitStrategy}</li> * <li><code>busySpin</code> - {@link BusySpinWaitStrategy}</li> * <li><code>liteBlocking</code> - {@link LiteBlockingWaitStrategy}</li> * <li><code>sleeping{retries,sleepTimeNs}</code> - {@link SleepingWaitStrategy} * - <code>retries</code> an integer number of times to spin before sleeping. (default = 200) * <code>sleepTimeNs</code> nanosecond time to sleep each iteration after spinning (default = 100) * </li> * <li><code>yielding</code> - {@link YieldingWaitStrategy}</li> * <li><code>phasedBackoff{spinTimeout,yieldTimeout,timeUnit,fallackStrategy}</code> - {@link PhasedBackoffWaitStrategy} * - <code>spinTimeout</code> and <code>yieldTimeout</code> are long values. * <code>timeUnit</code> is a string name of one of the {@link TimeUnit} values. * <code>fallbackStrategy</code> is a wait strategy string (e.g. <code>blocking</code>). * </li> * <li><code>timeoutBlocking{timeout,timeUnit}</code> - {@link TimeoutBlockingWaitStrategy} * - <code>timeout</code> is a long value. * <code>timeUnit</code> is a string name of one of the {@link TimeUnit} values. * </li> * <li><code>liteTimeoutBlocking{timeout,timeUnit}</code> - {@link LiteTimeoutBlockingWaitStrategy} * - <code>timeout</code> is a long value. * <code>timeUnit</code> is a string name of one of the {@link TimeUnit} values. * </li> * </ul> * * @param waitStrategyType the name of the desired wait strategy * @return a {@link WaitStrategy} instance or {@code null} if the supplied name is {@code null} or empty * @throws IllegalArgumentException if an unknown wait strategy type is given, or the parameters are unable to be parsed. */ public static WaitStrategy createWaitStrategyFromString(String waitStrategyType){ if (waitStrategyType == null) { return null; } waitStrategyType = waitStrategyType.trim().toLowerCase(); if (waitStrategyType.isEmpty()) { return null; } if (waitStrategyType.equals("blocking")) { return new BlockingWaitStrategy(); } if (waitStrategyType.equals("busyspin")) { return new BusySpinWaitStrategy(); } if (waitStrategyType.equals("liteblocking")) { return new LiteBlockingWaitStrategy(); } if (waitStrategyType.startsWith("sleeping")) { if (waitStrategyType.equals("sleeping")) { return new SleepingWaitStrategy(); } else { List<Object> params = parseParams(waitStrategyType, Integer.class, Long.class); return new SleepingWaitStrategy((Integer) params.get(0), (Long) params.get(1)); } } if (waitStrategyType.equals("yielding")) { return new YieldingWaitStrategy(); } if (waitStrategyType.startsWith("phasedbackoff")) { List<Object> params = parseParams(waitStrategyType, Long.class, Long.class, TimeUnit.class, WaitStrategy.class); return new PhasedBackoffWaitStrategy((Long) params.get(0), (Long) params.get(1), (TimeUnit) params.get(2), (WaitStrategy) params.get(3)); } if (waitStrategyType.startsWith("timeoutblocking")) { List<Object> params = parseParams(waitStrategyType, Long.class, TimeUnit.class); return new TimeoutBlockingWaitStrategy((Long) params.get(0), (TimeUnit) params.get(1)); } if (waitStrategyType.startsWith("litetimeoutblocking")) { List<Object> params = parseParams(waitStrategyType, Long.class, TimeUnit.class); return new LiteTimeoutBlockingWaitStrategy((Long) params.get(0), (TimeUnit) params.get(1)); } throw new IllegalArgumentException("Unknown wait strategy type: " + waitStrategyType); }
/src/main/java/net/logstash/logback/appender/WaitStrategyFactory.java
robustness-copilot_data_650
/** * This makes sourceAtom map of matching atoms out of sourceAtom map of matching bonds as produced by the get(Subgraph|Ismorphism)Map methods. * * @param rMapList The list produced by the getMap method. * @param graph1 first molecule. Must not be an IQueryAtomContainer. * @param graph2 second molecule. May be an IQueryAtomContainer. * @return The mapping found projected on graph1. This is sourceAtom List of CDKRMap objects containing Ids of matching atoms. */ private static List<List<CDKRMap>> makeAtomsMapOfBondsMap(List<CDKRMap> rMapList, IAtomContainer graph1, IAtomContainer graph2){ if (rMapList == null) { return (null); } List<List<CDKRMap>> result = null; if (rMapList.size() == 1) { result = makeAtomsMapOfBondsMapSingleBond(rMapList, graph1, graph2); } else { List<CDKRMap> resultLocal = new ArrayList<CDKRMap>(); for (int i = 0; i < rMapList.size(); i++) { IBond qBond = graph1.getBond(rMapList.get(i).getId1()); IBond tBond = graph2.getBond(rMapList.get(i).getId2()); IAtom[] qAtoms = BondManipulator.getAtomArray(qBond); IAtom[] tAtoms = BondManipulator.getAtomArray(tBond); for (int j = 0; j < 2; j++) { List<IBond> bondsConnectedToAtom1j = graph1.getConnectedBondsList(qAtoms[j]); for (int k = 0; k < bondsConnectedToAtom1j.size(); k++) { if (!bondsConnectedToAtom1j.get(k).equals(qBond)) { IBond testBond = bondsConnectedToAtom1j.get(k); for (int m = 0; m < rMapList.size(); m++) { IBond testBond2; if ((rMapList.get(m)).getId1() == graph1.indexOf(testBond)) { testBond2 = graph2.getBond((rMapList.get(m)).getId2()); for (int n = 0; n < 2; n++) { List<IBond> bondsToTest = graph2.getConnectedBondsList(tAtoms[n]); if (bondsToTest.contains(testBond2)) { CDKRMap map; if (j == n) { map = new CDKRMap(graph1.indexOf(qAtoms[0]), graph2.indexOf(tAtoms[0])); } else { map = new CDKRMap(graph1.indexOf(qAtoms[1]), graph2.indexOf(tAtoms[0])); } if (!resultLocal.contains(map)) { resultLocal.add(map); } CDKRMap map2; if (j == n) { map2 = new CDKRMap(graph1.indexOf(qAtoms[1]), graph2.indexOf(tAtoms[1])); } else { map2 = new CDKRMap(graph1.indexOf(qAtoms[0]), graph2.indexOf(tAtoms[1])); } if (!resultLocal.contains(map2)) { resultLocal.add(map2); } } } } } } } } } result = new ArrayList<List<CDKRMap>>(); result.add(resultLocal); } return result; }
/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKRMapHandler.java
robustness-copilot_data_651
/** * Creates a web hook object to track service calls. * * @param namespace the namespace * @return the active web hook * @throws ApiException if there is an error on the call that sets up the web hook. */ public Watchable<V1Service> createServiceWatch(String namespace) throws ApiException{ return FACTORY.createWatch(callParams, V1Service.class, new ListNamespacedServiceCall(namespace)); }
/operator/src/main/java/oracle/kubernetes/operator/builders/WatchBuilder.java
robustness-copilot_data_652
/** * Calculate the size of the partition as the sum of the sizes of the cells. * * @return the number of elements in the partition */ public int numberOfElements(){ int n = 0; for (SortedSet<Integer> cell : cells) { n += cell.size(); } return n; }
/tool/group/src/main/java/org/openscience/cdk/group/Partition.java
robustness-copilot_data_653
/** * Provide a short, simple human understandable string describing the supplied duration. The * duration is a non-negative value. The output is appended to the supplied StringBuilder and * has the form {@code <number> <space> <units>}, where {@code <number>} is an integer and * {@code <units>} is defined by the value of unitFormat. */ public static StringBuilder appendDuration(StringBuilder sb, Duration duration, TimeUnitFormat unitFormat){ return appendDuration(sb, duration.toMillis(), MILLISECONDS, unitFormat); }
/modules/common/src/main/java/org/dcache/util/TimeUtils.java
robustness-copilot_data_654
/** * Returns the index of the first character in the string that is not a digit, starting at offset. */ private static int indexOfNonDigit(String string, int offset){ for (int i = offset; i < string.length(); i++) { char c = string.charAt(i); if (c < '0' || c > '9') return i; } return string.length(); }
/src/main/java/com/fasterxml/jackson/databind/util/ISO8601Utils.java
robustness-copilot_data_655
/** * Checks whether a bond is connected to another one. * This can only be true if the bonds have an Atom in common. * * @param bond The bond which is checked to be connect with this one * @return true if the bonds share an atom, otherwise false */ public boolean isConnectedTo(IBond bond){ for (IAtom atom : atoms) { if (bond.contains(atom)) return true; } return false; }
/base/silent/src/main/java/org/openscience/cdk/silent/Bond.java
robustness-copilot_data_656
/** * Finds a minimal additional distance for the tour, when a pickup is added to * the plan. The AssociatedActivities contains both activities of a job which * should be added to the existing tour. The TourActivities which are already in * the tour are found in context.getRoute().getTourActivities. In this method * the position of the new pickup is fixed and three options of the location of * the delivery activity will be checked: delivery between every other activity * after the pickup, delivery as the last activity before the end and delivery * directly behind the new pickup. This method gives back the minimal distance * of this three options. * * @param context * @param newInvestigatedPickup * @param nextAct * @return minimal distance of the associated delivery */ private double findMinimalAdditionalDistance(JobInsertionContext context, TourActivity newInvestigatedPickup, TourActivity nextAct){ double minimalAdditionalDistance = 0; if (context.getAssociatedActivities().get(1) instanceof DeliverShipment) { TourActivity assignedDelivery = context.getAssociatedActivities().get(1); minimalAdditionalDistance = 0; int indexNextActicity = nextAct.getIndex(); int tourPositionOfAcitivityBehindNewPickup = 0; int countIndex = 0; Vehicle newVehicle = context.getNewVehicle(); VehicleRoute route = context.getRoute(); a: for (TourActivity tourActivity : route.getTourActivities().getActivities()) { if (tourActivity.getIndex() == indexNextActicity) { while (countIndex < route.getTourActivities().getActivities().size()) { if (route.getTourActivities().getActivities().get(countIndex).getIndex() == indexNextActicity) { tourPositionOfAcitivityBehindNewPickup = countIndex; break a; } countIndex++; } } } while ((tourPositionOfAcitivityBehindNewPickup + 1) < route.getTourActivities().getActivities().size()) { TourActivity activityBefore = route.getTourActivities().getActivities().get(tourPositionOfAcitivityBehindNewPickup); TourActivity activityAfter = route.getTourActivities().getActivities().get(tourPositionOfAcitivityBehindNewPickup + 1); double possibleAdditionalDistance = getDistance(activityBefore, assignedDelivery, newVehicle) + getDistance(assignedDelivery, activityAfter, newVehicle) - getDistance(activityBefore, activityAfter, newVehicle); minimalAdditionalDistance = findMinimalDistance(minimalAdditionalDistance, possibleAdditionalDistance); tourPositionOfAcitivityBehindNewPickup++; } if (route.getTourActivities().getActivities().size() > 0) { TourActivity activityLastDelivery = route.getTourActivities().getActivities().get(route.getTourActivities().getActivities().size() - 1); TourActivity activityEnd = route.getEnd(); double possibleAdditionalDistance = getDistance(activityLastDelivery, assignedDelivery, newVehicle) + getDistance(assignedDelivery, activityEnd, newVehicle) - getDistance(activityLastDelivery, activityEnd, newVehicle); minimalAdditionalDistance = findMinimalDistance(minimalAdditionalDistance, possibleAdditionalDistance); TourActivity activityAfter = route.getTourActivities().getActivities().get(tourPositionOfAcitivityBehindNewPickup); possibleAdditionalDistance = getDistance(newInvestigatedPickup, assignedDelivery, newVehicle) + getDistance(assignedDelivery, activityAfter, newVehicle) - getDistance(newInvestigatedPickup, activityAfter, newVehicle); minimalAdditionalDistance = findMinimalDistance(minimalAdditionalDistance, possibleAdditionalDistance); } } return minimalAdditionalDistance; }
/contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/DistanceConstraint.java
robustness-copilot_data_657
/** * Returns the "raw" field of a document based on a collection docid. The method is named to be consistent with * Lucene's {@link IndexReader#document(int)}, contra Java's standard method naming conventions. * * @param reader index reader * @param docid collection docid * @return the "raw" field the document */ public static String documentRaw(IndexReader reader, String docid){ try { return reader.document(convertDocidToLuceneDocid(reader, docid)).get(IndexArgs.RAW); } catch (Exception e) { return null; } }
/src/main/java/io/anserini/index/IndexReaderUtils.java
robustness-copilot_data_658
/** * Parse the given storedCheckSum string value and return a new CheckSum object. */ public static CheckSum parse(String checksumValue){ if (checksumValue == null) { return null; } // The general layout of a checksum is: // <1 digit: algorithm version number>:<1..n characters alphanumeric checksum> // Example: 7:2cdf9876e74347162401315d34b83746 Matcher matcher = CHECKSUM_PATTERN.matcher(checksumValue); if (matcher.find()) { return new CheckSum(matcher.group(2), Integer.parseInt(matcher.group(1))); } else { // No version information found return new CheckSum(checksumValue, 1); } }
/liquibase-core/src/main/java/liquibase/change/CheckSum.java
robustness-copilot_data_659
/** * Writes a {@link IChemObject} to the MDL molfile formated output. * It can only output ChemObjects of type {@link IChemFile}, * {@link IChemObject} and {@link IAtomContainer}. * * @param object {@link IChemObject} to write * @see #accepts(Class) */ public void write(IChemObject object) throws CDKException{ customizeJob(); try { if (object instanceof IChemFile) { writeChemFile((IChemFile) object); return; } else if (object instanceof IChemModel) { IChemFile file = object.getBuilder().newInstance(IChemFile.class); IChemSequence sequence = object.getBuilder().newInstance(IChemSequence.class); sequence.addChemModel((IChemModel) object); file.addChemSequence(sequence); writeChemFile((IChemFile) file); return; } else if (object instanceof IAtomContainer) { writeMolecule((IAtomContainer) object); return; } } catch (Exception ex) { logger.error(ex.getMessage()); logger.debug(ex); throw new CDKException("Exception while writing MDL file: " + ex.getMessage(), ex); } throw new CDKException("Only supported is writing of IChemFile, " + "IChemModel, and IAtomContainer objects."); }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Writer.java
robustness-copilot_data_660
/** * Get the value assigned to the current thread, creating a new one if none is assigned yet or the * previous has been disposed. * * The value must be {@link #release()} to ensure proper life cycle before it can be {@link #acquire()} * again. * * @return the value assigned to this thread * @throws IllegalStateException if the value is already in use and {@link #release()} was not yet invoked. */ public final T acquire(){ Holder<T> holder = this.threadLocal.get(); if (holder.leased) { throw new IllegalStateException("ThreadLocal value is already in use and not yet released."); } if (holder.value == null) { holder.value = Objects.requireNonNull(createInstance()); } holder.leased = true; return holder.value; }
/src/main/java/net/logstash/logback/util/ThreadLocalHolder.java
robustness-copilot_data_661
/** * Creates cross product for the selection of two tables. * * @param destination the destination table. * @param table1 the table on left of join. * @param table2 the table on right of join. * @param table1Rows the selection of rows in table1. * @param table2Rows the selection of rows in table2. * @param ignoreColumns a set of column indexes in the result to ignore. They are redundant join * columns. */ private void crossProduct(Table destination, Table table1, Table table2, Selection table1Rows, Selection table2Rows, Set<Integer> ignoreColumns, boolean keepTable2JoinKeyColumns){ for (int c = 0; c < table1.columnCount() + table2.columnCount(); c++) { if (!keepTable2JoinKeyColumns && ignoreColumns.contains(c)) { continue; } int table2Index = c - table1.columnCount(); for (int r1 : table1Rows) { for (int r2 : table2Rows) { if (c < table1.columnCount()) { Column t1Col = table1.column(c); destination.column(c).append(t1Col, r1); } else { Column t2Col = table2.column(table2Index); destination.column(c).append(t2Col, r2); } } } } }
/core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java
robustness-copilot_data_662
/** * Helper method used to construct appropriate description * when passed either type (Class) or an instance; in latter * case, class of instance is to be used. * * @since 2.9 */ public static String classNameOf(Object inst){ if (inst == null) { return "[null]"; } Class<?> raw = (inst instanceof Class<?>) ? (Class<?>) inst : inst.getClass(); return nameOf(raw); }
/src/main/java/com/fasterxml/jackson/databind/util/ClassUtil.java
robustness-copilot_data_663
/** * Adds annotated rule classes to an instance of NewRepository. Fails if one the classes has no SQALE annotation. */ public static void load(NewRepository repository, String languageKey, Iterable<Class> ruleClasses){ new AnnotationBasedRulesDefinition(repository, languageKey).addRuleClasses(true, ruleClasses); }
/cxx-squid-bridge/src/main/java/org/sonar/cxx/squidbridge/annotations/AnnotationBasedRulesDefinition.java
robustness-copilot_data_664
/** * Provides basic statistics of a given {@link Network}. * @param network */ public static void reportNetworkStatistics(Network network){ LOG.info("--- Network statistics: ------------------------------------------------------"); LOG.info(" Network description: " + network.getName()); LOG.info(" Number of nodes: " + network.getNodes().size()); LOG.info(" Number of links: " + network.getLinks().size()); LOG.info("------------------------------------------------------------------------------"); }
/matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/IntersectionSimplifier.java
robustness-copilot_data_665
/** * Order the ligands from high to low precedence according to atomic and mass numbers. */ private ILigand[] order(ILigand[] ligands){ ILigand[] newLigands = new ILigand[ligands.length]; System.arraycopy(ligands, 0, newLigands, 0, ligands.length); Arrays.sort(newLigands, numberRule); ILigand[] reverseLigands = new ILigand[newLigands.length]; for (int i = 0; i < newLigands.length; i++) { reverseLigands[(newLigands.length - 1) - i] = newLigands[i]; } return reverseLigands; }
/descriptor/cip/src/main/java/org/openscience/cdk/geometry/cip/rules/CIPLigandRule.java
robustness-copilot_data_666
/** * Signs the provided packet, so a CollectD server can verify that its authenticity. * Wire format: * <pre> * +-------------------------------+-------------------------------+ * ! Type (0x0200) ! Length ! * +-------------------------------+-------------------------------+ * ! Signature (SHA2(username + packet)) \ * +-------------------------------+-------------------------------+ * ! Username ! Packet \ * +---------------------------------------------------------------+ * </pre> * * @see <a href="https://collectd.org/wiki/index.php/Binary_protocol#Signature_part"> * Binary protocol - CollectD | Signature part</a> */ private ByteBuffer signPacket(ByteBuffer packet){ final byte[] signature = sign(password, (ByteBuffer) ByteBuffer.allocate(packet.remaining() + username.length).put(username).put(packet).flip()); return (ByteBuffer) ByteBuffer.allocate(BUFFER_SIZE).putShort((short) TYPE_SIGN_SHA256).putShort((short) (username.length + SIGNATURE_LEN)).put(signature).put(username).put((ByteBuffer) packet.flip()).flip(); }
/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java
robustness-copilot_data_667
/** * Appends a new row to the model source data, which consists of a molecule and whether or not it * is considered active. * * @param mol molecular structure, which must be non-blank * @param active whether active or not */ public void addMolecule(IAtomContainer mol, boolean active) throws CDKException{ if (mol == null || mol.getAtomCount() == 0) throw new CDKException("Molecule cannot be blank or null."); CircularFingerprinter circ = new CircularFingerprinter(classType); circ.setPerceiveStereo(optPerceiveStereo); circ.calculate(mol); final int AND_BITS = folding - 1; Set<Integer> hashset = new TreeSet<Integer>(); for (int n = circ.getFPCount() - 1; n >= 0; n--) { int code = circ.getFP(n).hashCode; if (folding > 0) code &= AND_BITS; hashset.add(code); } int[] hashes = new int[hashset.size()]; int p = 0; for (Integer h : hashset) hashes[p++] = h; if (active) numActive++; training.add(hashes); activity.add(active); for (int h : hashes) { int[] stash = inHash.get(h); if (stash == null) stash = new int[] { 0, 0 }; if (active) stash[0]++; stash[1]++; inHash.put(h, stash); } }
/tool/model/src/main/java/org/openscience/cdk/fingerprint/model/Bayesian.java
robustness-copilot_data_668
/** * Checks if a potential solution is a real one * (not included in a previous solution) * and add this solution to the solution list * in case of success. * * @param traversed new potential solution */ private void solution(BitSet traversed) throws CDKException{ boolean included = false; BitSet projG1 = projectG1(traversed); BitSet projG2 = projectG2(traversed); if (isContainedIn(getSourceBitSet(), projG1) && isContainedIn(getTargetBitSet(), projG2)) { for (Iterator<BitSet> i = getSolutionList().listIterator(); i.hasNext() && !included; ) { BitSet sol = i.next(); checkTimeOut(); if (!sol.equals(traversed)) { if (isFindAllMap() && (projG1.equals(projectG1(sol)) || projG2.equals(projectG2(sol)))) { } else if (isContainedIn(projG1, projectG1(sol)) || isContainedIn(projG2, projectG2(sol))) { included = true; } else if (isContainedIn(projectG1(sol), projG1) || isContainedIn(projectG2(sol), projG2)) { i.remove(); } } else { included = true; } } if (included == false) { getSolutionList().add(traversed); } if (!isFindAllStructure()) { setStop(true); } } }
/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKRGraph.java
robustness-copilot_data_669
/** * Changes to another plan with a probability proportional to exp( Delta scores ). * Need to think through if this goes to Nash Equilibrium or to SUE !!! */ public T selectPlan(final HasPlansAndId<T, I> person){ // current plan and random plan: T currentPlan = person.getSelectedPlan(); T otherPlan = new RandomPlanSelector<T, I>().selectPlan(person); if (currentPlan == null) { // this case should only happen when the agent has no plans at all return null; } if ((currentPlan.getScore() == null) || (otherPlan.getScore() == null)) { /* With the previous behavior, Double.NaN was returned if no score was available. * This resulted in weight=NaN below as well, and then ultimately in returning * the currentPlan---what we're doing right now as well. */ if (currentPlan.getScore() != null && otherPlan.getScore() == null) { if (scoreWrnFlag) { log.error("yyyyyy not switching to other plan although it needs to be explored. " + "Possibly a serious bug; ask kai if you encounter this. kai, sep'10"); scoreWrnFlag = false; } } return currentPlan; } // defending against NaN (which should not happen, but happens): if (currentPlan.getScore().isNaN()) { return otherPlan; } if (otherPlan.getScore().isNaN()) { return currentPlan; } double currentScore = currentPlan.getScore().doubleValue(); double otherScore = otherPlan.getScore().doubleValue(); if (betaWrnFlag) { log.warn("Would make sense to revise this once more. See comments in code. kai, nov08"); /** * Gunnar says, rightly I think, that what is below hits the "0.01*weight > 1" threshold fairly quickly. * An alternative might be to divide by exp(0.5*beta*oS)+exp(0.5*beta*cS), or the max of these two numbers. But: * (1) someone would need to go through the theory to make sure that we remain within what we have said before * (convergence to logit and proba of jump between equal options = 0.01 * (2) someone would need to test if the "traffic" results are similar */ betaWrnFlag = false; } double weight = Math.exp(0.5 * this.beta * (otherScore - currentScore)); // (so far, this is >1 if otherScore>currentScore, and <=1 otherwise) // (beta is the slope (strength) of the operation: large beta means strong reaction) if (MatsimRandom.getRandom().nextDouble() < 0.01 * weight) { // as of now, 0.01 is hardcoded (proba to change when both // scores are the same) return otherPlan; } return currentPlan; }
/matsim/src/main/java/org/matsim/core/replanning/selectors/ExpBetaPlanChanger.java
robustness-copilot_data_670
/** * Rescales Point2 so that length 1-2 is sum of covalent radii. * If covalent radii cannot be found, use bond length of 1.0 * *@param atom1 stationary atom *@param atom2 movable atom *@param point2 coordinates for atom 2 *@return new coordinates for atom 2 */ public Point3d rescaleBondLength(IAtom atom1, IAtom atom2, Point3d point2){ Point3d point1 = atom1.getPoint3d(); Double d1 = atom1.getCovalentRadius(); Double d2 = atom2.getCovalentRadius(); double distance = (d1 == null || d2 == null) ? 1.0 : d1 + d2; if (pSet != null) { distance = getDistanceValue(atom1.getAtomTypeName(), atom2.getAtomTypeName()); } Vector3d vect = new Vector3d(point2); vect.sub(point1); vect.normalize(); vect.scale(distance); Point3d newPoint = new Point3d(point1); newPoint.add(vect); return newPoint; }
/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomTetrahedralLigandPlacer3D.java
robustness-copilot_data_671
/** * Helper method called to add explicitly ignored properties to a list * of known ignored properties; this helps in proper reporting of * errors. */ protected void _collectIgnorals(String name){ if (!_forSerialization && (name != null)) { if (_ignoredPropertyNames == null) { _ignoredPropertyNames = new HashSet<String>(); } _ignoredPropertyNames.add(name); } }
/src/main/java/com/fasterxml/jackson/databind/introspect/POJOPropertiesCollector.java
robustness-copilot_data_672
/** * Converts a collection docid to a Lucene internal docid. * * @param reader index reader * @param docid collection docid * @return corresponding Lucene internal docid, or -1 if docid not found */ public static int convertDocidToLuceneDocid(IndexReader reader, String docid){ try { IndexSearcher searcher = new IndexSearcher(reader); Query q = new TermQuery(new Term(IndexArgs.ID, docid)); TopDocs rs = searcher.search(q, 1); ScoreDoc[] hits = rs.scoreDocs; if (hits == null || hits.length == 0) { return -1; } return hits[0].doc; } catch (IOException e) { return -1; } }
/src/main/java/io/anserini/index/IndexReaderUtils.java
robustness-copilot_data_673
/** * Return comparison result based on the content of the properties. * * @param objectToCompare test object * @return result of comparison */ public boolean equals(Object objectToCompare){ if (this == objectToCompare) { return true; } if (objectToCompare == null || getClass() != objectToCompare.getClass()) { return false; } if (!super.equals(objectToCompare)) { return false; } AssetResponse that = (AssetResponse) objectToCompare; return getCertificationCount() == that.getCertificationCount() && getCommentCount() == that.getCommentCount() && getConnectionCount() == that.getConnectionCount() && getExternalIdentifierCount() == that.getExternalIdentifierCount() && getExternalReferencesCount() == that.getExternalReferencesCount() && getInformalTagCount() == that.getInformalTagCount() && getLicenseCount() == that.getLicenseCount() && getLikeCount() == that.getLikeCount() && getKnownLocationsCount() == that.getKnownLocationsCount() && getNoteLogsCount() == that.getNoteLogsCount() && getRatingsCount() == that.getRatingsCount() && getRelatedAssetCount() == that.getRelatedAssetCount() && getRelatedMediaReferenceCount() == that.getRelatedMediaReferenceCount() && getSchemaType() == that.getSchemaType() && getLastAttachment() == that.getLastAttachment() && Objects.equals(getAsset(), that.getAsset()); }
/open-metadata-implementation/common-services/ocf-metadata-management/ocf-metadata-api/src/main/java/org/odpi/openmetadata/commonservices/ocf/metadatamanagement/rest/AssetResponse.java
robustness-copilot_data_674
/** * cleanup the timestamps array and replace all expired entries with * Instant.EPOCH; * * @return the number of emptied slots */ private int purgeExpiredEntries(){ int result = 0; for (int i = 0; i < timestamps.length; i++) { long now = clock.instant().toEpochMilli(); if (now - timestamps[i].toEpochMilli() > ONE_MINUTE) { timestamps[i] = Instant.EPOCH; result++; } } return result; }
/bundle/src/main/java/com/adobe/acs/commons/throttling/ThrottlingState.java
robustness-copilot_data_675
/** * Compare two IMolecularFormula looking at type and number of IIsotope and * charge of the formula. * * @param formula1 The first IMolecularFormula * @param formula2 The second IMolecularFormula * @return True, if the both IMolecularFormula are the same */ public static boolean compare(IMolecularFormula formula1, IMolecularFormula formula2){ if (!Objects.equals(formula1.getCharge(), formula2.getCharge())) return false; if (formula1.getIsotopeCount() != formula2.getIsotopeCount()) return false; for (IIsotope isotope : formula1.isotopes()) { if (!formula2.contains(isotope)) return false; if (formula1.getIsotopeCount(isotope) != formula2.getIsotopeCount(isotope)) return false; } for (IIsotope isotope : formula2.isotopes()) { if (!formula1.contains(isotope)) return false; if (formula2.getIsotopeCount(isotope) != formula1.getIsotopeCount(isotope)) return false; } return true; }
/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
robustness-copilot_data_676
/** * Create a vector by specifying the source and destination coordinates. * * @param src start point of the vector * @param dest end point of the vector * @return a new vector */ private static double[] toVector(Point3d src, Point3d dest){ return new double[] { dest.x - src.x, dest.y - src.y, dest.z - src.z }; }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/DoubleBond3DParity.java
robustness-copilot_data_677
/** * A method that will look for the first Enum value annotated with the given Annotation. * <p> * If there's more than one value annotated, the first one found will be returned. Which one exactly is used is undetermined. * * @param enumClass The Enum class to scan for a value with the given annotation * @param annotationClass The annotation to look for. * @return the Enum value annotated with the given Annotation or {@code null} if none is found. * @throws IllegalArgumentException if there's a reflection issue accessing the Enum * @since 2.8 */ public static Enum<?> findFirstAnnotatedEnumValue(Class<Enum<?>> enumClass, Class<T> annotationClass){ Field[] fields = enumClass.getDeclaredFields(); for (Field field : fields) { if (field.isEnumConstant()) { Annotation defaultValueAnnotation = field.getAnnotation(annotationClass); if (defaultValueAnnotation != null) { final String name = field.getName(); for (Enum<?> enumValue : enumClass.getEnumConstants()) { if (name.equals(enumValue.name())) { return enumValue; } } } } } return null; }
/src/main/java/com/fasterxml/jackson/databind/util/ClassUtil.java
robustness-copilot_data_678
/** * Sort MCS solution by stereo and bond type matches. * @throws CDKException */ public synchronized void sortResultsByStereoAndBondMatch() throws CDKException{ // System.out.println("\n\n\n\nSort By ResultsByStereoAndBondMatch"); Map<Integer, Map<Integer, Integer>> allStereoMCS = new HashMap<Integer, Map<Integer, Integer>>(); Map<Integer, Map<IAtom, IAtom>> allStereoAtomMCS = new HashMap<Integer, Map<IAtom, IAtom>>(); Map<Integer, Integer> fragmentScoreMap = new TreeMap<Integer, Integer>(); Map<Integer, Double> energyScoreMap = new TreeMap<Integer, Double>(); Map<Integer, Double> stereoScoreMap = new HashMap<Integer, Double>(); initializeMaps(allStereoMCS, allStereoAtomMCS, stereoScoreMap, fragmentScoreMap, energyScoreMap); boolean stereoMatchFlag = getStereoBondChargeMatch(stereoScoreMap, allStereoMCS, allStereoAtomMCS); boolean flag = false; if (stereoMatchFlag) { // Higher Score is mapped preferred over lower stereoScoreMap = sortMapByValueInDecendingOrder(stereoScoreMap); double higestStereoScore = stereoScoreMap.isEmpty() ? 0 : stereoScoreMap.values().iterator().next(); double secondhigestStereoScore = higestStereoScore; for (Integer key : stereoScoreMap.keySet()) { if (secondhigestStereoScore < higestStereoScore && stereoScoreMap.get(key) > secondhigestStereoScore) { secondhigestStereoScore = stereoScoreMap.get(key); } else if (secondhigestStereoScore == higestStereoScore && stereoScoreMap.get(key) < secondhigestStereoScore) { secondhigestStereoScore = stereoScoreMap.get(key); } } if (!stereoScoreMap.isEmpty()) { flag = true; clear(); } /* Put back the sorted solutions */ int counter = 0; for (Integer i : stereoScoreMap.keySet()) { // System.out.println("Sorted Map key " + I + " Sorted Value: " + stereoScoreMap.get(I)); // System.out.println("Stereo MCS " + allStereoMCS.get(I) + " Stereo Value: " // + stereoScoreMap.get(I)); if (higestStereoScore == stereoScoreMap.get(i).doubleValue()) { // || secondhigestStereoScore == stereoScoreMap.get(I).doubleValue()) { addSolution(counter, i, allStereoAtomMCS, allStereoMCS, stereoScoreMap, energyScoreMap, fragmentScoreMap); counter++; // System.out.println("Sorted Map key " + I + " Sorted Value: " + stereoScoreMap.get(I)); // System.out.println("Stereo MCS " + allStereoMCS.get(I) + " Stereo Value: " // + stereoScoreMap.get(I)); } } if (flag) { firstSolution.putAll(allMCS.get(0)); firstAtomMCS.putAll(allAtomMCS.get(0)); clear(allStereoMCS, allStereoAtomMCS, stereoScoreMap, fragmentScoreMap, energyScoreMap); } } }
/legacy/src/main/java/org/openscience/cdk/smsd/filters/ChemicalFilters.java
robustness-copilot_data_679
/** * Validate that an object is equal depending on their stored values. * * @param objectToCompare object * @return boolean result */ public boolean equals(Object objectToCompare){ if (this == objectToCompare) { return true; } if (objectToCompare == null || getClass() != objectToCompare.getClass()) { return false; } TypeDefPatch that = (TypeDefPatch) objectToCompare; return applyToVersion == that.applyToVersion && updateToVersion == that.updateToVersion && Objects.equals(typeDefGUID, that.typeDefGUID) && Objects.equals(typeDefName, that.typeDefName) && typeDefStatus == that.typeDefStatus && Objects.equals(newVersionName, that.newVersionName) && Objects.equals(updatedBy, that.updatedBy) && Objects.equals(updateTime, that.updateTime) && Objects.equals(description, that.description) && Objects.equals(descriptionGUID, that.descriptionGUID) && Objects.equals(superType, that.superType) && Objects.equals(propertyDefinitions, that.propertyDefinitions) && Objects.equals(typeDefOptions, that.typeDefOptions) && Objects.equals(externalStandardMappings, that.externalStandardMappings) && Objects.equals(validInstanceStatusList, that.validInstanceStatusList) && initialStatus == that.initialStatus && Objects.equals(validEntityDefs, that.validEntityDefs) && Objects.equals(endDef1, that.endDef1) && Objects.equals(endDef2, that.endDef2); }
/open-metadata-implementation/repository-services/repository-services-apis/src/main/java/org/odpi/openmetadata/repositoryservices/connectors/stores/metadatacollectionstore/properties/typedefs/TypeDefPatch.java
robustness-copilot_data_680
/** * Calculates the coordinate of the intersection point of the orthogonal projection * of a given point on a line segment with that line segment. The line segment * is given by two points, <code>lineFrom</code> and <code>lineTo</code>. If the * projection point does not lie *on* the line segment (but only somewhere on * the extension of the line segment, i.e. the infinite line), the end point of * the line segment which is closest to the given point is returned. * * <br><br> * The 3D version was adapted from the documentation of * <a href="http://www.geometrictools.com/Documentation/DistancePointLine.pdf"> * David Eberly/a>. * * @param lineFrom The start point of the line segment * @param lineTo The end point of the line segment * @param point The point whose distance to the line segment should be calculated * @return the <code>coordinate</code> of the intersection point of the orthogonal * projection of a given point on a line segment with that line segment * * @author dziemke, jwjoubert */ public static Coord orthogonalProjectionOnLineSegment(final Coord lineFrom, final Coord lineTo, final Coord point){ if (!lineFrom.hasZ() && !lineTo.hasZ() && !point.hasZ()) { double lineDX = lineTo.getX() - lineFrom.getX(); double lineDY = lineTo.getY() - lineFrom.getY(); if ((lineDX == 0.0) && (lineDY == 0.0)) { return lineFrom; } double u = ((point.getX() - lineFrom.getX()) * lineDX + (point.getY() - lineFrom.getY()) * lineDY) / (lineDX * lineDX + lineDY * lineDY); if (u <= 0) { return lineFrom; } if (u >= 1) { return lineTo; } return new Coord(lineFrom.getX() + u * lineDX, lineFrom.getY() + u * lineDY); } else if (lineFrom.hasZ() && lineTo.hasZ() && point.hasZ()) { Coord direction = minus(lineTo, lineFrom); double t0 = dotProduct(direction, minus(point, lineFrom)) / dotProduct(direction, direction); Coord q = plus(lineFrom, scalarMult(t0, direction)); return q; } else { if (!onlyOnceWarnGiven) { Logger.getLogger(CoordUtils.class).warn("Mix of 2D / 3D coordinates. Assuming 2D only.\n" + Gbl.ONLYONCE); onlyOnceWarnGiven = true; } return orthogonalProjectionOnLineSegment(new Coord(lineFrom.getX(), lineFrom.getY()), new Coord(lineTo.getX(), lineTo.getY()), new Coord(point.getX(), point.getY())); } }
/matsim/src/main/java/org/matsim/core/utils/geometry/CoordUtils.java
robustness-copilot_data_681
/** * Finds the best fallback for the given exception type and apply it to * the exception or throw the original error if no fallback found. * @param exp The original exception * @return Result of the most suitable fallback * @throws Exception The original exception if no fallback found */ private T fallback(final Throwable exp) throws Exception{ final Iterator<Map.Entry<Fallback<T>, Integer>> candidates = new Sorted<>(Comparator.comparing(Map.Entry::getValue), new Filtered<>(new org.cactoos.func.Flattened<>(entry -> new Not(new Equals<Integer, Integer>(entry::getValue, new Constant<>(Integer.MIN_VALUE)))), new MapOf<>(fbk -> fbk, fbk -> fbk.support(exp), this.fallbacks).entrySet().iterator())); if (candidates.hasNext()) { return candidates.next().getKey().apply(exp); } else { throw new Exception("No fallback found - throw the original exception", exp); } }
/src/main/java/org/cactoos/scalar/ScalarWithFallback.java
robustness-copilot_data_682
/** * Handle fragment grouping of a reaction that specifies certain disconnected components * are actually considered a single molecule. Normally used for salts, [Na+].[OH-]. * * @param rxn reaction * @param cxstate state */ private void handleFragmentGrouping(IReaction rxn, CxSmilesState cxstate){ if (cxstate.fragGroups == null && cxstate.racemicFrags == null) return; final int reactant = 1; final int agent = 2; final int product = 3; List<IAtomContainer> fragMap = new ArrayList<>(); Map<IAtomContainer, Integer> roleMap = new HashMap<>(); for (IAtomContainer mol : rxn.getReactants().atomContainers()) { fragMap.add(mol); roleMap.put(mol, reactant); } for (IAtomContainer mol : rxn.getAgents().atomContainers()) { fragMap.add(mol); roleMap.put(mol, agent); } for (IAtomContainer mol : rxn.getProducts().atomContainers()) { fragMap.add(mol); roleMap.put(mol, product); } if (cxstate.racemicFrags != null) { for (Integer grp : cxstate.racemicFrags) { if (grp >= fragMap.size()) continue; IAtomContainer mol = fragMap.get(grp); if (mol == null) continue; for (IStereoElement<?, ?> e : mol.stereoElements()) { if (e.getConfigClass() == IStereoElement.TH) { e.setGroupInfo(IStereoElement.GRP_RAC1); } } } } if (cxstate.fragGroups != null) { boolean invalid = false; Set<Integer> visit = new HashSet<>(); for (List<Integer> grouping : cxstate.fragGroups) { if (grouping.get(0) >= fragMap.size()) continue; IAtomContainer dest = fragMap.get(grouping.get(0)); if (dest == null) continue; if (!visit.add(grouping.get(0))) invalid = true; for (int i = 1; i < grouping.size(); i++) { if (!visit.add(grouping.get(i))) invalid = true; if (grouping.get(i) >= fragMap.size()) continue; IAtomContainer src = fragMap.get(grouping.get(i)); if (src != null) { dest.add(src); roleMap.put(src, 0); } } } if (!invalid) { rxn.getReactants().removeAllAtomContainers(); rxn.getAgents().removeAllAtomContainers(); rxn.getProducts().removeAllAtomContainers(); for (IAtomContainer mol : fragMap) { switch(roleMap.get(mol)) { case reactant: rxn.getReactants().addAtomContainer(mol); break; case product: rxn.getProducts().addAtomContainer(mol); break; case agent: rxn.getAgents().addAtomContainer(mol); break; } } } } }
/storage/smiles/src/main/java/org/openscience/cdk/smiles/SmilesParser.java
robustness-copilot_data_683
/** * Routes a trip between the given O/D pair, with the given main mode. * * @param mainMode the main mode for the trip * @param fromFacility a {@link Facility} representing the departure location * @param toFacility a {@link Facility} representing the arrival location * @param departureTime the departure time * @param person the {@link Person} to route * @return a list of {@link PlanElement}, in proper order, representing the trip. * * @throws UnknownModeException if no RoutingModule is registered for the * given mode. */ public synchronized List<? extends PlanElement> calcRoute(final String mainMode, final Facility fromFacility, final Facility toFacility, final double departureTime, final Person person){ Gbl.assertNotNull(fromFacility); Gbl.assertNotNull(toFacility); RoutingModule module = routingModules.get(mainMode); if (module != null) { List<? extends PlanElement> trip = module.calcRoute(fromFacility, toFacility, departureTime, person); if (trip == null) { trip = fallbackRoutingModule.calcRoute(fromFacility, toFacility, departureTime, person); } for (Leg leg : TripStructureUtils.getLegs(trip)) { TripStructureUtils.setRoutingMode(leg, mainMode); } return trip; } throw new UnknownModeException("unregistered main mode |" + mainMode + "|: does not pertain to " + routingModules.keySet()); }
/matsim/src/main/java/org/matsim/core/router/TripRouter.java
robustness-copilot_data_684
/** * Look for type hints in the name of a column to extract a usable type. * Also look for array hints as well. <br> * Possible formats: * <ul> * <li>column-name - A column named "column-name" </li> * <li>col@int - An integer column named "col" </li> * <li>col2@int[] - An integer array colum named "col2", assumes standard * delimiter (,) </li> * <li>col3@string[] or col3@[] - A String array named "col3", assumes * standard delimiter (,)</li> * <li>col4@string[||] - A string array where values are using a custom * delimiter (||)</li> * </ul> * * @param name * @return */ private Optional<Class> detectTypeFromName(String name){ boolean isArray = false; Class detectedClass = Object.class; if (name.contains("@")) { String typeStr = StringUtils.substringAfter(name, "@"); if (typeStr.contains("[")) { typeStr = StringUtils.substringBefore(typeStr, "["); } detectedClass = getClassFromName(typeStr); } if (name.endsWith("]")) { isArray = true; String delimiter = StringUtils.substringBetween(name, "[", "]"); if (!StringUtils.isEmpty(delimiter)) { String colName = convertHeaderName(name); delimiters.put(colName, delimiter); } } if (isArray) { return getArrayType(Optional.of(detectedClass)); } else { return Optional.of(detectedClass); } }
/bundle/src/main/java/com/adobe/acs/commons/data/Spreadsheet.java
robustness-copilot_data_685
/** * Finds the cluster of nodes of which <code>startNode</code> is part of. The cluster * contains all nodes which can be reached starting at <code>startNode</code> * and from where it is also possible to return again to <code>startNode</code>. * * @param startNode the node to start building the cluster * @param network the network the startNode is part of * @return cluster of nodes of which <code>startNode</code> is part of */ private Map<Id<Node>, Node> findCluster(final Node startNode, final Network network){ final Map<Node, DoubleFlagRole> nodeRoles = new HashMap<>(network.getNodes().size()); ArrayList<Node> pendingForward = new ArrayList<>(); ArrayList<Node> pendingBackward = new ArrayList<>(); TreeMap<Id<Node>, Node> clusterNodes = new TreeMap<>(); clusterNodes.put(startNode.getId(), startNode); DoubleFlagRole r = getDoubleFlag(startNode, nodeRoles); r.forwardFlag = true; r.backwardFlag = true; pendingForward.add(startNode); pendingBackward.add(startNode); // step through the network in forward mode while (pendingForward.size() > 0) { int idx = pendingForward.size() - 1; // get the last element to prevent object shifting in the array Node currNode = pendingForward.remove(idx); for (Link link : currNode.getOutLinks().values()) { Node node = link.getToNode(); r = getDoubleFlag(node, nodeRoles); if (!r.forwardFlag) { r.forwardFlag = true; pendingForward.add(node); } } } // now step through the network in backward mode while (pendingBackward.size() > 0) { int idx = pendingBackward.size() - 1; // get the last element to prevent object shifting in the array Node currNode = pendingBackward.remove(idx); for (Link link : currNode.getInLinks().values()) { Node node = link.getFromNode(); r = getDoubleFlag(node, nodeRoles); if (!r.backwardFlag) { r.backwardFlag = true; pendingBackward.add(node); if (r.forwardFlag) { // the node can be reached forward and backward, add it to the cluster clusterNodes.put(node.getId(), node); } } } } return clusterNodes; }
/matsim/src/main/java/org/matsim/core/network/algorithms/NetworkCleaner.java
robustness-copilot_data_686
/** * Applies the MDL valence model to atoms using the explicit valence (bond * order sum) and charge to determine the correct number of implicit * hydrogens. The model is not applied if the explicit valence is less than * 0 - this is the case when a query bond was read for an atom. * * @param atom the atom to apply the model to * @param unpaired unpaired electron count * @param explicitValence the explicit valence (bond order sum) */ private void applyMDLValenceModel(IAtom atom, int explicitValence, int unpaired){ if (atom.getValency() != null) { if (atom.getValency() >= explicitValence) atom.setImplicitHydrogenCount(atom.getValency() - (explicitValence - unpaired)); else atom.setImplicitHydrogenCount(0); } else { Integer element = atom.getAtomicNumber(); if (element == null) element = 0; Integer charge = atom.getFormalCharge(); if (charge == null) charge = 0; int implicitValence = MDLValence.implicitValence(element, charge, explicitValence); if (implicitValence < explicitValence) { atom.setValency(explicitValence); atom.setImplicitHydrogenCount(0); } else { atom.setValency(implicitValence); atom.setImplicitHydrogenCount(implicitValence - explicitValence); } } }
/storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Reader.java
robustness-copilot_data_687
/** * Adds the specified data entry to one or more split results, recording its location if it is not wholly * in the first split result. * @param entry a data entry */ private void addToSplitResult(DataEntry entry){ while (entry.getRemainingLength() > 0) { remainingRoom -= entry.addToMap(current, remainingRoom); if (remainingRoom == 0) { recordSplitResult(); startSplitResult(); } } }
/operator/src/main/java/oracle/kubernetes/operator/helpers/ConfigMapSplitter.java
robustness-copilot_data_688
/** * Returns either quoted value (with double-quotes) -- if argument non-null * String -- or String NULL (no quotes) (if null). * * @since 2.9 */ public static String quotedOr(Object str, String forNull){ if (str == null) { return forNull; } return String.format("\"%s\"", str); }
/src/main/java/com/fasterxml/jackson/databind/util/ClassUtil.java
robustness-copilot_data_689
/** * Checks if {@code s} contains a "truthy" value. * @param s * @return {@code true} iff {@code s} is not {@code null} and is "truthy" word. * @see #TRUE_VALUES */ public static boolean isTrue(String s){ return (s != null) && TRUE_VALUES.contains(s.trim().toLowerCase()); }
/src/main/java/edu/harvard/iq/dataverse/util/StringUtil.java
robustness-copilot_data_690
/** * Find the index of a hetroatom in a cycle. A hetroatom in MMFF is the unique atom that * contributes a pi-lone-pair to the aromatic system. * * @param cycle aromatic cycle, |C| = 5 * @param contribution vector of p electron contributions from each vertex * @return index of hetroatom, if none found index is < 0. */ static int indexOfHetro(int[] cycle, int[] contribution){ int index = -1; for (int i = 0; i < cycle.length - 1; i++) { if (contribution[cycle[i]] == 2) index = index == -1 ? i : -2; } return index; }
/tool/forcefield/src/main/java/org/openscience/cdk/forcefield/mmff/MmffAromaticTypeMapping.java
robustness-copilot_data_691
/** * Finds a vertex in 'vs' which is not 'u' or 'x'. * . * @param vs fixed size array of 3 elements * @param u a vertex in 'vs' * @param x another vertex in 'vs' * @return the other vertex */ private static int findOther(int[] vs, int u, int x){ for (int v : vs) { if (v != u && v != x) return v; } throw new IllegalArgumentException("vs[] did not contain another vertex"); }
/tool/hash/src/main/java/org/openscience/cdk/hash/stereo/DoubleBondElementEncoderFactory.java
robustness-copilot_data_692
/** * Select the theory and basis set from the first archive line. * * @param line Description of the Parameter * @return Description of the Return Value */ private String parseLevelOfTheory(String line){ StringBuffer summary = new StringBuffer(); summary.append(line); try { do { line = input.readLine().trim(); summary.append(line); } while (!(line.indexOf('@') >= 0)); } catch (Exception exc) { logger.debug("syntax problem while parsing summary of g98 section: "); logger.debug(exc); } logger.debug("parseLoT(): " + summary.toString()); StringTokenizer st1 = new StringTokenizer(summary.toString(), "\\"); if (st1.countTokens() < 6) { return null; } for (int i = 0; i < 4; ++i) { st1.nextToken(); } return st1.nextToken() + "/" + st1.nextToken(); }
/storage/io/src/main/java/org/openscience/cdk/io/Gaussian98Reader.java
robustness-copilot_data_693
/** * batch delete some shenyu dicts by some id list. * * @param ids shenyu dict id list. * @return {@linkplain ShenyuAdminResult} */ public ShenyuAdminResult deleteShenyuDicts(@RequestBody @NotEmpty final List<@NotBlank String> ids){ Integer deleteCount = shenyuDictService.deleteShenyuDicts(ids); return ShenyuAdminResult.success(ShenyuResultMessage.DELETE_SUCCESS, deleteCount); }
/shenyu-admin/src/main/java/org/apache/shenyu/admin/controller/ShenyuDictController.java
robustness-copilot_data_694
/** * Thrown when the reflective bean converter has no access to a parameter name. Compilation * must be done using <code>parameters</code> compiler option. * * @param parameter Parameter. * @return Usage exception. */ public static Usage parameterNameNotPresent(@Nonnull Parameter parameter){ Executable executable = parameter.getDeclaringExecutable(); int p = Stream.of(executable.getParameters()).collect(Collectors.toList()).indexOf(parameter); String message = "Unable to provision parameter at position: '" + p + "', require by: " + ProvisioningException.toString(parameter.getDeclaringExecutable()) + ". Parameter's name is missing"; return new Usage(message, "bean-converter-parameter-name-missing"); }
/jooby/src/main/java/io/jooby/Usage.java
robustness-copilot_data_695
/** * Combines the separate stereo encoder factories into a single factory. * * @return a single stereo encoder factory */ private StereoEncoderFactory makeStereoEncoderFactory(){ if (stereoEncoders.isEmpty()) { return StereoEncoderFactory.EMPTY; } else if (stereoEncoders.size() == 1) { return stereoEncoders.get(0); } else { StereoEncoderFactory factory = new ConjugatedEncoderFactory(stereoEncoders.get(0), stereoEncoders.get(1)); for (int i = 2; i < stereoEncoders.size(); i++) { factory = new ConjugatedEncoderFactory(factory, stereoEncoders.get(i)); } return factory; } }
/tool/hash/src/main/java/org/openscience/cdk/hash/HashGeneratorMaker.java
robustness-copilot_data_696
/** * Check if there are any feasible mappings left for the query vertex n. We * scan the compatibility matrix to see if any value is > 0. * * @param n query vertex * @return a candidate is present */ private boolean hasCandidate(int n){ for (int j = (n * matrix.mCols), end = (j + matrix.mCols); j < end; j++) if (matrix.get(j)) return true; return false; }
/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/UllmannState.java
robustness-copilot_data_697
/** * Generate coordinates for all atoms which are singly bonded and have no * coordinates. This is useful when hydrogens are present but have no coordinates. * It knows about C, O, N, S only and will give tetrahedral or trigonal * geometry elsewhere. Bond lengths are computed from covalent radii or taken * out of a parameter set if available. Angles are tetrahedral or trigonal * * @param atomContainer the set of atoms involved * @throws CDKException * @cdk.keyword coordinate calculation * @cdk.keyword 3D model */ public void add3DCoordinatesForSinglyBondedLigands(IAtomContainer atomContainer) throws CDKException{ IAtom refAtom = null; IAtom atomC = null; int nwanted = 0; for (int i = 0; i < atomContainer.getAtomCount(); i++) { refAtom = atomContainer.getAtom(i); if (refAtom.getAtomicNumber() != IElement.H && hasUnsetNeighbour(refAtom, atomContainer)) { IAtomContainer noCoords = getUnsetAtomsInAtomContainer(refAtom, atomContainer); IAtomContainer withCoords = getPlacedAtomsInAtomContainer(refAtom, atomContainer); if (withCoords.getAtomCount() > 0) { atomC = getPlacedHeavyAtomInAtomContainer(withCoords.getAtom(0), refAtom, atomContainer); } if (refAtom.getFormalNeighbourCount() == 0 && refAtom.getAtomicNumber() == IElement.C) { nwanted = noCoords.getAtomCount(); } else if (refAtom.getFormalNeighbourCount() == 0 && refAtom.getAtomicNumber() != IElement.C) { nwanted = 4; } else { nwanted = refAtom.getFormalNeighbourCount() - withCoords.getAtomCount(); } Point3d[] newPoints = get3DCoordinatesForLigands(refAtom, noCoords, withCoords, atomC, nwanted, DEFAULT_BOND_LENGTH_H, -1); for (int j = 0; j < noCoords.getAtomCount(); j++) { IAtom ligand = noCoords.getAtom(j); Point3d newPoint = rescaleBondLength(refAtom, ligand, newPoints[j]); ligand.setPoint3d(newPoint); ligand.setFlag(CDKConstants.ISPLACED, true); } noCoords.removeAllElements(); withCoords.removeAllElements(); } } }
/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomTetrahedralLigandPlacer3D.java
robustness-copilot_data_698
/** * Method for finding all super classes (but not super interfaces) of given class, * starting with the immediate super class and ending in the most distant one. * Class itself is included if <code>addClassItself</code> is true. *<p> * NOTE: mostly/only called to resolve mix-ins as that's where we do not care * about fully-resolved types, just associated annotations. * * @since 2.7 */ public static List<Class<?>> findSuperClasses(Class<?> cls, Class<?> endBefore, boolean addClassItself){ List<Class<?>> result = new ArrayList<Class<?>>(8); if ((cls != null) && (cls != endBefore)) { if (addClassItself) { result.add(cls); } while ((cls = cls.getSuperclass()) != null) { if (cls == endBefore) { break; } result.add(cls); } } return result; }
/src/main/java/com/fasterxml/jackson/databind/util/ClassUtil.java
robustness-copilot_data_699
/** * Checks some simple heuristics for whether the subgraph query can * realistically be atom subgraph of the supergraph. If, for example, the * number of nitrogen atoms in the query is larger than that of the supergraph * it cannot be part of it. * * @param ac1 the supergraph to be checked. Must not be an IQueryAtomContainer. * @param ac2 the subgraph to be tested for. May be an IQueryAtomContainer. * @return true if the subgraph ac2 has atom chance to be atom subgraph of ac1 * @throws org.openscience.cdk.exception.CDKException if the first molecule is an instance * of IQueryAtomContainer */ private static boolean testSubgraphHeuristics(IAtomContainer ac1, IAtomContainer ac2) throws CDKException{ if (ac1 instanceof IQueryAtomContainer) { throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); } int ac1SingleBondCount = 0; int ac1DoubleBondCount = 0; int ac1TripleBondCount = 0; int ac1AromaticBondCount = 0; int ac2SingleBondCount = 0; int ac2DoubleBondCount = 0; int ac2TripleBondCount = 0; int ac2AromaticBondCount = 0; int ac1SCount = 0; int ac1OCount = 0; int ac1NCount = 0; int ac1FCount = 0; int ac1ClCount = 0; int ac1BrCount = 0; int ac1ICount = 0; int ac1CCount = 0; int ac2SCount = 0; int ac2OCount = 0; int ac2NCount = 0; int ac2FCount = 0; int ac2ClCount = 0; int ac2BrCount = 0; int ac2ICount = 0; int ac2CCount = 0; IBond bond; IAtom atom; for (int i = 0; i < ac1.getBondCount(); i++) { bond = ac1.getBond(i); if (bond.getFlag(CDKConstants.ISAROMATIC)) { ac1AromaticBondCount++; } else if (bond.getOrder() == IBond.Order.SINGLE) { ac1SingleBondCount++; } else if (bond.getOrder() == IBond.Order.DOUBLE) { ac1DoubleBondCount++; } else if (bond.getOrder() == IBond.Order.TRIPLE) { ac1TripleBondCount++; } } for (int i = 0; i < ac2.getBondCount(); i++) { bond = ac2.getBond(i); if (bond instanceof IQueryBond) { continue; } if (bond.getFlag(CDKConstants.ISAROMATIC)) { ac2AromaticBondCount++; } else if (bond.getOrder() == IBond.Order.SINGLE) { ac2SingleBondCount++; } else if (bond.getOrder() == IBond.Order.DOUBLE) { ac2DoubleBondCount++; } else if (bond.getOrder() == IBond.Order.TRIPLE) { ac2TripleBondCount++; } } if (ac2SingleBondCount > ac1SingleBondCount) { return false; } if (ac2AromaticBondCount > ac1AromaticBondCount) { return false; } if (ac2DoubleBondCount > ac1DoubleBondCount) { return false; } if (ac2TripleBondCount > ac1TripleBondCount) { return false; } for (int i = 0; i < ac1.getAtomCount(); i++) { atom = ac1.getAtom(i); if (atom.getSymbol().equals("S")) { ac1SCount++; } else if (atom.getSymbol().equals("N")) { ac1NCount++; } else if (atom.getSymbol().equals("O")) { ac1OCount++; } else if (atom.getSymbol().equals("F")) { ac1FCount++; } else if (atom.getSymbol().equals("Cl")) { ac1ClCount++; } else if (atom.getSymbol().equals("Br")) { ac1BrCount++; } else if (atom.getSymbol().equals("I")) { ac1ICount++; } else if (atom.getSymbol().equals("C")) { ac1CCount++; } } for (int i = 0; i < ac2.getAtomCount(); i++) { atom = ac2.getAtom(i); if (atom instanceof IQueryAtom) { continue; } if (atom.getSymbol().equals("S")) { ac2SCount++; } else if (atom.getSymbol().equals("N")) { ac2NCount++; } else if (atom.getSymbol().equals("O")) { ac2OCount++; } else if (atom.getSymbol().equals("F")) { ac2FCount++; } else if (atom.getSymbol().equals("Cl")) { ac2ClCount++; } else if (atom.getSymbol().equals("Br")) { ac2BrCount++; } else if (atom.getSymbol().equals("I")) { ac2ICount++; } else if (atom.getSymbol().equals("C")) { ac2CCount++; } } if (ac1SCount < ac2SCount) { return false; } if (ac1NCount < ac2NCount) { return false; } if (ac1OCount < ac2OCount) { return false; } if (ac1FCount < ac2FCount) { return false; } if (ac1ClCount < ac2ClCount) { return false; } if (ac1BrCount < ac2BrCount) { return false; } if (ac1ICount < ac2ICount) { return false; } return ac1CCount >= ac2CCount; }
/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java
robustness-copilot_data_700
/** * Returns true if and only if the subject has the given group ID. */ public static boolean hasGid(Subject subject, long gid){ Set<GidPrincipal> principals = subject.getPrincipals(GidPrincipal.class); for (GidPrincipal principal : principals) { if (principal.getGid() == gid) { return true; } } return false; }
/modules/common/src/main/java/org/dcache/auth/Subjects.java