id stringlengths 25 27 | content stringlengths 190 15.4k | max_stars_repo_path stringlengths 31 217 |
|---|---|---|
robustness-copilot_data_501 | /**
* Creates matrix with info about the bonds in the amino acids.
* 0 = bond id, 1 = atom1 in bond, 2 = atom2 in bond, 3 = bond order.
* @return info
*/
public static int[][] aaBondInfo(){
if (aminoAcids == null) {
createAAs();
}
int[][] info = new int[153][4];
int counter = 0;
int total = 0;
for (int aa = 0; aa < aminoAcids.length; aa++) {
AminoAcid acid = aminoAcids[aa];
LOGGER.debug("#bonds for ", acid.getProperty(RESIDUE_NAME).toString(), " = " + acid.getBondCount());
total += acid.getBondCount();
LOGGER.debug("total #bonds: ", total);
Iterator<IBond> bonds = acid.bonds().iterator();
while (bonds.hasNext()) {
IBond bond = (IBond) bonds.next();
info[counter][0] = counter;
info[counter][1] = acid.indexOf(bond.getBegin());
info[counter][2] = acid.indexOf(bond.getEnd());
info[counter][3] = bond.getOrder().numeric();
counter++;
}
}
if (counter > 153) {
LOGGER.error("Error while creating AA info! Bond count is too large: ", counter);
return null;
}
return info;
} | /storage/pdb/src/main/java/org/openscience/cdk/templates/AminoAcids.java |
robustness-copilot_data_502 | /**
* Convenience function to center an atom symbol on a specified point. The
* centering depends on the symbol alignment.
*
* @param x x-axis location
* @param y y-axis location
* @return the centered symbol (new instance)
*/
AtomSymbol center(double x, double y){
Point2D center = getAlignmentCenter();
return translate(x - center.getX(), y - center.getY());
} | /display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/AtomSymbol.java |
robustness-copilot_data_503 | /**
* Check that two elements are in the same cell of the partition.
*
* @param elementI an element in the partition
* @param elementJ an element in the partition
* @return true if both elements are in the same cell
*/
public boolean inSameCell(int elementI, int elementJ){
for (int cellIndex = 0; cellIndex < size(); cellIndex++) {
SortedSet<Integer> cell = getCell(cellIndex);
if (cell.contains(elementI) && cell.contains(elementJ)) {
return true;
}
}
return false;
} | /tool/group/src/main/java/org/openscience/cdk/group/Partition.java |
robustness-copilot_data_504 | /**
* Builds the context for a schema element without the asset context.
*
* @param userId the unique identifier for the user
* @param entityDetail the entity for which the context is build
*
* @return the context of the schema element
*
* @throws OCFCheckedExceptionBase checked exception for reporting errors found when using OCF connectors
*/
public Map<String, RelationshipsContext> buildSchemaElementContext(String userId, EntityDetail entityDetail) throws OCFCheckedExceptionBase{
final String methodName = "buildSchemaElementContext";
handlerHelper.validateAsset(entityDetail, methodName, supportedZones);
Map<String, RelationshipsContext> context = new HashMap<>();
final String typeDefName = entityDetail.getType().getTypeDefName();
Set<GraphContext> columnContext = new HashSet<>();
switch(typeDefName) {
case TABULAR_COLUMN:
if (!isInternalTabularColumn(userId, entityDetail)) {
columnContext = buildTabularColumnContext(userId, entityDetail);
}
break;
case TABULAR_FILE_COLUMN:
columnContext = buildTabularColumnContext(userId, entityDetail);
break;
case RELATIONAL_COLUMN:
columnContext = buildRelationalColumnContext(userId, entityDetail);
break;
case EVENT_SCHEMA_ATTRIBUTE:
columnContext = buildEventSchemaAttributeContext(userId, entityDetail);
break;
default:
return context;
}
context.put(AssetLineageEventType.COLUMN_CONTEXT_EVENT.getEventTypeName(), new RelationshipsContext(entityDetail.getGUID(), columnContext));
return 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_505 | /**
* Adds some parameters to the given Node then adds it to the set of pending
* nodes.
*
* @param l
* The link from which we came to this Node.
* @param n
* The Node to add to the pending nodes.
* @param pendingNodes
* The set of pending nodes.
* @param currTime
* The time at which we started to traverse l.
* @param currCost
* The cost at the time we started to traverse l.
* @param toNode
* The target Node of the route.
* @return true if the node was added to the pending nodes, false otherwise
* (e.g. when the same node already has an earlier visiting time).
*/
protected boolean addToPendingNodes(final Link l, final Node n, final RouterPriorityQueue<Node> pendingNodes, final double currTime, final double currCost, final Node toNode){
final double travelTime = this.timeFunction.getLinkTravelTime(l, currTime, this.person, this.vehicle);
final double travelCost = this.costFunction.getLinkTravelDisutility(l, currTime, this.person, this.vehicle);
final DijkstraNodeData data = getData(n);
if (!data.isVisited(getIterationId())) {
visitNode(n, data, pendingNodes, currTime + travelTime, currCost + travelCost, l);
return true;
}
final double nCost = data.getCost();
final double totalCost = currCost + travelCost;
if (totalCost < nCost) {
revisitNode(n, data, pendingNodes, currTime + travelTime, totalCost, l);
return true;
} else if (totalCost == nCost) {
Link prevLink = data.getPrevLink();
if (prevLink != null && prevLink.getId().compareTo(l.getId()) > 0) {
revisitNode(n, data, pendingNodes, currTime + travelTime, totalCost, l);
return true;
}
}
return false;
} | /matsim/src/main/java/org/matsim/core/router/Dijkstra.java |
robustness-copilot_data_506 | /**
* Convert a set of asserted LoAs so it includes all equivalent LoAs.
*
* @param entity the kind of identity asserted, if known.
* @param asserted a collection of LoA asserted by some external agent.
* @return all LoAs for this identity.
*/
public static EnumSet<LoA> withImpliedLoA(Optional<EntityDefinition> entity, Collection<LoA> asserted){
Map<LoA, LoA> mapping = entity.filter(PERSON::equals).map(e -> PERSONAL_EQUIVALENT_LOA).orElse(GENERIC_EQUIVALENT_LOA);
EnumSet<LoA> result = EnumSet.copyOf(asserted);
Collection<LoA> considered = asserted;
do {
EnumSet<LoA> additional = considered.stream().map(mapping::get).filter(Objects::nonNull).collect(Collectors.toCollection(() -> EnumSet.noneOf(LoA.class)));
result.addAll(additional);
considered = additional;
} while (!considered.isEmpty());
return result;
} | /modules/common/src/main/java/org/dcache/auth/LoAs.java |
robustness-copilot_data_507 | /**
* Read non-structural data from input and store as properties the provided
* 'container'. Non-structural data appears in a structure data file (SDF)
* after an Molfile and before the record deliminator ('$$$$'). The data
* consists of one or more Data Header and Data blocks, an example is seen
* below.
*
* <pre>{@code
* > 29 <DENSITY>
* 0.9132 - 20.0
*
* > 29 <BOILING.POINT>
* 63.0 (737 MM)
* 79.0 (42 MM)
*
* > 29 <ALTERNATE.NAMES>
* SYLVAN
*
* > 29 <DATE>
* 09-23-1980
*
* > 29 <CRC.NUMBER>
* F-0213
*
* }</pre>
*
*
* @param input input source
* @param container the container
* @throws IOException an error occur whilst reading the input
*/
static void readNonStructuralData(final BufferedReader input, final IAtomContainer container) throws IOException{
String line, header = null;
boolean wrap = false;
final StringBuilder data = new StringBuilder(80);
while (!endOfRecord(line = input.readLine())) {
final String newHeader = dataHeader(line);
if (newHeader != null) {
if (header != null)
container.setProperty(header, data.toString());
header = newHeader;
wrap = false;
data.setLength(0);
} else {
if (data.length() > 0 || !line.equals(" "))
line = line.trim();
if (line.isEmpty())
continue;
if (!wrap && data.length() > 0)
data.append('\n');
data.append(line);
wrap = line.length() == 80;
}
}
if (header != null)
container.setProperty(header, data.toString());
} | /storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Reader.java |
robustness-copilot_data_508 | /**
* Inserts a trip between two activities in the sequence of plan elements
* returned by the {@link Plan#getPlanElements()} method of a plan. Note
* that the plan will be modified only if the returned list is the internal
* reference!
* <p></p>
* Note that this methods returns a unique solution because it expects the activity object references as arguments, which are unique.
*
* @param plan the plan to modify
* @param origin the activity to use as origin. It must be a member of the list of plan elements.
* @param trip the trip to insert
* @param destination the destination activity. It must be a member of the list.
* @return the "old trip": the sequence of plan elements originally existing between the origin and the destination
*/
public static List<PlanElement> insertTrip(final Plan plan, final Activity origin, final List<? extends PlanElement> trip, final Activity destination){
return insertTrip(plan.getPlanElements(), origin, trip, destination);
} | /matsim/src/main/java/org/matsim/core/router/TripRouter.java |
robustness-copilot_data_509 | /**
* This uses a gaussian distance weighting to calculate the impact of link based emissions onto the centroid of a
* grid cell. The level of emission is assumed to be linear over the link. The calculation is described in Argawal's
* PhD thesis https://depositonce.tu-berlin.de/handle/11303/6266 in Appendix A.2
*
* @param from Link from coordinate
* @param to Link to coordinate
* @param cellCentroid centroid of the impacted cell
* @return weight factor by which the emission value should be multiplied to calculate the impact of the cell
*/
public static double calculateWeightFromLine(final Coordinate from, final Coordinate to, final Coordinate cellCentroid, final double smoothingRadius){
if (smoothingRadius <= 0)
throw new IllegalArgumentException("smoothing radius must be greater 0");
double a = from.distance(cellCentroid) * from.distance(cellCentroid);
double b = (to.x - from.x) * (from.x - cellCentroid.x) + (to.y - from.y) * (from.y - cellCentroid.y);
double linkLength = from.distance(to);
double c = (smoothingRadius * Math.sqrt(Math.PI) / (linkLength * 2)) * Math.exp(-(a - (b * b / (linkLength * linkLength))) / (smoothingRadius * smoothingRadius));
double upperLimit = linkLength + b / linkLength;
double lowerLimit = b / linkLength;
double integrationUpperLimit = Erf.erf(upperLimit / smoothingRadius);
double integrationLowerLimit = Erf.erf(lowerLimit / smoothingRadius);
double weight = c * (integrationUpperLimit - integrationLowerLimit);
if (weight < 0)
throw new RuntimeException("Weight may not be negative! Value: " + weight);
return weight;
} | /contribs/analysis/src/main/java/org/matsim/contrib/analysis/spatial/SpatialInterpolation.java |
robustness-copilot_data_510 | /**
* Calculates the descriptor value using the {@link VABCVolume} class.
*
* @param atomContainer The {@link IAtomContainer} whose volume is to be calculated
* @return A double containing the volume
*/
public DescriptorValue calculate(IAtomContainer atomContainer){
double volume;
try {
volume = VABCVolume.calculate(clone(atomContainer));
} catch (CDKException exception) {
return getDummyDescriptorValue(exception);
}
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new DoubleResult(volume), getDescriptorNames());
} | /descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/VABCDescriptor.java |
robustness-copilot_data_511 | /**
* Writes a Molecule to an OutputStream in MDL sdf format.
*
* @param container Molecule that is written to an OutputStream
*/
public void writeMolecule(IAtomContainer container) throws Exception{
final int dim = getNumberOfDimensions(container);
StringBuilder line = new StringBuilder();
Map<Integer, Integer> rgroups = null;
Map<Integer, String> aliases = null;
String title = container.getTitle();
if (title == null)
title = "";
if (title.length() > 80)
title = title.substring(0, 80);
writer.write(title);
writer.write('\n');
writer.write(" ");
writer.write(getProgName());
writer.write(new SimpleDateFormat("MMddyyHHmm").format(System.currentTimeMillis()));
if (dim != 0) {
writer.write(Integer.toString(dim));
writer.write('D');
}
writer.write('\n');
String comment = (String) container.getProperty(CDKConstants.REMARK);
if (comment == null)
comment = "";
if (comment.length() > 80)
comment = comment.substring(0, 80);
writer.write(comment);
writer.write('\n');
Map<IAtom, ITetrahedralChirality> atomstereo = new HashMap<>();
Map<IAtom, Integer> atomindex = new HashMap<>();
for (IStereoElement element : container.stereoElements()) if (element instanceof ITetrahedralChirality)
atomstereo.put(((ITetrahedralChirality) element).getChiralAtom(), (ITetrahedralChirality) element);
for (IAtom atom : container.atoms()) atomindex.put(atom, atomindex.size());
line.append(formatMDLInt(container.getAtomCount(), 3));
line.append(formatMDLInt(container.getBondCount(), 3));
Map<Integer, IAtom> atomLists = new LinkedHashMap<>();
for (int f = 0; f < container.getAtomCount(); f++) {
if (container.getAtom(f) instanceof IQueryAtom) {
QueryAtom queryAtom = (QueryAtom) AtomRef.deref(container.getAtom(f));
Expr expr = queryAtom.getExpression();
if (isValidAtomListExpression(expr)) {
atomLists.put(f, container.getAtom(f));
}
}
}
line.append(formatMDLInt(atomLists.size(), 3));
line.append(" 0");
line.append(getChiralFlag(atomstereo.values()) ? " 1" : " 0");
line.append(" 0 0 0 0 0999 V2000");
writer.write(line.toString());
writer.write('\n');
for (int f = 0; f < container.getAtomCount(); f++) {
IAtom atom = container.getAtom(f);
line.setLength(0);
switch(dim) {
case 0:
line.append(" 0.0000 0.0000 0.0000 ");
break;
case 2:
if (atom.getPoint2d() != null) {
line.append(formatMDLFloat((float) atom.getPoint2d().x));
line.append(formatMDLFloat((float) atom.getPoint2d().y));
line.append(" 0.0000 ");
} else {
line.append(" 0.0000 0.0000 0.0000 ");
}
break;
case 3:
if (atom.getPoint3d() != null) {
line.append(formatMDLFloat((float) atom.getPoint3d().x));
line.append(formatMDLFloat((float) atom.getPoint3d().y));
line.append(formatMDLFloat((float) atom.getPoint3d().z)).append(" ");
} else {
line.append(" 0.0000 0.0000 0.0000 ");
}
break;
}
if (container.getAtom(f) instanceof IPseudoAtom) {
IPseudoAtom pseudoAtom = (IPseudoAtom) container.getAtom(f);
String label = pseudoAtom.getLabel();
if (label == null)
label = "";
Matcher matcher = NUMERED_R_GROUP.matcher(label);
if ("R".equals(pseudoAtom.getSymbol()) && !label.isEmpty() && matcher.matches()) {
line.append("R# ");
if (rgroups == null) {
rgroups = new TreeMap<Integer, Integer>();
}
rgroups.put(f + 1, Integer.parseInt(matcher.group(1)));
} else {
if (label.length() > 3) {
if (aliases == null)
aliases = new TreeMap<Integer, String>();
aliases.put(f + 1, label);
line.append(formatMDLString(atom.getSymbol(), 3));
} else {
if (!label.isEmpty())
line.append(formatMDLString(label, 3));
else
line.append(formatMDLString(atom.getSymbol(), 3));
}
}
} else if (atomLists.containsKey(f)) {
line.append(formatMDLString("L", 3));
} else {
line.append(formatMDLString(container.getAtom(f).getSymbol(), 3));
}
int[] atomprops = new int[12];
atomprops[0] = determineIsotope(atom);
atomprops[1] = determineCharge(container, atom);
atomprops[2] = determineStereoParity(container, atomstereo, atomindex, atom);
atomprops[5] = determineValence(container, atom);
atomprops[9] = determineAtomMap(atom);
line.append(formatMDLInt(atomprops[0], 2));
line.append(formatMDLInt(atomprops[1], 3));
int last = atomprops.length - 1;
if (!writeDefaultProps.isSet()) {
while (last >= 0) {
if (atomprops[last] != 0)
break;
last--;
}
if (last >= 2 && last < 5)
last = 5;
}
for (int i = 2; i <= last; i++) line.append(formatMDLInt(atomprops[i], 3));
line.append('\n');
writer.write(line.toString());
}
for (IBond bond : container.bonds()) {
line.setLength(0);
if (bond.getAtomCount() != 2) {
logger.warn("Skipping bond with more/less than two atoms: " + bond);
} else {
if (bond.getStereo() == IBond.Stereo.UP_INVERTED || bond.getStereo() == IBond.Stereo.DOWN_INVERTED || bond.getStereo() == IBond.Stereo.UP_OR_DOWN_INVERTED) {
line.append(formatMDLInt(atomindex.get(bond.getEnd()) + 1, 3));
line.append(formatMDLInt(atomindex.get(bond.getBegin()) + 1, 3));
} else {
line.append(formatMDLInt(atomindex.get(bond.getBegin()) + 1, 3));
line.append(formatMDLInt(atomindex.get(bond.getEnd()) + 1, 3));
}
int bondType = 0;
if (bond instanceof QueryBond) {
QueryBond qbond = ((QueryBond) bond);
Expr e = qbond.getExpression();
switch(e.type()) {
case ALIPHATIC_ORDER:
case ORDER:
bondType = e.value();
break;
case IS_AROMATIC:
bondType = 4;
break;
case SINGLE_OR_DOUBLE:
bondType = 5;
break;
case SINGLE_OR_AROMATIC:
bondType = 6;
break;
case DOUBLE_OR_AROMATIC:
bondType = 7;
break;
case TRUE:
bondType = 8;
break;
case OR:
if (e.equals(new Expr(Expr.Type.ALIPHATIC_ORDER, 1).or(new Expr(Expr.Type.ALIPHATIC_ORDER, 2))) || e.equals(new Expr(Expr.Type.ALIPHATIC_ORDER, 2).or(new Expr(Expr.Type.ALIPHATIC_ORDER, 1))))
bondType = 5;
else if (e.equals(new Expr(Expr.Type.ALIPHATIC_ORDER, 1).or(new Expr(Expr.Type.IS_AROMATIC))) || e.equals(new Expr(Expr.Type.IS_AROMATIC).or(new Expr(Expr.Type.ALIPHATIC_ORDER, 1))))
bondType = 6;
else if (e.equals(new Expr(Expr.Type.ALIPHATIC_ORDER, 2).or(new Expr(Expr.Type.IS_AROMATIC))) || e.equals(new Expr(Expr.Type.IS_AROMATIC).or(new Expr(Expr.Type.ALIPHATIC_ORDER, 2))))
bondType = 6;
break;
default:
throw new IllegalArgumentException("Unsupported bond type!");
}
} else {
if (bond.getOrder() != null) {
switch(bond.getOrder()) {
case SINGLE:
case DOUBLE:
case TRIPLE:
if (writeAromaticBondTypes.isSet() && bond.isAromatic())
bondType = 4;
else
bondType = bond.getOrder().numeric();
break;
case UNSET:
if (bond.isAromatic()) {
if (!writeAromaticBondTypes.isSet())
throw new CDKException("Bond at idx " + container.indexOf(bond) + " was an unspecific aromatic bond which should only be used for queries in Molfiles. These can be written if desired by enabling the option 'WriteAromaticBondTypes'.");
bondType = 4;
}
break;
}
}
}
if (bondType == 0)
throw new CDKException("Bond at idx=" + container.indexOf(bond) + " is not supported by Molfile, bond=" + bond.getOrder());
line.append(formatMDLInt(bondType, 3));
line.append(" ");
switch(bond.getStereo()) {
case UP:
line.append("1");
break;
case UP_INVERTED:
line.append("1");
break;
case DOWN:
line.append("6");
break;
case DOWN_INVERTED:
line.append("6");
break;
case UP_OR_DOWN:
line.append("4");
break;
case UP_OR_DOWN_INVERTED:
line.append("4");
break;
case E_OR_Z:
line.append("3");
break;
default:
line.append("0");
}
if (writeDefaultProps.isSet())
line.append(" 0 0 0");
line.append('\n');
writer.write(line.toString());
}
}
for (int i = 0; i < container.getAtomCount(); i++) {
IAtom atom = container.getAtom(i);
if (atom.getProperty(CDKConstants.COMMENT) != null && atom.getProperty(CDKConstants.COMMENT) instanceof String && !((String) atom.getProperty(CDKConstants.COMMENT)).trim().equals("")) {
writer.write("V ");
writer.write(formatMDLInt(i + 1, 3));
writer.write(" ");
writer.write((String) atom.getProperty(CDKConstants.COMMENT));
writer.write('\n');
}
}
for (int i = 0; i < container.getAtomCount(); i++) {
IAtom atom = container.getAtom(i);
Integer charge = atom.getFormalCharge();
if (charge != null && charge != 0) {
writer.write("M CHG 1 ");
writer.write(formatMDLInt(i + 1, 3));
writer.write(" ");
writer.write(formatMDLInt(charge, 3));
writer.write('\n');
}
}
if (container.getSingleElectronCount() > 0) {
Map<Integer, SPIN_MULTIPLICITY> atomIndexSpinMap = new LinkedHashMap<Integer, SPIN_MULTIPLICITY>();
for (int i = 0; i < container.getAtomCount(); i++) {
IAtom atom = container.getAtom(i);
int eCount = container.getConnectedSingleElectronsCount(atom);
switch(eCount) {
case 0:
continue;
case 1:
atomIndexSpinMap.put(i, SPIN_MULTIPLICITY.Monovalent);
break;
case 2:
SPIN_MULTIPLICITY multiplicity = atom.getProperty(CDKConstants.SPIN_MULTIPLICITY);
if (multiplicity != null)
atomIndexSpinMap.put(i, multiplicity);
else {
atomIndexSpinMap.put(i, SPIN_MULTIPLICITY.DivalentSinglet);
}
break;
default:
logger.debug("Invalid number of radicals found: " + eCount);
break;
}
}
Iterator<Map.Entry<Integer, SPIN_MULTIPLICITY>> iterator = atomIndexSpinMap.entrySet().iterator();
for (int i = 0; i < atomIndexSpinMap.size(); i += NN8) {
if (atomIndexSpinMap.size() - i <= NN8) {
writer.write("M RAD" + formatMDLInt(atomIndexSpinMap.size() - i, WIDTH));
writeRadicalPattern(iterator, 0);
} else {
writer.write("M RAD" + formatMDLInt(NN8, WIDTH));
writeRadicalPattern(iterator, 0);
}
writer.write('\n');
}
}
for (int i = 0; i < container.getAtomCount(); i++) {
IAtom atom = container.getAtom(i);
if (!(atom instanceof IPseudoAtom)) {
Integer atomicMass = atom.getMassNumber();
if (!writeMajorIsotopes.isSet() && isMajorIsotope(atom))
atomicMass = null;
if (atomicMass != null) {
writer.write("M ISO 1 ");
writer.write(formatMDLInt(i + 1, 3));
writer.write(" ");
writer.write(formatMDLInt(atomicMass, 3));
writer.write('\n');
}
}
}
if (rgroups != null) {
StringBuilder rgpLine = new StringBuilder();
int cnt = 0;
for (Map.Entry<Integer, Integer> e : rgroups.entrySet()) {
rgpLine.append(formatMDLInt(e.getKey(), 4));
rgpLine.append(formatMDLInt(e.getValue(), 4));
cnt++;
if (cnt == 8) {
rgpLine.insert(0, "M RGP" + formatMDLInt(cnt, 3));
writer.write(rgpLine.toString());
writer.write('\n');
rgpLine = new StringBuilder();
cnt = 0;
}
}
if (cnt != 0) {
rgpLine.insert(0, "M RGP" + formatMDLInt(cnt, 3));
writer.write(rgpLine.toString());
writer.write('\n');
}
}
if (aliases != null) {
for (Map.Entry<Integer, String> e : aliases.entrySet()) {
writer.write("A" + formatMDLInt(e.getKey(), 5));
writer.write('\n');
String label = e.getValue();
if (label.length() > 70)
label = label.substring(0, 70);
writer.write(label);
writer.write('\n');
}
}
writeAtomLists(atomLists, writer);
writeSgroups(container, writer, atomindex);
writer.write("M END");
writer.write('\n');
writer.flush();
} | /storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Writer.java |
robustness-copilot_data_512 | /**
* Checks if the ReplicationStatusManager should make the provides resource w replication status.
*
* @param resource the return
* @return true is the resource is markable resource
* @throws RepositoryException
*/
private boolean accept(final Resource resource) throws RepositoryException{
if (resource == null || ResourceUtil.isNonExistingResource(resource)) {
return false;
}
for (final Map.Entry<String, Pattern> nodeTypeAndPathRestriction : this.pathRestrictionByNodeType.entrySet()) {
final String[] hierarchyNodeTypes = StringUtils.split(nodeTypeAndPathRestriction.getKey(), "/");
boolean match = true;
Resource walkingResource = resource;
for (int i = (hierarchyNodeTypes.length - 1); i >= 0; i--) {
if (walkingResource == null) {
match = false;
break;
} else {
final Node node = walkingResource.adaptTo(Node.class);
if (node == null || !node.isNodeType(hierarchyNodeTypes[i])) {
match = false;
break;
}
walkingResource = walkingResource.getParent();
}
}
if (match) {
Pattern pathRestriction = nodeTypeAndPathRestriction.getValue();
if (pathRestriction != null && !pathRestriction.matcher(resource.getPath()).matches()) {
log.debug("Path restriction '{}' prevents the resource at '{}' from getting its replication status updated!", pathRestriction, resource.getPath());
return false;
}
return true;
}
}
return false;
} | /bundle/src/main/java/com/adobe/acs/commons/replication/status/impl/JcrPackageReplicationStatusEventHandler.java |
robustness-copilot_data_513 | /**
* Creates the path where all iteration-related data should be stored.
*/
public final void createIterationDirectory(final int iteration){
File dir = new File(getIterationPath(iteration));
if (!dir.mkdir()) {
if (this.overwriteFiles == OverwriteFileSetting.overwriteExistingFiles && dir.exists()) {
log.info("Iteration directory " + getIterationPath(iteration) + " exists already.");
} else {
log.warn("Could not create iteration directory " + getIterationPath(iteration) + ".");
}
}
} | /matsim/src/main/java/org/matsim/core/controler/OutputDirectoryHierarchy.java |
robustness-copilot_data_514 | /**
* Format local date time from timestamp by system time zone.
*
* @param timestamp the timestamp
* @return the local date time
*/
public static LocalDateTime formatLocalDateTimeFromTimestampBySystemTimezone(final Long timestamp){
return LocalDateTime.ofEpochSecond(timestamp / 1000, 0, OffsetDateTime.now().getOffset());
} | /shenyu-common/src/main/java/org/apache/shenyu/common/utils/DateUtils.java |
robustness-copilot_data_515 | /**
* Similar to {@link #_readMapAndClose} but specialized for <code>JsonNode</code>
* reading.
*
* @since 2.9
*/
protected JsonNode _readTreeAndClose(JsonParser p0) throws IOException{
try (JsonParser p = p0) {
final JavaType valueType = constructType(JsonNode.class);
DeserializationConfig cfg = getDeserializationConfig();
cfg.initialize(p);
JsonToken t = p.currentToken();
if (t == null) {
t = p.nextToken();
if (t == null) {
return cfg.getNodeFactory().missingNode();
}
}
final JsonNode resultNode;
final DefaultDeserializationContext ctxt = createDeserializationContext(p, cfg);
if (t == JsonToken.VALUE_NULL) {
resultNode = cfg.getNodeFactory().nullNode();
} else {
resultNode = (JsonNode) ctxt.readRootValue(p, valueType, _findRootDeserializer(ctxt, valueType), null);
}
if (cfg.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
_verifyNoTrailingTokens(p, ctxt, valueType);
}
return resultNode;
}
} | /src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java |
robustness-copilot_data_516 | /**
* Formats message based on string loaded from the resource bundle backing this logger.
* @param msgId Message id
* @param params Parameters to message formatting
* @return Formatted message
*/
public String formatMessage(String msgId, Object... params){
if (params == null || params.length == 0) {
return getResourceBundle().getString(msgId);
}
String msg = getResourceBundle().getString(msgId);
MessageFormat formatter = new MessageFormat(msg);
return formatter.format(params);
} | /operator/src/main/java/oracle/kubernetes/operator/logging/LoggingFacade.java |
robustness-copilot_data_517 | /**
* Since pending and undefined steps were added later
* there is need to fill missing data for those statuses.
*/
private void fillMissingSteps(){
passedFeatures = fillMissingArray(passedFeatures);
passedScenarios = fillMissingArray(passedScenarios);
passedSteps = fillMissingArray(passedSteps);
skippedSteps = fillMissingArray(skippedSteps);
pendingSteps = fillMissingArray(pendingSteps);
undefinedSteps = fillMissingArray(undefinedSteps);
} | /src/main/java/net/masterthought/cucumber/Trends.java |
robustness-copilot_data_518 | /**
* Put in order the elements of the molecular formula.
*
* @param formula The IMolecularFormula to put in order
* @return IMolecularFormula object
*/
private IMolecularFormula putInOrder(IMolecularFormula formula){
IMolecularFormula new_formula = formula.getBuilder().newInstance(IMolecularFormula.class);
for (int i = 0; i < orderElements.length; i++) {
IElement element = builder.newInstance(IElement.class, orderElements[i]);
if (MolecularFormulaManipulator.containsElement(formula, element)) {
Iterator<IIsotope> isotopes = MolecularFormulaManipulator.getIsotopes(formula, element).iterator();
while (isotopes.hasNext()) {
IIsotope isotope = isotopes.next();
new_formula.addIsotope(isotope, formula.getIsotopeCount(isotope));
}
}
}
return new_formula;
} | /legacy/src/main/java/org/openscience/cdk/formula/MassToFormulaTool.java |
robustness-copilot_data_519 | /**
* Create a big multicolumn selection for all join columns in the given table. Joins two tables.
*
* @param table the table that used to generate Selection.
* @param ri row number of row in table.
* @param indexes a reverse index for every join column in the table.
* @param selectionSize max size in table .
* @param joinColumnIndexes the column index of join key in tables
* @return selection created
*/
private Selection createMultiColSelection(Table table, int ri, List<Index> indexes, int selectionSize, List<Integer> joinColumnIndexes){
Selection multiColSelection = Selection.withRange(0, selectionSize);
int i = 0;
for (Integer joinColumnIndex : joinColumnIndexes) {
Column<?> col = table.column(joinColumnIndex);
Selection oneColSelection = selectionForColumn(col, ri, indexes.get(i));
multiColSelection = multiColSelection.and(oneColSelection);
i++;
}
return multiColSelection;
} | /core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java |
robustness-copilot_data_520 | /**
* Fluent copy method that creates a new instance that is a copy
* of this instance except for one additional property that is
* passed as the argument.
* Note that method does not modify this instance but constructs
* and returns a new one.
*/
public BeanPropertyMap withProperty(SettableBeanProperty newProp){
String key = getPropertyName(newProp);
for (int i = 1, end = _hashArea.length; i < end; i += 2) {
SettableBeanProperty prop = (SettableBeanProperty) _hashArea[i];
if ((prop != null) && prop.getName().equals(key)) {
return new BeanPropertyMap(this, newProp, i, _findFromOrdered(prop));
}
}
final int slot = _hashCode(key);
return new BeanPropertyMap(this, newProp, key, slot);
} | /src/main/java/com/fasterxml/jackson/databind/deser/impl/BeanPropertyMap.java |
robustness-copilot_data_521 | /**
* Puts a big-endian representation of {@code value} into <code>bytes</code> staring from
* <code>offset</code>.
*
* @param bytes
* @param offset
* @param value
* @throws IllegalArgumentException there is no enough room for 8 bytes.
*/
public static void putLong(byte[] bytes, int offset, long value) throws IllegalArgumentException{
if (bytes.length - offset < 8) {
throw new IllegalArgumentException("not enough space to store long");
}
bytes[offset] = (byte) (value >> 56);
bytes[offset + 1] = (byte) (value >> 48);
bytes[offset + 2] = (byte) (value >> 40);
bytes[offset + 3] = (byte) (value >> 32);
bytes[offset + 4] = (byte) (value >> 24);
bytes[offset + 5] = (byte) (value >> 16);
bytes[offset + 6] = (byte) (value >> 8);
bytes[offset + 7] = (byte) value;
} | /modules/common/src/main/java/org/dcache/util/Bytes.java |
robustness-copilot_data_522 | /**
* Determine the next value of the atom at index <i>v</i>. The value is
* calculated by combining the current values of adjacent atoms. When a
* duplicate value is found it can not be directly included and is
* <i>rotated</i> the number of times it has previously been seen.
*
* @param graph adjacency list representation of connected atoms
* @param v the atom to calculate the next value for
* @param current the current values
* @param unique buffer for working out which adjacent values are unique
* @param included buffer for storing the rotated <i>unique</i> value, this
* value is <i>rotated</i> each time the same value is
* found.
* @param suppressed bit set indicates which atoms are 'suppressed'
* @return the next value for <i>v</i>
*/
long next(int[][] graph, int v, long[] current, long[] unique, long[] included, Suppressed suppressed){
if (suppressed.contains(v))
return current[v];
long invariant = distribute(current[v]);
int nUnique = 0;
for (int w : graph[v]) {
if (suppressed.contains(w))
continue;
long adjInv = current[w];
int i = 0;
while (i < nUnique && unique[i] != adjInv) {
++i;
}
included[i] = (i == nUnique) ? unique[nUnique++] = adjInv : rotate(included[i]);
invariant ^= included[i];
}
return invariant;
} | /tool/hash/src/main/java/org/openscience/cdk/hash/SuppressedAtomHashGenerator.java |
robustness-copilot_data_523 | /**
* Sends a {@link SetWindowSlotMessage} to update the contents of an inventory slot.
*
* @param slot the slot ID
* @param item the new contents
*/
public void sendItemChange(int slot, ItemStack item){
if (invMonitor != null) {
session.send(new SetWindowSlotMessage(invMonitor.getId(), slot, item));
}
} | /src/main/java/net/glowstone/entity/GlowPlayer.java |
robustness-copilot_data_524 | /** Returns a new Row object with its position set to the given zero-based row index. */
public Row row(int rowIndex){
Row row = new Row(Table.this);
row.at(rowIndex);
return row;
} | /core/src/main/java/tech/tablesaw/api/Table.java |
robustness-copilot_data_525 | /**
* This has special case logic to handle NOT quoting column names if they are
* of type 'LiquibaseColumn' - columns in the DATABASECHANGELOG or DATABASECHANGELOGLOCK
* tables.
*/
public String escapeObjectName(String objectName, Class<? extends DatabaseObject> objectType){
if ((quotingStrategy == ObjectQuotingStrategy.LEGACY) && hasMixedCase(objectName)) {
return "\"" + objectName + "\"";
} else if (objectType != null && LiquibaseColumn.class.isAssignableFrom(objectType)) {
return (objectName != null && !objectName.isEmpty()) ? objectName.trim() : objectName;
}
return super.escapeObjectName(objectName, objectType);
} | /liquibase-core/src/main/java/liquibase/database/core/PostgresDatabase.java |
robustness-copilot_data_526 | /**
* Building an <code>ArrayList</code> of <code>DigicoreCluster</code>s. The DJ-Clustering
* procedure of Zhou <i>et al</i> (2004) is followed. If there are no points to cluster, a
* warning message is logged, and the procedure bypassed.
*/
public void clusterInput(double radius, int minimumPoints){
if (this.inputPoints.size() == 0) {
log.warn("DJCluster.clusterInput() called, but no points to cluster.");
} else {
if (!silent) {
log.info("Clustering input points. This may take a while.");
}
int clusterIndex = 0;
int pointMultiplier = 1;
int uPointCounter = 0;
int cPointCounter = 0;
/*
* Determine the extent of the QuadTree.
*/
double xMin = Double.POSITIVE_INFINITY;
double yMin = Double.POSITIVE_INFINITY;
double xMax = Double.NEGATIVE_INFINITY;
double yMax = Double.NEGATIVE_INFINITY;
for (Node node : this.inputPoints) {
Coord c = node.getCoord();
/* TODO Remove if no NullPointerExceptions are thrown. */
if (c == null) {
log.warn("Coord is null. Number of points in list: " + inputPoints.size());
} else {
xMin = Math.min(xMin, c.getX());
yMin = Math.min(yMin, c.getY());
xMax = Math.max(xMax, c.getX());
yMax = Math.max(yMax, c.getY());
}
}
/*
* Build a new QuadTree, and place each point in the QuadTree as a ClusterActivity.
* The geographic coordinates of each point is used as the keys in the QuadTree.
* Initially all ClusterPoints will have a NULL reference to its DigicoreCluster. An
* ArrayList of Points is also kept as iterator for unclustered points.
*/
if (!silent) {
log.info("Place points in QuadTree.");
}
quadTree = new QuadTree<ClusterActivity>(xMin - 1, yMin - 1, xMax + 1, yMax + 1);
List<ClusterActivity> listOfPoints = new ArrayList<ClusterActivity>();
for (int i = 0; i < this.inputPoints.size(); i++) {
double x = inputPoints.get(i).getCoord().getX();
double y = inputPoints.get(i).getCoord().getY();
ClusterActivity cp = new ClusterActivity(Id.create(i, Coord.class), inputPoints.get(i), null);
quadTree.put(x, y, cp);
listOfPoints.add(cp);
}
if (!silent) {
log.info("Done placing activities.");
}
int pointCounter = 0;
while (pointCounter < listOfPoints.size()) {
// Get next point.
ClusterActivity p = listOfPoints.get(pointCounter);
if (p.getCluster() == null) {
// Compute the density-based neighbourhood, N(p), of the point p
Collection<ClusterActivity> neighbourhood = quadTree.getDisk(p.getCoord().getX(), p.getCoord().getY(), radius);
List<ClusterActivity> uN = new ArrayList<ClusterActivity>(neighbourhood.size());
List<ClusterActivity> cN = new ArrayList<ClusterActivity>(neighbourhood.size());
for (ClusterActivity cp : neighbourhood) {
if (cp.getCluster() == null) {
uN.add(cp);
} else {
cN.add(cp);
}
}
if (neighbourhood.size() < minimumPoints) {
/* Point is considered to be noise.
* FIXME Not quite true... it may be incorporated into
* another cluster later! (JWJ - Mar '14)
*/
lostPoints.put(p.getId(), p);
uPointCounter++;
} else if (cN.size() > 0) {
/*
* Merge all the clusters. Use the DigicoreCluster with the smallest clusterId
* value as the remaining DigicoreCluster.
*/
List<Cluster> localClusters = new ArrayList<Cluster>();
Cluster smallestCluster = cN.get(0).getCluster();
for (int i = 1; i < cN.size(); i++) {
if (Integer.parseInt(cN.get(i).getCluster().getId().toString()) < Integer.parseInt(smallestCluster.getId().toString())) {
smallestCluster = cN.get(i).getCluster();
}
if (!localClusters.contains(cN.get(i).getCluster())) {
localClusters.add(cN.get(i).getCluster());
}
}
for (Cluster DigicoreCluster : localClusters) {
if (!DigicoreCluster.equals(smallestCluster)) {
List<ClusterActivity> thisClusterList = DigicoreCluster.getPoints();
for (int j = 0; j < thisClusterList.size(); j++) {
// Change the DigicoreCluster reference of the ClusterActivity.
thisClusterList.get(j).setCluster(smallestCluster);
// Add the ClusterActivity to the new DigicoreCluster.
smallestCluster.getPoints().add(thisClusterList.get(j));
// Remove the ClusterActivity from old DigicoreCluster.
/*
* 20091009 - I've commented this out... this seems
* both dangerous and unnecessary.
*/
// DigicoreCluster.getPoints().remove(thisClusterList.get(j));
}
}
}
// Add unclustered points in the neighborhood.
for (ClusterActivity cp : uN) {
smallestCluster.getPoints().add(cp);
cp.setCluster(smallestCluster);
cPointCounter++;
if (lostPoints.containsKey(cp.getId())) {
lostPoints.remove(cp.getId());
uPointCounter--;
}
}
} else {
// Create new DigicoreCluster and add all the points.
Cluster newCluster = new Cluster(Id.create(clusterIndex, Cluster.class));
clusterIndex++;
for (ClusterActivity cp : uN) {
cp.setCluster(newCluster);
newCluster.getPoints().add(cp);
cPointCounter++;
if (lostPoints.containsKey(cp.getId())) {
lostPoints.remove(cp.getId());
uPointCounter--;
}
}
}
}
pointCounter++;
// Report progress
if (!silent) {
if (pointCounter == pointMultiplier) {
log.info(" Points clustered: " + pointCounter);
pointMultiplier = (int) Math.max(pointCounter, pointMultiplier) * 2;
}
}
}
if (!silent) {
log.info(" Points clustered: " + pointCounter + " (Done)");
int sum = cPointCounter + uPointCounter;
log.info("Sum should add up: " + cPointCounter + " (clustered) + " + uPointCounter + " (unclustered) = " + sum);
/* Code added for Joubert & Meintjes paper (2014). */
log.info("Unclustered points: ");
for (ClusterActivity ca : lostPoints.values()) {
log.info(String.format(" %.6f,%.6f", ca.getCoord().getX(), ca.getCoord().getY()));
}
log.info("New way of unclustered points:");
log.info(" Number: " + lostPoints.size());
}
/*
* Build the DigicoreCluster list. Once built, I rename the clusterId field so as to
* start at '0', and increment accordingly. This allows me to directly use
* the clusterId field as 'row' and 'column' reference in the 2D matrices
* when determining adjacency in Social Network Analysis.
*/
if (!silent) {
log.info("Building the DigicoreCluster list (2 steps)");
}
Map<Cluster, List<ClusterActivity>> clusterMap = new HashMap<Cluster, List<ClusterActivity>>();
if (!silent) {
log.info("Step 1 of 2:");
log.info("Number of ClusterPoints to process: " + listOfPoints.size());
}
int cpCounter = 0;
int cpMultiplier = 1;
for (ClusterActivity ca : listOfPoints) {
Cluster theCluster = ca.getCluster();
if (theCluster != null) {
// Removed 7/12/2011 (JWJ): Seems unnecessary computation.
// theCluster.setCenterOfGravity();
if (!clusterMap.containsKey(theCluster)) {
List<ClusterActivity> newList = new ArrayList<ClusterActivity>();
clusterMap.put(theCluster, newList);
}
clusterMap.get(theCluster).add(ca);
}
if (!silent) {
if (++cpCounter == cpMultiplier) {
log.info(" ClusterPoints processed: " + cpCounter + " (" + String.format("%3.2f", ((double) cpCounter / (double) listOfPoints.size()) * 100) + "%)");
cpMultiplier *= 2;
}
}
}
if (!silent) {
log.info(" ClusterPoints processed: " + cpCounter + " (Done)");
}
if (!silent) {
log.info("Step 2 of 2:");
log.info("Number of clusters to process: " + clusterMap.keySet().size());
}
int clusterCounter = 0;
int clusterMultiplier = 1;
int clusterNumber = 0;
for (Map.Entry<Cluster, List<ClusterActivity>> e : clusterMap.entrySet()) {
Cluster digicoreCluster = e.getKey();
List<ClusterActivity> listOfClusterPoints = e.getValue();
if (listOfClusterPoints.size() >= minimumPoints) {
digicoreCluster.setClusterId(Id.create(clusterNumber++, Cluster.class));
clusterNumber++;
digicoreCluster.setCenterOfGravity();
clusterList.add(digicoreCluster);
} else if (!silent) {
log.warn(" ... why do we HAVE a cluster with too few points?...");
}
if (!silent) {
if (++clusterCounter == clusterMultiplier) {
log.info(" Clusters processed: " + clusterCounter + " (" + String.format("%3.2f", ((double) clusterCounter / (double) clusterMap.keySet().size()) * 100) + "%)");
clusterMultiplier *= 2;
}
}
}
if (!silent) {
log.info(" Clusters processed: " + clusterCounter + " (Done)");
log.info("DigicoreCluster list built.");
}
}
// lost list must be made up of clusters without Id.
} | /matsim/src/main/java/org/matsim/core/network/algorithms/intersectionSimplifier/DensityCluster.java |
robustness-copilot_data_527 | /**
* Update a StateTransition object so a new StateComponent will be added to dCache's state. The
* changes are recorded in StateTransition so they can be applied later.
*
* @param ourPath the StatePath to this StateComposite.
* @param newComponentPath the StatePath to this StateComponent, relative to this
* StateComposition
* @param newComponent the StateComponent to add.
* @param transition the StateTransition in which we will record these changes
*/
public void buildTransition(StatePath ourPath, StatePath newComponentPath, StateComponent newComponent, StateTransition transition) throws MetricStatePathException{
String childName = newComponentPath.getFirstElement();
StateChangeSet changeSet = transition.getOrCreateChangeSet(ourPath);
if (this.isMortal() && newComponent.isMortal()) {
Date newComponentExpiryDate = newComponent.getExpiryDate();
changeSet.recordNewWhenIShouldExpireDate(newComponentExpiryDate);
}
if (newComponent.isImmortal()) {
changeSet.recordChildIsImmortal();
}
changeSet.ensureChildNotRemoved(childName);
if (newComponentPath.isSimplePath()) {
if (_children.containsKey(childName)) {
changeSet.recordUpdatedChild(childName, newComponent);
} else {
changeSet.recordNewChild(childName, newComponent);
}
if (newComponent instanceof StateComposite) {
StateComposite newComposite = (StateComposite) newComponent;
newComposite._metadataRef = getChildMetadata(childName);
}
return;
}
StateComponent child = _children.get(childName);
if (child == null) {
child = changeSet.getNewChildValue(childName);
if (child == null) {
child = new StateComposite(getChildMetadata(childName), DEFAULT_LIFETIME);
changeSet.recordNewChild(childName, child);
}
}
changeSet.recordChildItr(childName);
child.buildTransition(buildChildPath(ourPath, childName), newComponentPath.childPath(), newComponent, transition);
} | /modules/dcache-info/src/main/java/org/dcache/services/info/base/StateComposite.java |
robustness-copilot_data_528 | /**
* Calculate the mass total given the elements and their respective occurrences.
*
* @param elemToCond_new The IIsotope to calculate
* @param value_In Array matrix with occurrences
* @return The sum total
*/
private double calculateMassT(List<IIsotope> isoToCond_new, int[] value_In){
double result = 0;
for (int i = 0; i < isoToCond_new.size(); i++) {
if (value_In[i] != 0) {
result += isoToCond_new.get(i).getExactMass() * value_In[i];
}
}
return result;
} | /legacy/src/main/java/org/openscience/cdk/formula/MassToFormulaTool.java |
robustness-copilot_data_529 | /**
* Add the class designated by the fully qualified class name provided to the set of
* resolved classes if and only if it is approved by the Test supplied.
*
* @param test the test used to determine if the class matches
* @param fqn the fully qualified name of a class
*/
protected void addIfMatching(Test test, String fqn){
try {
String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
ClassLoader loader = getClassLoader();
if (log.isDebugEnabled()) {
log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
}
Class<?> type = loader.loadClass(externalName);
if (test.matches(type)) {
matches.add((Class<T>) type);
}
} catch (Throwable t) {
log.warn("Could not examine class '" + fqn + "'" + " due to a " + t.getClass().getName() + " with message: " + t.getMessage());
}
} | /src/main/java/org/apache/ibatis/io/ResolverUtil.java |
robustness-copilot_data_530 | /**
* Clones this <code>IChemObject</code>. It clones the identifier, flags,
* properties and pointer vectors. The ChemObjectListeners are not cloned, and
* neither is the content of the pointer vectors.
*
*@return The cloned object
*/
public Object clone() throws CloneNotSupportedException{
ChemObject clone = (ChemObject) super.clone();
clone.flags = getFlagValue().shortValue();
if (properties != null)
clone.properties = new HashMap<Object, Object>(getProperties());
clone.chemObjectListeners = null;
return clone;
} | /base/data/src/main/java/org/openscience/cdk/ChemObject.java |
robustness-copilot_data_531 | /**
* Applies the given function to a byte subtag if it is present, converting it to boolean and
* negating it first.
*
* @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 readBooleanNegated(@NonNls String key, Consumer<? super Boolean> consumer){
return readTag(key, ByteTag.class, byteVal -> consumer.accept(byteVal == 0));
} | /src/main/java/net/glowstone/util/nbt/CompoundTag.java |
robustness-copilot_data_532 | /**
* Copy buffer to response for read count smaller then buffer size.
* @param buffer The buffer array
* @param response The response array
* @param num Number of bytes in response array from previous read
* @param read Number of bytes read in the buffer
* @return New count of bytes in the response array
* @checkstyle ParameterNumberCheck (3 lines)
*/
private int copyPartial(final byte[] buffer, final byte[] response, final int num, final int read){
final int result;
if (num > 0) {
System.arraycopy(response, read, response, 0, this.count - read);
System.arraycopy(buffer, 0, response, this.count - read, read);
result = this.count;
} else {
System.arraycopy(buffer, 0, response, 0, read);
result = read;
}
return result;
} | /src/main/java/org/cactoos/io/TailOf.java |
robustness-copilot_data_533 | /**
* Obtains caller details, class name and method, to be provided to the actual Logger. This code
* is adapted from ODLLogRecord, which should yield consistency in reporting using PlatformLogger
* versus a raw (ODL) Logger. JDK Logger does something similar but utilizes native methods
* directly.
*/
CallerDetails inferCaller(){
CallerDetails details = new CallerDetails();
Throwable t = new Throwable();
StackTraceElement[] stack = t.getStackTrace();
int i = 0;
while (i < stack.length) {
StackTraceElement frame = stack[i];
String cname = frame.getClassName();
if (!cname.equals(CLASS)) {
details.clazz = cname;
details.method = frame.getMethodName();
break;
}
i++;
}
return details;
} | /operator/src/main/java/oracle/kubernetes/operator/logging/LoggingFacade.java |
robustness-copilot_data_534 | /**
* Return the best wrapped version of the provided session.
*
* @param session the session to wrap
* @return a wrapped session
*/
public static Session useBestWrapper(final Session session){
if (session instanceof JackrabbitWrapper || session instanceof JcrWrapper) {
return session;
} else if (session instanceof JackrabbitSession) {
return new JackrabbitWrapper((JackrabbitSession) session);
} else if (session != null) {
return new JcrWrapper(session);
}
return null;
} | /bundle/src/main/java/com/adobe/acs/commons/wrap/impl/SessionLogoutGuardFactory.java |
robustness-copilot_data_535 | /**
* Extracts the number of data layers and data blocks from the layer around the bull's eye.
*
* @param bullsEyeCorners the array of bull's eye corners
* @throws NotFoundException in case of too many errors or invalid parameters
*/
private void extractParameters(ResultPoint[] bullsEyeCorners) throws NotFoundException{
if (!isValid(bullsEyeCorners[0]) || !isValid(bullsEyeCorners[1]) || !isValid(bullsEyeCorners[2]) || !isValid(bullsEyeCorners[3])) {
throw NotFoundException.getNotFoundInstance();
}
int length = 2 * nbCenterLayers;
int[] sides = { sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length), sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length), sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length), sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length) };
shift = getRotation(sides, length);
long parameterData = 0;
for (int i = 0; i < 4; i++) {
int side = sides[(shift + i) % 4];
if (compact) {
parameterData <<= 7;
parameterData += (side >> 1) & 0x7F;
} else {
parameterData <<= 10;
parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
}
}
int correctedData = getCorrectedParameterData(parameterData, compact);
if (compact) {
nbLayers = (correctedData >> 6) + 1;
nbDataBlocks = (correctedData & 0x3F) + 1;
} else {
nbLayers = (correctedData >> 11) + 1;
nbDataBlocks = (correctedData & 0x7FF) + 1;
}
} | /core/src/main/java/com/google/zxing/aztec/detector/Detector.java |
robustness-copilot_data_536 | /**
* JSON Schema defines oneOf as a validation property which can be applied to any schema.
* <p>
* OpenAPI Specification is a variant of JSON Schema for which oneOf is defined as:
* "Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema."
* <p>
* Where the only examples of oneOf in OpenAPI Specification are used to define either/or type structures rather than validations.
* Because of this ambiguity in the spec about what is non-standard about oneOf support, we'll warn as a recommendation that
* properties on the schema defining oneOf relationships may not be intentional in the OpenAPI Specification.
*
* @param schemaWrapper An input schema, regardless of the type of schema
* @return {@link ValidationRule.Pass} if the check succeeds, otherwise {@link ValidationRule.Fail}
*/
private static ValidationRule.Result checkOneOfWithProperties(SchemaWrapper schemaWrapper){
Schema schema = schemaWrapper.getSchema();
ValidationRule.Result result = ValidationRule.Pass.empty();
if (schema instanceof ComposedSchema) {
final ComposedSchema composed = (ComposedSchema) schema;
// check for loosely defined oneOf extension requirements.
// This is a recommendation because the 3.0.x spec is not clear enough on usage of oneOf.
// see https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.section.9.2.1.3 and the OAS section on 'Composition and Inheritance'.
if (composed.getOneOf() != null && composed.getOneOf().size() > 0) {
if (composed.getProperties() != null && composed.getProperties().size() >= 1 && composed.getProperties().get("discriminator") == null) {
// not necessarily "invalid" here, but we trigger the recommendation which requires the method to return false.
result = ValidationRule.Fail.empty();
}
}
}
return result;
} | /modules/openapi-generator/src/main/java/org/openapitools/codegen/validations/oas/OpenApiSchemaValidations.java |
robustness-copilot_data_537 | /**
* Find out if the Database object is already stored in the repository. It uses the fully qualified name to retrieve the entity
*
* @param userId the name of the calling user
* @param qualifiedName the qualifiedName name of the database to be searched
*
* @return optional with entity details if found, empty optional if not found
*
* @throws InvalidParameterException the bean properties are invalid
* @throws UserNotAuthorizedException user not authorized to issue this request
* @throws PropertyServerException problem accessing the property server
*/
private Optional<EntityDetail> findDatabaseEntity(String userId, String qualifiedName) throws InvalidParameterException, PropertyServerException, UserNotAuthorizedException{
return dataEngineCommonHandler.findEntity(userId, qualifiedName, DATABASE_TYPE_NAME);
} | /open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEngineRelationalDataHandler.java |
robustness-copilot_data_538 | /**
* Create unit vectors from one atom to all other provided atoms.
*
* @param fromAtom reference atom (will become 0,0)
* @param toAtoms list of to atoms
* @return unit vectors
*/
static List<Vector2d> newUnitVectors(final IAtom fromAtom, final List<IAtom> toAtoms){
final List<Vector2d> unitVectors = new ArrayList<Vector2d>(toAtoms.size());
for (final IAtom toAtom : toAtoms) {
unitVectors.add(newUnitVector(fromAtom.getPoint2d(), toAtom.getPoint2d()));
}
return unitVectors;
} | /display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/VecmathUtil.java |
robustness-copilot_data_539 | /**
* Closing leads to flushing the buffered output stream or writer to the underlying/wrapped response but only in case {@link #flushBufferOnClose} is set to {@code true}.
* Also this will automatically commit the response in case {@link #flushBuffer} has been called previously!
*
* @throws IOException */
void close() throws IOException{
if (flushBufferOnClose) {
if (ResponseWriteMethod.OUTPUTSTREAM.equals(this.writeMethod) && outputStream != null && getBufferedBytes().length > 0) {
wrappedResponse.getOutputStream().write(getBufferedBytes());
} else if (ResponseWriteMethod.WRITER.equals(this.writeMethod) && writer != null && getBufferedString().length() > 0) {
wrappedResponse.getWriter().write(getBufferedString());
}
}
if (flushWrappedBuffer) {
wrappedResponse.flushBuffer();
}
} | /bundle/src/main/java/com/adobe/acs/commons/util/BufferedServletOutput.java |
robustness-copilot_data_540 | /**
* Determines whether this entity can eat an item while healthy, and if so, applies the effects
* of eating it.
*
* @param player the player feeding the entity, for statistical purposes
* @param type an item that may be food
* @return true if the item should be consumed; false otherwise
*/
protected boolean tryFeed(Material type, GlowPlayer player){
if (!getBreedingFoods().contains(type)) {
return false;
}
if (canBreed() && getInLove() <= 0) {
// TODO get the correct duration
setInLove(1000);
player.incrementStatistic(Statistic.ANIMALS_BRED);
return true;
}
int growth = computeGrowthAmount(type);
if (growth > 0) {
grow(growth);
return true;
}
return false;
} | /src/main/java/net/glowstone/entity/GlowAnimal.java |
robustness-copilot_data_541 | /**
* Adds a single network change event and applies it to the corresponding
* links.
*
* @param event
* a network change event.
*/
public void addNetworkChangeEvent(final NetworkChangeEvent event){
this.networkChangeEvents.add(event);
for (Link link : event.getLinks()) {
if (link instanceof TimeVariantLinkImpl) {
((TimeVariantLinkImpl) link).applyEvent(event);
} else {
throw new IllegalArgumentException("Link " + link.getId().toString() + " is not timeVariant. " + "Did you make the network factory time variant? The easiest way to achieve this is " + "either in the config file, or syntax of the type\n" + "config.network().setTimeVariantNetwork(true);\n" + "Scenario scenario = ScenarioUtils.load/createScenario(config);\n" + "Note that the scenario needs to be created _after_ the config option is set, otherwise" + "the factory will already be there.");
}
}
} | /matsim/src/main/java/org/matsim/core/network/NetworkImpl.java |
robustness-copilot_data_542 | /**
* Maps given WeekDay to representation hold by this instance.
*
* @param targetWeekDayDefinition - referred weekDay
* @param dayOfWeek - day of week to be mapped.
* Value corresponds to this instance mapping.
* @return - int result
*/
public int mapTo(final int dayOfWeek, final WeekDay targetWeekDayDefinition){
if (firstDayZero && targetWeekDayDefinition.isFirstDayZero()) {
return bothSameStartOfRange(0, 6, this, targetWeekDayDefinition).apply(dayOfWeek);
}
if (!firstDayZero && !targetWeekDayDefinition.isFirstDayZero()) {
return bothSameStartOfRange(1, 7, this, targetWeekDayDefinition).apply(dayOfWeek);
}
// start range is different for each case. We need to normalize ranges
if (targetWeekDayDefinition.isFirstDayZero()) {
// my range is 1-7. I normalize ranges, get the "zero" mapping and turn result into original scale
return mapTo(dayOfWeek, new WeekDay(targetWeekDayDefinition.getMondayDoWValue() + 1, false)) - 1;
} else {
// my range is 0-6. I normalize ranges, get the "one" mapping and turn result into original scale
return mapTo(dayOfWeek, new WeekDay(targetWeekDayDefinition.getMondayDoWValue() - 1, true)) + 1;
}
} | /src/main/java/com/cronutils/mapper/WeekDay.java |
robustness-copilot_data_543 | /**
* Create an encoder for axial 2D stereochemistry for the given start and
* end atoms.
*
* @param container the molecule
* @param start start of the cumulated system
* @param startBonds bonds connected to the start
* @param end end of the cumulated system
* @param endBonds bonds connected to the end
* @return an encoder
*/
private static StereoEncoder axial2DEncoder(IAtomContainer container, IAtom start, List<IBond> startBonds, IAtom end, List<IBond> endBonds){
Point2d[] ps = new Point2d[4];
int[] es = new int[4];
PermutationParity perm = new CombinedPermutationParity(fill2DCoordinates(container, start, startBonds, ps, es, 0), fill2DCoordinates(container, end, endBonds, ps, es, 2));
GeometricParity geom = new Tetrahedral2DParity(ps, es);
int u = container.indexOf(start);
int v = container.indexOf(end);
return new GeometryEncoder(new int[] { u, v }, perm, geom);
} | /tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java |
robustness-copilot_data_544 | /**
* Returns Patterns for the provided billing formats, as a Multimap mapping the Pattern to the
* attributes contained in the pattern.
*/
private static ImmutableSetMultimap<Pattern, String> toPatterns(Map<String, String> formats){
ImmutableSetMultimap.Builder<Pattern, String> builder = ImmutableSetMultimap.builder();
for (Map.Entry<String, String> format : formats.entrySet()) {
builder.putAll(toPattern(format.getKey(), format.getValue()), toAttributes(format.getValue()));
}
return builder.build();
} | /modules/dcache/src/main/java/org/dcache/services/billing/text/BillingParserBuilder.java |
robustness-copilot_data_545 | /**
* Removed empty fields, sets field value display order.
*
* @param dsv the dataset version show fields we want to tidy up.
*/
protected void tidyUpFields(DatasetVersion dsv){
Iterator<DatasetField> dsfIt = dsv.getDatasetFields().iterator();
while (dsfIt.hasNext()) {
if (dsfIt.next().removeBlankDatasetFieldValues()) {
dsfIt.remove();
}
}
Iterator<DatasetField> dsfItSort = dsv.getDatasetFields().iterator();
while (dsfItSort.hasNext()) {
dsfItSort.next().setValueDisplayOrder();
}
Iterator<DatasetField> dsfItTrim = dsv.getDatasetFields().iterator();
while (dsfItTrim.hasNext()) {
dsfItTrim.next().trimTrailingSpaces();
}
} | /src/main/java/edu/harvard/iq/dataverse/engine/command/impl/AbstractDatasetCommand.java |
robustness-copilot_data_546 | /**
* Save the headers into a headers node under the cache entry node.
* @throws RepositoryException
*/
private void populateHeaders() throws RepositoryException{
final Node headers = getOrCreateByPath(entryNode, JCRHttpCacheStoreConstants.PATH_HEADERS, OAK_UNSTRUCTURED, OAK_UNSTRUCTURED);
for (Iterator<Map.Entry<String, List<String>>> entryIterator = cacheContent.getHeaders().entrySet().iterator(); entryIterator.hasNext(); ) {
Map.Entry<String, List<String>> entry = entryIterator.next();
final String key = entry.getKey();
final List<String> values = entry.getValue();
headers.setProperty(key, values.toArray(new String[values.size()]));
}
} | /bundle/src/main/java/com/adobe/acs/commons/httpcache/store/jcr/impl/writer/EntryNodeWriter.java |
robustness-copilot_data_547 | /**
* The method calculates the number of rotatable bonds of an atom container.
* If the boolean parameter is set to true, terminal bonds are included.
*
*@param ac AtomContainer
*@return number of rotatable bonds
*/
public DescriptorValue calculate(IAtomContainer ac){
ac = clone(ac);
int rotatableBondsCount = 0;
int degree0;
int degree1;
IRingSet ringSet;
try {
ringSet = new SpanningTree(ac).getBasicRings();
} catch (NoSuchAtomException e) {
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new IntegerResult((int) Double.NaN), getDescriptorNames(), e);
}
for (IBond bond : ac.bonds()) {
if (ringSet.getRings(bond).getAtomContainerCount() > 0) {
bond.setFlag(CDKConstants.ISINRING, true);
}
}
for (IBond bond : ac.bonds()) {
IAtom atom0 = bond.getBegin();
IAtom atom1 = bond.getEnd();
if (atom0.getAtomicNumber() == IElement.H || atom1.getAtomicNumber() == IElement.H)
continue;
if (bond.getOrder() == Order.SINGLE) {
if ((BondManipulator.isLowerOrder(ac.getMaximumBondOrder(atom0), IBond.Order.TRIPLE)) && (BondManipulator.isLowerOrder(ac.getMaximumBondOrder(atom1), IBond.Order.TRIPLE))) {
if (!bond.getFlag(CDKConstants.ISINRING)) {
if (excludeAmides && (isAmide(atom0, atom1, ac) || isAmide(atom1, atom0, ac))) {
continue;
}
degree0 = ac.getConnectedBondsCount(atom0) - getConnectedHCount(ac, atom0);
degree1 = ac.getConnectedBondsCount(atom1) - getConnectedHCount(ac, atom1);
if ((degree0 == 1) || (degree1 == 1)) {
if (includeTerminals) {
rotatableBondsCount += 1;
}
} else {
rotatableBondsCount += 1;
}
}
}
}
}
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new IntegerResult(rotatableBondsCount), getDescriptorNames());
} | /descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/RotatableBondsCountDescriptor.java |
robustness-copilot_data_548 | /**
* Converts the given config value into the appropriate bundle. If the given value is blank or
* null, the default value is returned. If the given value does not match any preprogrammmed
* bundles case insensitively, then null is returned.
*
* @param configValue The value from the config file.
*/
public static CompatibilityBundle fromConfig(String configValue){
if (configValue == null || CharMatcher.whitespace().matchesAllOf(configValue)) {
return CompatibilityBundle.CRAFTBUKKIT;
}
try {
return valueOf(configValue.toUpperCase());
} catch (IllegalArgumentException e) {
return null;
}
} | /src/main/java/net/glowstone/util/CompatibilityBundle.java |
robustness-copilot_data_549 | /**
* Method assigns 3D coordinates to the heavy atoms in an aliphatic chain.
*
* @param molecule the reference molecule for the chain
* @param chain the atoms to be assigned, must be connected
* @throws CDKException the 'chain' was not a chain
*/
public void placeAliphaticHeavyChain(IAtomContainer molecule, IAtomContainer chain) throws CDKException{
int[] first = new int[2];
int counter = 1;
int nextAtomNr = 0;
String id1 = "";
String id2 = "";
String id3 = "";
first = findHeavyAtomsInChain(molecule, chain);
distances = new double[first[1]];
firstAtoms = new int[first[1]];
angles = new double[first[1]];
secondAtoms = new int[first[1]];
dihedrals = new double[first[1]];
thirdAtoms = new int[first[1]];
firstAtoms[0] = first[0];
molecule.getAtom(firstAtoms[0]).setFlag(CDKConstants.VISITED, true);
int hybridisation = 0;
for (int i = 0; i < chain.getAtomCount(); i++) {
if (isHeavyAtom(chain.getAtom(i))) {
if (!chain.getAtom(i).getFlag(CDKConstants.VISITED)) {
nextAtomNr = molecule.indexOf(chain.getAtom(i));
id2 = molecule.getAtom(firstAtoms[counter - 1]).getAtomTypeName();
id1 = molecule.getAtom(nextAtomNr).getAtomTypeName();
if (molecule.getBond(molecule.getAtom(firstAtoms[counter - 1]), molecule.getAtom(nextAtomNr)) == null)
throw new CDKException("atoms do not form a chain, please use ModelBuilder3D");
distances[counter] = getBondLengthValue(id1, id2);
firstAtoms[counter] = nextAtomNr;
secondAtoms[counter] = firstAtoms[counter - 1];
if (counter > 1) {
id3 = molecule.getAtom(firstAtoms[counter - 2]).getAtomTypeName();
hybridisation = getHybridisationState(molecule.getAtom(firstAtoms[counter - 1]));
angles[counter] = getAngleValue(id1, id2, id3);
if (angles[counter] == -1) {
if (hybridisation == 3) {
angles[counter] = DEFAULT_SP3_ANGLE;
} else if (hybridisation == 2) {
angles[counter] = DEFAULT_SP2_ANGLE;
} else if (hybridisation == 1) {
angles[counter] = DEFAULT_SP_ANGLE;
}
}
thirdAtoms[counter] = firstAtoms[counter - 2];
} else {
angles[counter] = -1;
thirdAtoms[counter] = -1;
}
if (counter > 2) {
try {
if (getDoubleBondConfiguration2D(molecule.getBond(molecule.getAtom(firstAtoms[counter - 1]), molecule.getAtom(firstAtoms[counter - 2])), (molecule.getAtom(firstAtoms[counter])).getPoint2d(), (molecule.getAtom(firstAtoms[counter - 1])).getPoint2d(), (molecule.getAtom(firstAtoms[counter - 2])).getPoint2d(), (molecule.getAtom(firstAtoms[counter - 3])).getPoint2d()) == 5) {
dihedrals[counter] = DIHEDRAL_BRANCHED_CHAIN;
} else {
dihedrals[counter] = DIHEDRAL_EXTENDED_CHAIN;
}
} catch (CDKException ex1) {
dihedrals[counter] = DIHEDRAL_EXTENDED_CHAIN;
}
} else {
dihedrals[counter] = -1;
}
counter++;
}
}
}
} | /tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java |
robustness-copilot_data_550 | /**
* Calculates Tanimoto distance for two count fingerprints using method 1.
*
* The feature/count type fingerprints may be of different length.
* Uses Tanimoto method from {@cdk.cite Steffen09}.
*
* @param fp1 count fingerprint 1
* @param fp2 count fingerprint 2
* @return a Tanimoto distance
*/
public static double method1(ICountFingerprint fp1, ICountFingerprint fp2){
long xy = 0, x = 0, y = 0;
for (int i = 0; i < fp1.numOfPopulatedbins(); i++) {
int hash = fp1.getHash(i);
for (int j = 0; j < fp2.numOfPopulatedbins(); j++) {
if (hash == fp2.getHash(j)) {
xy += fp1.getCount(i) * fp2.getCount(j);
}
}
x += fp1.getCount(i) * fp1.getCount(i);
}
for (int j = 0; j < fp2.numOfPopulatedbins(); j++) {
y += fp2.getCount(j) * fp2.getCount(j);
}
return ((double) xy / (x + y - xy));
} | /descriptor/fingerprint/src/main/java/org/openscience/cdk/similarity/Tanimoto.java |
robustness-copilot_data_551 | /**
* Judge whether job's sharding items are all started.
*
* @return job's sharding items are all started or not
*/
public boolean isAllStarted(){
return jobNodeStorage.isJobNodeExisted(GuaranteeNode.STARTED_ROOT) && configService.load(false).getShardingTotalCount() == jobNodeStorage.getJobNodeChildrenKeys(GuaranteeNode.STARTED_ROOT).size();
} | /elasticjob-lite/elasticjob-lite-core/src/main/java/org/apache/shardingsphere/elasticjob/lite/internal/guarantee/GuaranteeService.java |
robustness-copilot_data_552 | /**
* Generic grow function, expand an array by a varried amount to have
* enough (required) space.
*
* @param array the array to expand
* @param required the minimum required space
* @param <T> array type
* @return the expanded array
*/
private static T[] grow(T[] array, int required){
int oldCapacity = array.length;
int newCapacity = oldCapacity == 0 ? DEFAULT_CAPACITY : oldCapacity + (oldCapacity >> 1);
if (newCapacity < required)
newCapacity = required;
return Arrays.copyOf(array, newCapacity);
} | /base/data/src/main/java/org/openscience/cdk/AtomContainer.java |
robustness-copilot_data_553 | /**
* Provide a new QualityValue with the same quality but with the value mapped to a different
* type.
*
* @param <U> The new type of the value
* @param conversion the method to convert to the new type
* @return The mapped QualityValue.
*/
public QualityValue<U> mapWith(Function<String, U> conversion){
return new QualityValue(rawValue, conversion.apply(rawValue), quality);
} | /modules/dcache/src/main/java/org/dcache/util/QualityValue.java |
robustness-copilot_data_554 | /**
* Performs a breadthFirstSearch in an AtomContainer starting with a
* particular sphere, which usually consists of one start atom, and searches
* for a pi system.
*
* @param container The AtomContainer to
* be searched
* @param sphere A sphere of atoms to
* start the search with
* @param path An array list which stores the atoms belonging to the pi system
* @throws org.openscience.cdk.exception.CDKException
* Description of the
* Exception
*/
private void breadthFirstSearch(IAtomContainer container, List<IAtom> sphere, List<IAtom> path) throws CDKException{
IAtom nextAtom;
List<IAtom> newSphere = new ArrayList<IAtom>();
for (IAtom atom : sphere) {
List bonds = container.getConnectedBondsList(atom);
for (Object bond : bonds) {
nextAtom = ((IBond) bond).getOther(atom);
if ((container.getMaximumBondOrder(nextAtom) != IBond.Order.SINGLE || Math.abs(nextAtom.getFormalCharge()) >= 1 || nextAtom.getFlag(CDKConstants.ISAROMATIC) || nextAtom.getAtomicNumber() == IElement.N || nextAtom.getAtomicNumber() == IElement.O) & !nextAtom.getFlag(CDKConstants.VISITED)) {
path.add(nextAtom);
nextAtom.setFlag(CDKConstants.VISITED, true);
if (container.getConnectedBondsCount(nextAtom) > 1) {
newSphere.add(nextAtom);
}
} else {
nextAtom.setFlag(CDKConstants.VISITED, true);
}
}
}
if (newSphere.size() > 0) {
breadthFirstSearch(container, newSphere, path);
}
} | /descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/LargestPiSystemDescriptor.java |
robustness-copilot_data_555 | /**
* Receive a 'picture' message to the socket (or actor).
*
*
* @param picture The picture is a string that defines the type of each frame.
* This makes it easy to recv a complex multiframe message in
* one call. The picture can contain any of these characters,
* each corresponding to zero or one elements in the result:
*
* <table>
* <caption> </caption>
* <tr><td>i = int (stores signed integer)</td></tr>
* <tr><td>1 = int (stores 8-bit unsigned integer)</td></tr>
* <tr><td>2 = int (stores 16-bit unsigned integer)</td></tr>
* <tr><td>4 = long (stores 32-bit unsigned integer)</td></tr>
* <tr><td>8 = long (stores 64-bit unsigned integer)</td></tr>
* <tr><td>s = String</td></tr>
* <tr><td>b = byte[]</td></tr>
* <tr><td>f = ZFrame (creates zframe)</td></tr>
* <tr><td>m = ZMsg (creates a zmsg with the remaing frames)</td></tr>
* <tr><td>z = null, asserts empty frame (0 arguments)</td></tr>
* </table>
*
* Also see {@link #sendPicture(Socket, String, Object...)} how to send a
* multiframe picture.
*
* @return the picture elements as object array
*/
public Object[] recvPicture(Socket socket, String picture){
if (!FORMAT.matcher(picture).matches()) {
throw new ZMQException(picture + " is not in expected format " + FORMAT.pattern(), ZError.EPROTO);
}
Object[] elements = new Object[picture.length()];
for (int index = 0; index < picture.length(); index++) {
char pattern = picture.charAt(index);
switch(pattern) {
case 'i':
{
elements[index] = Integer.valueOf(socket.recvStr());
break;
}
case '1':
{
elements[index] = (0xff) & Integer.valueOf(socket.recvStr());
break;
}
case '2':
{
elements[index] = (0xffff) & Integer.valueOf(socket.recvStr());
break;
}
case '4':
{
elements[index] = (0xffffffff) & Integer.valueOf(socket.recvStr());
break;
}
case '8':
{
elements[index] = Long.valueOf(socket.recvStr());
break;
}
case 's':
{
elements[index] = socket.recvStr();
break;
}
case 'b':
case 'c':
{
elements[index] = socket.recv();
break;
}
case 'f':
{
elements[index] = ZFrame.recvFrame(socket);
break;
}
case 'm':
{
elements[index] = ZMsg.recvMsg(socket);
break;
}
case 'z':
{
ZFrame zeroFrame = ZFrame.recvFrame(socket);
if (zeroFrame == null || zeroFrame.size() > 0) {
throw new ZMQException("zero frame is not empty", ZError.EPROTO);
}
elements[index] = new ZFrame((byte[]) null);
break;
}
default:
assert (false) : "invalid picture element '" + pattern + "'";
}
}
return elements;
} | /src/main/java/org/zeromq/proto/ZPicture.java |
robustness-copilot_data_556 | /**
* Decides wheter to use the round robin algorithm or full enumeration algorithm.
* The round robin implementation here is optimized for chemical elements in organic compounds. It gets slow
* if
* - the mass of the smallest element is very large (i.e. hydrogen is not allowed)
* - the maximal mass to decompose is too large (round robin always decomposes integers. Therefore, the mass have
* to be small enough to be represented as 32 bit integer)
* - the number of elements in the set is extremely small (in this case, however, the problem becomes trivial anyways)
*
* In theory we could handle these problems by optimizing the way DECOMP discretizes the masses. However, it's easier
* to just fall back to the full enumeration method if a problem occurs (especially, because most of the problems
* lead to trivial cases that are fast to compute).
*
* @return true if the problem is ill-posed (i.e. should be calculated by full enumeration method)
*/
private static boolean isIllPosed(double minMass, double maxMass, MolecularFormulaRange mfRange){
// when the number of integers to decompose is incredible large
// we have to adjust the internal settings (e.g. precision!)
// instead we simply fallback to the full enumeration method
if (maxMass - minMass >= 1)
return true;
if (maxMass > 400000)
return true;
// if the number of elements to decompose is very small
// we fall back to the full enumeration methods as the
// minimal decomposable mass of a certain residue class might
// exceed the 32 bit integer space
if (mfRange.getIsotopeCount() <= 2)
return true;
// if the mass of the smallest element in alphabet is large
// it is more efficient to use the full enumeration method
double smallestMass = Double.POSITIVE_INFINITY;
for (IIsotope i : mfRange.isotopes()) {
smallestMass = Math.min(smallestMass, i.getExactMass());
}
return smallestMass > 5;
} | /tool/formula/src/main/java/org/openscience/cdk/formula/MolecularFormulaGenerator.java |
robustness-copilot_data_557 | /**
* Adds a condition to the status, replacing any existing conditions with the same type, and removing other
* conditions according to the domain rules.
*
* @param newCondition the condition to add.
* @return this object.
*/
public DomainStatus addCondition(DomainCondition newCondition){
if (conditions.contains(newCondition)) {
return this;
}
conditions = conditions.stream().filter(c -> preserve(c, newCondition.getType())).collect(Collectors.toList());
conditions.add(newCondition);
reason = newCondition.getStatusReason();
message = newCondition.getStatusMessage();
return this;
} | /operator/src/main/java/oracle/kubernetes/weblogic/domain/model/DomainStatus.java |
robustness-copilot_data_558 | /**
* An easily-readable version of the permutation as a product of cycles.
*
* @return the cycle form of the permutation as a string
*/
public String toCycleString(){
int n = this.values.length;
boolean[] p = new boolean[n];
Arrays.fill(p, true);
StringBuilder sb = new StringBuilder();
int j = 0;
for (int i = 0; i < n; i++) {
if (p[i]) {
sb.append('(');
sb.append(i);
p[i] = false;
j = i;
while (p[values[j]]) {
sb.append(", ");
j = values[j];
sb.append(j);
p[j] = false;
}
sb.append(')');
}
}
return sb.toString();
} | /tool/group/src/main/java/org/openscience/cdk/group/Permutation.java |
robustness-copilot_data_559 | /**
* Applies the command line configuration to a MATSim {@link Config} instance.
* See {@link CommandLine} for more information on the syntax.
*
* @throws ConfigurationException
*/
public void applyConfiguration(Config config) throws ConfigurationException{
List<String> configOptions = options.keySet().stream().filter(o -> o.startsWith(CONFIG_PREFIX + ":")).collect(Collectors.toList());
for (String option : configOptions) {
processConfigOption(config, option, option.substring(CONFIG_PREFIX.length() + 1));
}
} | /matsim/src/main/java/org/matsim/core/config/CommandLine.java |
robustness-copilot_data_560 | /**
* Given a molecule (possibly disconnected) compute the labels which
* would order the atoms by increasing canonical labelling. If the SMILES
* are isomeric (i.e. stereo and isotope specific) the InChI numbers are
* used. These numbers are loaded via reflection and the 'cdk-inchi' module
* should be present on the classpath.
*
* @param molecule the molecule to
* @return the permutation
* @see Canon
*/
private static int[] labels(int flavour, final IAtomContainer molecule) throws CDKException{
long[] labels = SmiFlavor.isSet(flavour, SmiFlavor.Isomeric) ? inchiNumbers(molecule) : Canon.label(molecule, GraphUtil.toAdjList(molecule), createComparator(molecule, flavour));
int[] cpy = new int[labels.length];
for (int i = 0; i < labels.length; i++) cpy[i] = (int) labels[i] - 1;
return cpy;
} | /storage/smiles/src/main/java/org/openscience/cdk/smiles/SmilesGenerator.java |
robustness-copilot_data_561 | /**
* Adds double-bond conformations ({@link DoubleBondStereochemistry}) to the
* atom-container.
*
* @param g Beam graph object (for directional bonds)
* @param ac The atom-container built from the Beam graph
*/
private void addDoubleBondStereochemistry(Graph g, IAtomContainer ac){
for (final Edge e : g.edges()) {
if (e.bond() != Bond.DOUBLE)
continue;
int u = e.either();
int v = e.other(u);
Edge first = null;
Edge second = null;
if ((first = findDirectionalEdge(g, u)) != null) {
if ((second = findDirectionalEdge(g, v)) != null) {
Conformation conformation = first.bond(u) == second.bond(v) ? Conformation.TOGETHER : Conformation.OPPOSITE;
IBond db = ac.getBond(ac.getAtom(u), ac.getAtom(v));
IBond[] ligands = new IBond[] { ac.getBond(ac.getAtom(u), ac.getAtom(first.other(u))), ac.getBond(ac.getAtom(v), ac.getAtom(second.other(v))) };
ac.addStereoElement(new DoubleBondStereochemistry(db, ligands, conformation));
} else if (g.degree(v) == 2) {
List<Edge> edges = new ArrayList<>();
edges.add(e);
Edge f = findCumulatedEdge(g, v, e);
int beg = v;
while (f != null) {
edges.add(f);
v = f.other(v);
f = findCumulatedEdge(g, v, f);
if (beg == v) {
beg = -1;
break;
}
}
if (beg < 0)
continue;
if ((edges.size() & 0x1) == 0)
continue;
second = findDirectionalEdge(g, v);
if (second != null) {
int cfg = first.bond(u) == second.bond(v) ? IStereoElement.TOGETHER : IStereoElement.OPPOSITE;
Edge middleEdge = edges.get(edges.size() / 2);
IBond middleBond = ac.getBond(ac.getAtom(middleEdge.either()), ac.getAtom(middleEdge.other(middleEdge.either())));
IBond[] ligands = new IBond[] { ac.getBond(ac.getAtom(u), ac.getAtom(first.other(u))), ac.getBond(ac.getAtom(v), ac.getAtom(second.other(v))) };
ac.addStereoElement(new ExtendedCisTrans(middleBond, ligands, cfg));
}
}
} else {
Configuration uConf = g.configurationOf(u);
Configuration vConf = g.configurationOf(v);
if (uConf.type() == Configuration.Type.DoubleBond && vConf.type() == Configuration.Type.DoubleBond) {
int[] nbrs = new int[6];
int[] uNbrs = g.neighbors(u);
int[] vNbrs = g.neighbors(v);
if (uNbrs.length < 2 || uNbrs.length > 3)
continue;
if (vNbrs.length < 2 || vNbrs.length > 3)
continue;
int idx = 0;
System.arraycopy(uNbrs, 0, nbrs, idx, uNbrs.length);
idx += uNbrs.length;
if (uNbrs.length == 2)
nbrs[idx++] = u;
System.arraycopy(vNbrs, 0, nbrs, idx, vNbrs.length);
idx += vNbrs.length;
if (vNbrs.length == 2)
nbrs[idx] = v;
Arrays.sort(nbrs, 0, 3);
Arrays.sort(nbrs, 3, 6);
int vPos = Arrays.binarySearch(nbrs, 0, 3, v);
int uPos = Arrays.binarySearch(nbrs, 3, 6, u);
int uhi = 0, ulo = 0;
int vhi = 0, vlo = 0;
uhi = nbrs[(vPos + 1) % 3];
ulo = nbrs[(vPos + 2) % 3];
vhi = nbrs[3 + ((uPos + 1) % 3)];
vlo = nbrs[3 + ((uPos + 2) % 3)];
if (uConf.shorthand() == Configuration.CLOCKWISE) {
int tmp = uhi;
uhi = ulo;
ulo = tmp;
}
if (vConf.shorthand() == Configuration.ANTI_CLOCKWISE) {
int tmp = vhi;
vhi = vlo;
vlo = tmp;
}
DoubleBondStereochemistry.Conformation conf = null;
IBond[] bonds = new IBond[2];
if (uhi != u) {
bonds[0] = ac.getBond(ac.getAtom(u), ac.getAtom(uhi));
if (vhi != v) {
conf = Conformation.TOGETHER;
bonds[1] = ac.getBond(ac.getAtom(v), ac.getAtom(vhi));
} else if (vlo != v) {
conf = Conformation.OPPOSITE;
bonds[1] = ac.getBond(ac.getAtom(v), ac.getAtom(vlo));
}
} else if (ulo != u) {
bonds[0] = ac.getBond(ac.getAtom(u), ac.getAtom(ulo));
if (vhi != v) {
conf = Conformation.OPPOSITE;
bonds[1] = ac.getBond(ac.getAtom(v), ac.getAtom(vhi));
} else if (vlo != v) {
conf = Conformation.TOGETHER;
bonds[1] = ac.getBond(ac.getAtom(v), ac.getAtom(vlo));
}
}
ac.addStereoElement(new DoubleBondStereochemistry(ac.getBond(ac.getAtom(u), ac.getAtom(v)), bonds, conf));
}
}
}
} | /storage/smiles/src/main/java/org/openscience/cdk/smiles/BeamToCDK.java |
robustness-copilot_data_562 | /**
* Pre-visit allows us to prepare the visitor for more optimal output.
* Currently we
* - find the most common stoke/fill/stroke-width values and set these as defaults
*
* @param elements elements to be visited
*/
public void previsit(Collection<? extends IRenderingElement> elements){
Deque<IRenderingElement> queue = new ArrayDeque<>(2 * elements.size());
queue.addAll(elements);
FreqMap<Color> strokeFreq = new FreqMap<>();
FreqMap<Color> fillFreq = new FreqMap<>();
FreqMap<Double> strokeWidthFreq = new FreqMap<>();
while (!queue.isEmpty()) {
IRenderingElement element = queue.poll();
// wrappers first
if (element instanceof Bounds) {
queue.add(((Bounds) element).root());
} else if (element instanceof MarkedElement) {
queue.add(((MarkedElement) element).element());
} else if (element instanceof ElementGroup) {
for (IRenderingElement child : (ElementGroup) element) queue.add(child);
} else if (element instanceof LineElement) {
strokeFreq.add(((LineElement) element).color);
strokeWidthFreq.add(scaled(((LineElement) element).width));
} else if (element instanceof GeneralPath) {
if (((GeneralPath) element).fill)
fillFreq.add(((GeneralPath) element).color);
} else {
// ignored
}
}
if (!defaultsWritten) {
defaultFill = fillFreq.getMostFrequent();
defaultStroke = strokeFreq.getMostFrequent();
Double strokeWidth = strokeWidthFreq.getMostFrequent();
if (strokeWidth != null)
defaultStrokeWidth = toStr(strokeWidth);
}
} | /app/depict/src/main/java/org/openscience/cdk/depict/SvgDrawVisitor.java |
robustness-copilot_data_563 | /**
* Quick check to see whether <i>either</i> the links are shorter than the
* given threshold.
* @param linkA
* @param linkB
* @param thresholdLength
* @return true if <i>either</i> links are shorter than the given threshold,
* false otherwise.
*/
private boolean eitherLinkIsShorterThanThreshold(Link linkA, Link linkB, double thresholdLength){
boolean hasShortLink = false;
if (linkA.getLength() < thresholdLength || linkB.getLength() < thresholdLength) {
hasShortLink = true;
}
return hasShortLink;
} | /matsim/src/main/java/org/matsim/core/network/algorithms/NetworkSimplifier.java |
robustness-copilot_data_564 | /**
* Progress the state-machine - the function return false when a mapping is
* found on the mapping is done.
*
* @return the state is partial
*/
private boolean map(){
if ((n == state.nMax() || m == state.mMax()) && !stack.empty())
state.remove(n = stack.popN(), m = stack.popM());
while ((m = state.nextM(n, m)) < state.mMax()) {
if (state.add(n, m)) {
stack.push(n, m);
n = state.nextN(-1);
m = -1;
return n < state.nMax();
}
}
return state.size() > 0 || m < state.mMax();
} | /base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/StateStream.java |
robustness-copilot_data_565 | /**
* Check if all atoms in the bond list have 3D coordinates. There is some
* redundant checking but the list will typically be short.
*
* @param bonds the bonds to check
* @return whether all atoms have 2D coordinates
*/
private static boolean has3DCoordinates(List<IBond> bonds){
for (IBond bond : bonds) {
if (bond.getBegin().getPoint3d() == null || bond.getEnd().getPoint3d() == null)
return false;
}
return true;
} | /tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricCumulativeDoubleBondFactory.java |
robustness-copilot_data_566 | /**
* Return true iff this restriction has an Authorisation that is subsumed by other.
*/
private boolean hasAuthorisationSubsumedBy(Authorisation other){
EnumSet<Activity> disallowedOtherActivities = EnumSet.complementOf(other.activities);
return authorisations.stream().anyMatch(ap -> disallowedOtherActivities.containsAll(EnumSet.complementOf(ap.activities)) && other.getPath().hasPrefix(ap.getPath()));
} | /modules/common/src/main/java/org/dcache/auth/attributes/MultiTargetedRestriction.java |
robustness-copilot_data_567 | /**
* Extract the information from a line which contains HOSE_ID & energy.
*
* @param str String with the information
* @return List with String = HOSECode and String = energy
*/
private static List<String> extractInfo(String str){
int beg = 0;
int end = 0;
int len = str.length();
List<String> parts = new ArrayList<>();
while (end < len && !Character.isSpaceChar(str.charAt(end))) end++;
parts.add(str.substring(beg, end));
while (end < len && Character.isSpaceChar(str.charAt(end))) end++;
beg = end;
while (end < len && !Character.isSpaceChar(str.charAt(end))) end++;
parts.add(str.substring(beg, end));
return parts;
} | /descriptor/qsaratomic/src/main/java/org/openscience/cdk/qsar/descriptors/atomic/ProtonAffinityHOSEDescriptor.java |
robustness-copilot_data_568 | /**
* Adds the specified class to the list of {@link VFS} implementations. Classes added in this
* manner are tried in the order they are added and before any of the built-in implementations.
*
* @param clazz The {@link VFS} implementation class to add.
*/
public static void addImplClass(Class<? extends VFS> clazz){
if (clazz != null) {
USER_IMPLEMENTATIONS.add(clazz);
}
} | /src/main/java/org/apache/ibatis/io/VFS.java |
robustness-copilot_data_569 | /**
* Finds the AtomType matching the Atom's element symbol, formal charge and
* hybridization state.
*
* @param atomContainer AtomContainer
* @param atom the target atom
* @exception CDKException Exception thrown if something goes wrong
* @return the matching AtomType
*/
public List<IAtomType> possibleAtomTypes(IAtomContainer atomContainer, IAtom atom) throws CDKException{
if (factory == null) {
try {
factory = AtomTypeFactory.getInstance("org/openscience/cdk/config/data/structgen_atomtypes.xml", atom.getBuilder());
} catch (Exception ex1) {
logger.error(ex1.getMessage());
logger.debug(ex1);
throw new CDKException("Could not instantiate the AtomType list!", ex1);
}
}
double bondOrderSum = atomContainer.getBondOrderSum(atom);
IBond.Order maxBondOrder = atomContainer.getMaximumBondOrder(atom);
int charge = atom.getFormalCharge();
int hcount = atom.getImplicitHydrogenCount();
List<IAtomType> matchingTypes = new ArrayList<IAtomType>();
IAtomType[] types = factory.getAtomTypes(atom.getSymbol());
for (IAtomType type : types) {
logger.debug(" ... matching atom ", atom, " vs ", type);
if (bondOrderSum - charge + hcount <= type.getBondOrderSum() && !BondManipulator.isHigherOrder(maxBondOrder, type.getMaxBondOrder())) {
matchingTypes.add(type);
}
}
logger.debug(" No Match");
return matchingTypes;
} | /tool/structgen/src/main/java/org/openscience/cdk/atomtype/StructGenAtomTypeGuesser.java |
robustness-copilot_data_570 | /**
* Main method to be called to resolve overlap situations.
*
* @param ac The atomcontainer in which the atom or bond overlap exists
* @param sssr A ring set for this atom container if one exists, otherwhise null
*/
public double resolveOverlap(IAtomContainer ac, IRingSet sssr){
Vector overlappingAtoms = new Vector();
Vector overlappingBonds = new Vector();
logger.debug("Start of resolveOverlap");
double overlapScore = getOverlapScore(ac, overlappingAtoms, overlappingBonds);
if (overlapScore > 0) {
overlapScore = displace(ac, overlappingAtoms, overlappingBonds);
}
logger.debug("overlapScore = " + overlapScore);
logger.debug("End of resolveOverlap");
return overlapScore;
} | /tool/sdg/src/main/java/org/openscience/cdk/layout/OverlapResolver.java |
robustness-copilot_data_571 | /**
* Normalize the intensity (relative abundance) of all isotopes in relation
* of the most abundant isotope.
*
* @param isopattern The IsotopePattern object
* @param minIntensity The minimum abundance
* @return The IsotopePattern cleaned
*/
private IsotopePattern cleanAbundance(IsotopePattern isopattern, double minIntensity){
double intensity, biggestIntensity = 0.0f;
for (IsotopeContainer sc : isopattern.getIsotopes()) {
intensity = sc.getIntensity();
if (intensity > biggestIntensity)
biggestIntensity = intensity;
}
for (IsotopeContainer sc : isopattern.getIsotopes()) {
intensity = sc.getIntensity();
intensity /= biggestIntensity;
if (intensity < 0)
intensity = 0;
sc.setIntensity(intensity);
}
IsotopePattern sortedIsoPattern = new IsotopePattern();
sortedIsoPattern.setMonoIsotope(new IsotopeContainer(isopattern.getIsotopes().get(0)));
for (int i = 1; i < isopattern.getNumberOfIsotopes(); i++) {
if (isopattern.getIsotopes().get(i).getIntensity() >= (minIntensity)) {
IsotopeContainer container = new IsotopeContainer(isopattern.getIsotopes().get(i));
sortedIsoPattern.addIsotope(container);
}
}
return sortedIsoPattern;
} | /tool/formula/src/main/java/org/openscience/cdk/formula/IsotopePatternGenerator.java |
robustness-copilot_data_572 | /**
* Converts a {@link IAtomContainer} into a {@link Model} representation using the CDK OWL.
*
* @param molecule {@link IAtomContainer} to serialize into a RDF graph.
* @return the RDF graph representing the {@link IAtomContainer}.
*/
public static Model molecule2Model(IAtomContainer molecule){
Model model = createCDKModel();
Resource subject = model.createResource(createIdentifier(model, molecule));
model.add(subject, RDF.type, CDK.MOLECULE);
Map<IAtom, Resource> cdkToRDFAtomMap = new HashMap<IAtom, Resource>();
for (IAtom atom : molecule.atoms()) {
Resource rdfAtom = model.createResource(createIdentifier(model, atom));
cdkToRDFAtomMap.put(atom, rdfAtom);
model.add(subject, CDK.HASATOM, rdfAtom);
if (atom instanceof IPseudoAtom) {
model.add(rdfAtom, RDF.type, CDK.PSEUDOATOM);
serializePseudoAtomFields(model, rdfAtom, (IPseudoAtom) atom);
} else {
model.add(rdfAtom, RDF.type, CDK.ATOM);
serializeAtomFields(model, rdfAtom, atom);
}
}
for (IBond bond : molecule.bonds()) {
Resource rdfBond = model.createResource(createIdentifier(model, bond));
model.add(rdfBond, RDF.type, CDK.BOND);
for (IAtom atom : bond.atoms()) {
model.add(rdfBond, CDK.BINDSATOM, cdkToRDFAtomMap.get(atom));
}
if (bond.getOrder() != null) {
model.add(rdfBond, CDK.HASORDER, order2Resource(bond.getOrder()));
}
model.add(subject, CDK.HASBOND, rdfBond);
serializeElectronContainerFields(model, rdfBond, bond);
}
return model;
} | /storage/iordf/src/main/java/org/openscience/cdk/libio/jena/Convertor.java |
robustness-copilot_data_573 | /**
* Selects a pool from a list using the WASS algorithm.
* <p/>
* Returns null if all pools are full.
*/
public P selectByAvailableSpace(List<P> pools, long filesize, Function<P, PoolCostInfo> getCost){
int length = pools.size();
double[] available = new double[length];
double minLoad = Double.POSITIVE_INFINITY;
for (int i = 0; i < length; i++) {
PoolCostInfo info = getCost.apply(pools.get(i));
double free = getAvailable(info.getSpaceInfo(), filesize);
if (free > 0) {
available[i] = free;
minLoad = Math.min(minLoad, getLoad(info));
}
}
if (minLoad == Double.POSITIVE_INFINITY) {
return null;
}
double sum = 0.0;
for (int i = 0; i < length; i++) {
PoolCostInfo info = getCost.apply(pools.get(i));
double normalizedLoad = getLoad(info) - minLoad;
double weightedAvailable = getWeightedAvailable(info, available[i], normalizedLoad);
sum += weightedAvailable;
available[i] = sum;
}
double threshold = random() * sum;
for (int i = 0; i < length; i++) {
if (threshold < available[i]) {
return pools.get(i);
}
}
if (sum == Double.POSITIVE_INFINITY) {
throw new IllegalStateException("WASS overflow: Configured space cost factor (" + spaceCostFactor + ") is too large.");
}
throw new RuntimeException("Unreachable statement.");
} | /modules/dcache/src/main/java/org/dcache/poolmanager/WeightedAvailableSpaceSelection.java |
robustness-copilot_data_574 | /**
* Returns the time in millisecond until the next timer.
* @return the time in millisecond until the next timer.
*/
public long timeout(){
final long now = now();
for (Entry<Timer, Long> entry : entries()) {
final Timer timer = entry.getKey();
final Long expiration = entry.getValue();
if (timer.alive) {
if (expiration - now > 0) {
return expiration - now;
} else {
return 0;
}
}
timers.remove(expiration, timer);
}
return -1;
} | /src/main/java/zmq/util/Timers.java |
robustness-copilot_data_575 | /**
* Check whether another path points to the same location.
*
* @param otherPath: the other path to compare
* @return: whether the other path point to the same location.
*/
public boolean equals(Object otherObject){
if (!(otherObject instanceof StatePath)) {
return false;
}
if (otherObject == this) {
return true;
}
StatePath otherPath = (StatePath) otherObject;
if (otherPath._elements.size() != _elements.size()) {
return false;
}
for (int i = 0; i < _elements.size(); i++) {
if (otherPath._elements.get(i) != _elements.get(i)) {
return false;
}
}
return true;
} | /modules/dcache-info/src/main/java/org/dcache/services/info/base/StatePath.java |
robustness-copilot_data_576 | /**
* Build edges of the RGraphs
* This method create the edge of the CDKRGraph and
* calculates the incompatibility and neighbourhood
* relationships between CDKRGraph nodes.
*
* @param graph the rGraph
* @param ac1 first molecule. Must not be an IQueryAtomContainer.
* @param ac2 second molecule. May be an IQueryAtomContainer.
* @throws org.openscience.cdk.exception.CDKException if it takes too long to get the overlaps
*/
private static void arcConstructor(CDKRGraph graph, IAtomContainer ac1, IAtomContainer ac2) throws CDKException{
for (int i = 0; i < graph.getGraph().size(); i++) {
CDKRNode rNodeX = graph.getGraph().get(i);
rNodeX.getForbidden().set(i);
}
IBond bondA1;
IBond bondA2;
IBond bondB1;
IBond bondB2;
graph.setFirstGraphSize(ac1.getBondCount());
graph.setSecondGraphSize(ac2.getBondCount());
for (int i = 0; i < graph.getGraph().size(); i++) {
CDKRNode rNodeX = graph.getGraph().get(i);
for (int j = i + 1; j < graph.getGraph().size(); j++) {
CDKRNode rNodeY = graph.getGraph().get(j);
bondA1 = ac1.getBond(graph.getGraph().get(i).getRMap().getId1());
bondA2 = ac2.getBond(graph.getGraph().get(i).getRMap().getId2());
bondB1 = ac1.getBond(graph.getGraph().get(j).getRMap().getId1());
bondB2 = ac2.getBond(graph.getGraph().get(j).getRMap().getId2());
if (bondA2 instanceof IQueryBond) {
if (bondA1.equals(bondB1) || bondA2.equals(bondB2) || !queryAdjacencyAndOrder(bondA1, bondB1, bondA2, bondB2)) {
rNodeX.getForbidden().set(j);
rNodeY.getForbidden().set(i);
} else if (hasCommonAtom(bondA1, bondB1)) {
rNodeX.getExtension().set(j);
rNodeY.getExtension().set(i);
}
} else {
if (bondA1.equals(bondB1) || bondA2.equals(bondB2) || (!getCommonSymbol(bondA1, bondB1).equals(getCommonSymbol(bondA2, bondB2)))) {
rNodeX.getForbidden().set(j);
rNodeY.getForbidden().set(i);
} else if (hasCommonAtom(bondA1, bondB1)) {
rNodeX.getExtension().set(j);
rNodeY.getExtension().set(i);
}
}
}
}
} | /legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java |
robustness-copilot_data_577 | /**
* Parse and verify the state returned from the provider.
*
* As it contains the providers implementation "id" field when send by us,
* we can return the corresponding provider object.
*
* This function is not side effect free: it will (if present) set {@link #redirectPage}
* to the value received from the state.
*
* @param state The state string, created in {@link #createState(AbstractOAuth2AuthenticationProvider, Optional)}, send and returned by provider
* @return A corresponding provider object when state verification succeeded.
*/
Optional<AbstractOAuth2AuthenticationProvider> parseStateFromRequest(@NotNull String state){
if (state == null || state.trim().equals("")) {
logger.log(Level.INFO, "No state present in request");
return Optional.empty();
}
String[] topFields = state.split("~", 2);
if (topFields.length != 2) {
logger.log(Level.INFO, "Wrong number of fields in state string", state);
return Optional.empty();
}
AbstractOAuth2AuthenticationProvider idp = authenticationSvc.getOAuth2Provider(topFields[0]);
if (idp == null) {
logger.log(Level.INFO, "Can''t find IDP ''{0}''", topFields[0]);
return Optional.empty();
}
String raw = StringUtil.decrypt(topFields[1], idp.clientSecret);
String[] stateFields = raw.split("~", -1);
if (idp.getId().equals(stateFields[0])) {
long timeOrigin = Long.parseLong(stateFields[1]);
long timeDifference = this.clock.millis() - timeOrigin;
if (timeDifference > 0 && timeDifference < STATE_TIMEOUT) {
if (stateFields.length > 3) {
this.redirectPage = Optional.ofNullable(stateFields[3]);
}
return Optional.of(idp);
} else {
logger.info("State timeout");
return Optional.empty();
}
} else {
logger.log(Level.INFO, "Invalid id field: ''{0}''", stateFields[0]);
return Optional.empty();
}
} | /src/main/java/edu/harvard/iq/dataverse/authorization/providers/oauth2/OAuth2LoginBackingBean.java |
robustness-copilot_data_578 | /**
* Calculate the configuration of the double bond as a parity.
*
* @return opposite (+1), together (-1)
*/
public int parity(){
// create three vectors, v->u, v->w and u->x
double[] vu = toVector(v, u);
double[] vw = toVector(v, w);
double[] ux = toVector(u, x);
// normal vector (to compare against), the normal vector (n) looks like:
// x n w
// \ |/
// u = v
double[] normal = crossProduct(vu, crossProduct(vu, vw));
// compare the dot products of v->w and u->x, if the signs are the same
// they are both pointing the same direction. if a value is close to 0
// then it is at pi/2 radians (i.e. unspecified) however 3D coordinates
// are generally discrete and do not normally represent on unspecified
// stereo configurations so we don't check this
int parity = (int) Math.signum(dot(normal, vw)) * (int) Math.signum(dot(normal, ux));
// invert sign, this then matches with Sp2 double bond parity
return parity * -1;
} | /tool/hash/src/main/java/org/openscience/cdk/hash/stereo/DoubleBond3DParity.java |
robustness-copilot_data_579 | /**
* Parse a string like "[0,2|1,3]" to form the partition; cells are
* separated by '|' characters and elements within the cell by commas.
*
* @param strForm the partition in string form
* @return the partition corresponding to the string
* @throws IllegalArgumentException thrown if the provided strFrom is
* null or empty
*/
public static Partition fromString(String strForm){
if (strForm == null || strForm.isEmpty())
throw new IllegalArgumentException("null or empty string provided");
Partition p = new Partition();
int index = 0;
if (strForm.charAt(0) == '[') {
index++;
}
int endIndex;
if (strForm.charAt(strForm.length() - 1) == ']') {
endIndex = strForm.length() - 2;
} else {
endIndex = strForm.length() - 1;
}
int currentCell = -1;
int numStart = -1;
while (index <= endIndex) {
char c = strForm.charAt(index);
if (Character.isDigit(c)) {
if (numStart == -1) {
numStart = index;
}
} else if (c == ',') {
int element = Integer.parseInt(strForm.substring(numStart, index));
if (currentCell == -1) {
p.addCell(element);
currentCell = 0;
} else {
p.addToCell(currentCell, element);
}
numStart = -1;
} else if (c == '|') {
int element = Integer.parseInt(strForm.substring(numStart, index));
if (currentCell == -1) {
p.addCell(element);
currentCell = 0;
} else {
p.addToCell(currentCell, element);
}
currentCell++;
p.addCell();
numStart = -1;
}
index++;
}
int lastElement = Integer.parseInt(strForm.substring(numStart, endIndex + 1));
p.addToCell(currentCell, lastElement);
return p;
} | /tool/group/src/main/java/org/openscience/cdk/group/Partition.java |
robustness-copilot_data_580 | /**
* Applies the given function to a list subtag if it is present, converting it to a list of
* values first.
*
* @param <T> the type to convert the list entries to
* @param key the key to look up
* @param type the type that the list entries must be
* @param consumer the function to apply
* @return true if the tag exists and was passed to the consumer; false otherwise
*/
public boolean readList(@NonNls String key, TagType type, Consumer<? super List<T>> consumer){
if (isList(key, type)) {
consumer.accept(getList(key, type));
return true;
}
return false;
} | /src/main/java/net/glowstone/util/nbt/CompoundTag.java |
robustness-copilot_data_581 | /**
* Returns true if and only if the subject has the given user ID.
*/
public static boolean hasUid(Subject subject, long uid){
Set<UidPrincipal> principals = subject.getPrincipals(UidPrincipal.class);
for (UidPrincipal principal : principals) {
if (principal.getUid() == uid) {
return true;
}
}
return false;
} | /modules/common/src/main/java/org/dcache/auth/Subjects.java |
robustness-copilot_data_582 | /**
* access the number of stereo bonds in the provided bond list.
*
* @param bonds input list
* @return number of UP/DOWN bonds in the list, -1 if a query bond was
* found
*/
private static int nStereoBonds(List<IBond> bonds){
int count = 0;
for (IBond bond : bonds) {
IBond.Stereo stereo = bond.getStereo();
switch(stereo) {
case E_OR_Z:
case UP_OR_DOWN:
case UP_OR_DOWN_INVERTED:
return -1;
case UP:
case DOWN:
case UP_INVERTED:
case DOWN_INVERTED:
count++;
break;
}
}
return count;
} | /tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricTetrahedralEncoderFactory.java |
robustness-copilot_data_583 | /**
* Writes the gathered data tab-separated into a text file.
*
* @param filename The name of a file where to write the gathered data.
*/
public void write(final String filename){
try (OutputStream stream = IOUtils.getOutputStream(IOUtils.getFileUrl(filename), false)) {
write(new PrintStream(stream));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} | /matsim/src/main/java/org/matsim/analysis/LegHistogram.java |
robustness-copilot_data_584 | /**
* Checks if the given path looks like a Jcr Package path.
*
* Provides a very fast, String-based, in-memory check to weed out most false positives and avoid
* resolving the path to a Jcr Package and ensure it is valid.
*
* @param path
* @return true if at least one path looks like a Jcr Package path
*/
private boolean containsJcrPackagePath(final String path){
if (StringUtils.startsWith(path, "/etc/packages/") && StringUtils.endsWith(path, ".zip")) {
return true;
}
return false;
} | /bundle/src/main/java/com/adobe/acs/commons/replication/status/impl/JcrPackageReplicationStatusEventHandler.java |
robustness-copilot_data_585 | /**
* Stores an IRingSet corresponding to a AtomContainer using the bond numbers.
*
* @param mol The IAtomContainer for which to store the IRingSet.
* @param ringSet The IRingSet to store
*/
private void storeRingSystem(IAtomContainer mol, IRingSet ringSet){
listOfRings = new ArrayList<Integer[]>();
for (int r = 0; r < ringSet.getAtomContainerCount(); ++r) {
IRing ring = (IRing) ringSet.getAtomContainer(r);
Integer[] bondNumbers = new Integer[ring.getBondCount()];
for (int i = 0; i < ring.getBondCount(); ++i) bondNumbers[i] = mol.indexOf(ring.getBond(i));
listOfRings.add(bondNumbers);
}
} | /legacy/src/main/java/org/openscience/cdk/smiles/DeduceBondSystemTool.java |
robustness-copilot_data_586 | /**
* Writes a single frame in PDB format to the Writer.
*
* @param molecule the Molecule to write
*/
public void writeMolecule(IAtomContainer molecule) throws CDKException{
try {
writeHeader();
int atomNumber = 1;
String hetatmRecordName = (writeAsHET.isSet()) ? "HETATM" : "ATOM ";
String id = molecule.getID();
String residueName = (id == null || id.equals("")) ? "MOL" : id;
String terRecordName = "TER";
// Loop through the atoms and write them out:
StringBuffer buffer = new StringBuffer();
Iterator<IAtom> atoms = molecule.atoms().iterator();
FormatStringBuffer fsb = new FormatStringBuffer("");
String[] connectRecords = null;
if (writeCONECTRecords.isSet()) {
connectRecords = new String[molecule.getAtomCount()];
}
while (atoms.hasNext()) {
buffer.setLength(0);
buffer.append(hetatmRecordName);
fsb.reset(SERIAL_FORMAT).format(atomNumber);
buffer.append(fsb.toString());
buffer.append(' ');
IAtom atom = atoms.next();
String name;
if (useElementSymbolAsAtomName.isSet()) {
name = atom.getSymbol();
} else {
if (atom.getID() == null || atom.getID().equals("")) {
name = atom.getSymbol();
} else {
name = atom.getID();
}
}
fsb.reset(ATOM_NAME_FORMAT).format(name);
buffer.append(fsb.toString());
fsb.reset(RESIDUE_FORMAT).format(residueName);
buffer.append(fsb).append(" 0 ");
Point3d position = atom.getPoint3d();
fsb.reset(POSITION_FORMAT).format(position.x);
buffer.append(fsb.toString());
fsb.reset(POSITION_FORMAT).format(position.y);
buffer.append(fsb.toString());
fsb.reset(POSITION_FORMAT).format(position.z);
buffer.append(fsb.toString());
// occupancy + temperature factor
buffer.append(" 1.00 0.00 ").append(atom.getSymbol());
Integer formalCharge = atom.getFormalCharge();
if (formalCharge == CDKConstants.UNSET) {
buffer.append("+0");
} else {
if (formalCharge < 0) {
buffer.append(formalCharge);
} else {
buffer.append('+').append(formalCharge);
}
}
if (connectRecords != null && writeCONECTRecords.isSet()) {
List<IAtom> neighbours = molecule.getConnectedAtomsList(atom);
if (neighbours.size() != 0) {
StringBuffer connectBuffer = new StringBuffer("CONECT");
connectBuffer.append(String.format("%5d", atomNumber));
for (IAtom neighbour : neighbours) {
int neighbourNumber = molecule.indexOf(neighbour) + 1;
connectBuffer.append(String.format("%5d", neighbourNumber));
}
connectRecords[atomNumber - 1] = connectBuffer.toString();
} else {
connectRecords[atomNumber - 1] = null;
}
}
writer.write(buffer.toString(), 0, buffer.length());
writer.write('\n');
++atomNumber;
}
if (writeTERRecord.isSet()) {
writer.write(terRecordName, 0, terRecordName.length());
writer.write('\n');
}
if (connectRecords != null && writeCONECTRecords.isSet()) {
for (String connectRecord : connectRecords) {
if (connectRecord != null) {
writer.write(connectRecord);
writer.write('\n');
}
}
}
if (writeENDRecord.isSet()) {
writer.write("END ");
writer.write('\n');
}
} catch (IOException exception) {
throw new CDKException("Error while writing file: " + exception.getMessage(), exception);
}
} | /storage/pdb/src/main/java/org/openscience/cdk/io/PDBWriter.java |
robustness-copilot_data_587 | /**
* Adds an {@link CarrierShipment} to the {@link Carrier}.
* @param carrier
* @param carrierShipment
*/
public static void addShipment(Carrier carrier, CarrierShipment carrierShipment){
carrier.getShipments().put(carrierShipment.getId(), carrierShipment);
} | /contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierUtils.java |
robustness-copilot_data_588 | /**
* Calculates the distance of a given point to the border of the
* rectangle. If the point lies within the rectangle, the distance
* is zero.
*
* @param x left-right location
* @param y up-down location
* @return distance to border, 0 if inside rectangle or on border
*/
private double calcDistanceIndicator(final double x, final double y){
double distanceX;
double distanceY;
if (this.minX <= x && x <= this.maxX) {
distanceX = 0;
} else {
distanceX = Math.min(Math.abs(this.minX - x), Math.abs(this.maxX - x));
}
if (this.minY <= y && y <= this.maxY) {
distanceY = 0;
} else {
distanceY = Math.min(Math.abs(this.minY - y), Math.abs(this.maxY - y));
}
return distanceX * distanceX + distanceY * distanceY;
} | /matsim/src/main/java/org/matsim/core/network/LinkQuadTree.java |
robustness-copilot_data_589 | /**
* Loads the persisted version of each process definition and set values on the in-memory
* version to be consistent.
*/
protected void makeProcessDefinitionsConsistentWithPersistedVersions(ParsedDeployment parsedDeployment){
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
ProcessDefinitionEntity persistedProcessDefinition = bpmnDeploymentHelper.getPersistedInstanceOfProcessDefinition(processDefinition);
if (persistedProcessDefinition != null) {
processDefinition.setId(persistedProcessDefinition.getId());
processDefinition.setVersion(persistedProcessDefinition.getVersion());
processDefinition.setAppVersion(persistedProcessDefinition.getAppVersion());
processDefinition.setSuspensionState(persistedProcessDefinition.getSuspensionState());
}
}
} | /activiti-core/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/BpmnDeployer.java |
robustness-copilot_data_590 | /**
* Returns a {@link String} representation for this {@link IDifference}.
*
* @return a {@link String}
*/
public String toString(){
if (differences.size() == 0)
return "";
StringBuffer diffBuffer = new StringBuffer();
diffBuffer.append(this.name).append('{');
Iterator<IDifference> children = getChildren().iterator();
while (children.hasNext()) {
diffBuffer.append(children.next().toString());
if (children.hasNext()) {
diffBuffer.append(", ");
}
}
diffBuffer.append('}');
return diffBuffer.toString();
} | /misc/diff/src/main/java/org/openscience/cdk/tools/diff/tree/Point3dDifference.java |
robustness-copilot_data_591 | /**
* Returns true if the given arg is a valid main command of Liquibase.
*
* @param arg the String to test
* @return true if it is a valid main command, false if not
*/
private static boolean isCommand(String arg){
return COMMANDS.MIGRATE.equals(arg) || COMMANDS.MIGRATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE.equalsIgnoreCase(arg) || COMMANDS.UPDATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_COUNT.equalsIgnoreCase(arg) || COMMANDS.UPDATE_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TO_TAG.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TO_TAG_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_TO_DATE.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_COUNT.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_TO_DATE_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.REGISTER_CHANGELOG.equalsIgnoreCase(arg) || COMMANDS.DEACTIVATE_CHANGELOG.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_FROM_TAG_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TESTING_ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.TAG.equalsIgnoreCase(arg) || COMMANDS.TAG_EXISTS.equalsIgnoreCase(arg) || COMMANDS.LIST_LOCKS.equalsIgnoreCase(arg) || COMMANDS.HISTORY.equalsIgnoreCase(arg) || COMMANDS.DROP_ALL.equalsIgnoreCase(arg) || COMMANDS.RELEASE_LOCKS.equalsIgnoreCase(arg) || COMMANDS.STATUS.equalsIgnoreCase(arg) || COMMANDS.UNEXPECTED_CHANGESETS.equalsIgnoreCase(arg) || COMMANDS.VALIDATE.equalsIgnoreCase(arg) || COMMANDS.HELP.equalsIgnoreCase(arg) || COMMANDS.DIFF.equalsIgnoreCase(arg) || COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(arg) || COMMANDS.GENERATE_CHANGELOG.equalsIgnoreCase(arg) || COMMANDS.SNAPSHOT.equalsIgnoreCase(arg) || COMMANDS.SNAPSHOT_REFERENCE.equalsIgnoreCase(arg) || COMMANDS.SYNC_HUB.equalsIgnoreCase(arg) || COMMANDS.EXECUTE_SQL.equalsIgnoreCase(arg) || COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(arg) || COMMANDS.CLEAR_CHECKSUMS.equalsIgnoreCase(arg) || COMMANDS.DB_DOC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC_TO_TAG.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC_TO_TAG_SQL.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_ONE_CHANGE_SET.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_ONE_CHANGE_SET_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_ONE_UPDATE.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_ONE_UPDATE_SQL.equalsIgnoreCase(arg);
} | /liquibase-core/src/main/java/liquibase/integration/commandline/Main.java |
robustness-copilot_data_592 | /**
* Convert this value to int (if possible).
*
* @return Int value.
*/
int intValue(){
try {
return Integer.parseInt(value());
} catch (NumberFormatException x) {
throw new TypeMismatchException(name(), int.class, x);
}
} | /jooby/src/main/java/io/jooby/Value.java |
robustness-copilot_data_593 | /**
* Parse an string possibly containing CXSMILES into an intermediate state
* ({@link CxSmilesState}) representation.
*
* @param str input character string (SMILES title field)
* @param state output CXSMILES state
* @return position where CXSMILES ends (below 0 means no CXSMILES)
*/
static int processCx(final String str, final CxSmilesState state){
final CharIter iter = new CharIter(str);
if (!iter.nextIf('|'))
return -1;
while (iter.hasNext()) {
switch(iter.next()) {
case '$':
Map<Integer, String> dest;
if (iter.nextIf("_AV:"))
dest = state.atomValues = new TreeMap<>();
else
dest = state.atomLabels = new TreeMap<>();
if (!processAtomLabels(iter, dest))
return -1;
break;
case '(':
if (!processCoords(iter, state))
return -1;
break;
case 'c':
case 't':
if (iter.nextIf(':')) {
if (!skipIntList(iter, COMMA_SEPARATOR))
return -1;
} else if (iter.nextIf("tu:")) {
if (!skipIntList(iter, COMMA_SEPARATOR))
return -1;
}
break;
case '&':
if (!processStereoGrps(state, iter, IStereoElement.GRP_RAC))
return -1;
break;
case 'o':
if (!processStereoGrps(state, iter, IStereoElement.GRP_REL))
return -1;
break;
case 'a':
if (!processStereoGrps(state, iter, IStereoElement.GRP_ABS))
return -1;
break;
case 'r':
if (iter.nextIf(':')) {
state.racemicFrags = new ArrayList<>();
if (!processIntList(iter, ',', state.racemicFrags))
return -1;
} else {
state.racemic = true;
if (!iter.nextIf(',') && iter.curr() != '|')
return -1;
}
break;
case 'l':
if (!iter.nextIf("p:"))
return -1;
if (!skipIntMap(iter))
return -1;
break;
case 'f':
if (!iter.nextIf(':'))
return -1;
if (!processFragmentGrouping(iter, state))
return -1;
break;
case 'S':
if (iter.nextIf("g:")) {
if (!processPolymerSgroups(iter, state))
return -1;
} else if (iter.nextIf("gD:")) {
if (!processDataSgroups(iter, state))
return -1;
if (iter.nextIf(','))
break;
} else if (iter.nextIf("gH:")) {
if (!processSgroupsHierarchy(iter, state))
return -1;
} else {
return -1;
}
break;
case 'm':
if (!iter.nextIf(':'))
return -1;
if (!processPositionalVariation(iter, state))
return -1;
break;
case '^':
if (!processRadicals(iter, state))
return -1;
break;
case 'C':
case 'H':
if (!iter.nextIf(':'))
return -1;
while (iter.hasNext() && isDigit(iter.curr())) {
if (!skipIntList(iter, DOT_SEPARATOR))
return -1;
iter.nextIf(',');
}
break;
case '|':
if (!iter.nextIf(' '))
iter.nextIf('\t');
return iter.pos;
case 'L':
if (iter.nextIf('O')) {
if (!iter.nextIf(':'))
return -1;
if (!processLigandOrdering(iter, state))
return -1;
} else {
return -1;
}
break;
default:
return -1;
}
}
return -1;
} | /storage/smiles/src/main/java/org/openscience/cdk/smiles/CxSmilesParser.java |
robustness-copilot_data_594 | /**
* First creates a grid based on the network bounding box. Then removes all zones that do not intersect the service area.
* Result may contain zones that are barely included in the service area. But as passengers may walk into the service area,
* it seems appropriate that the DrtZonalSystem, which is used for demand estimation, is larger than the service area.
* The {@code cellsize} indirectly determines, how much larger the DrtZonalSystem may get.
*
* @param network
* @param cellsize
* @param serviceAreaGeoms geometries that define the service area
* @return
*/
public static Map<String, PreparedGeometry> createGridFromNetworkWithinServiceArea(Network network, double cellsize, List<PreparedGeometry> serviceAreaGeoms){
Map<String, PreparedGeometry> grid = createGridFromNetwork(network, cellsize);
log.info("total number of created grid zones = " + grid.size());
log.info("searching for grid zones within the drt service area...");
Counter counter = new Counter("dealt with zone ");
Map<String, PreparedGeometry> zonesWithinServiceArea = EntryStream.of(grid).peekKeys(id -> counter.incCounter()).filterValues(cell -> serviceAreaGeoms.stream().anyMatch(serviceArea -> serviceArea.intersects(cell.getGeometry()))).toMap();
log.info("number of remaining grid zones = " + zonesWithinServiceArea.size());
return zonesWithinServiceArea;
} | /contribs/drt/src/main/java/org/matsim/contrib/drt/analysis/zonal/DrtGridUtils.java |
robustness-copilot_data_595 | /**
* Extracts each folder path and builds FileFolders, with the qualified name of the form
* '<externalSourceName>::<path>'. The order is important, meaning the first folder is the one containing the file
* and the last one the root, and used in creating the folder hierarchy structure al the way to the SoftwareServerCapability
*
* @param pathName file path
* @param externalSourceName name of SoftwareServerCapability
* @param methodName method name
*
* @return list of FileFolders
*/
private List<FileFolder> extractFolders(String pathName, String externalSourceName, String methodName) throws InvalidParameterException{
boolean fileSeparatorReversed = false;
if (pathName.contains("\\")) {
pathName = pathName.replace("\\", "/");
fileSeparatorReversed = true;
}
Path path = Paths.get(pathName);
File parentFile = path.toFile().getParentFile();
invalidParameterHandler.validateObject(parentFile, "pathName", methodName);
List<FileFolder> folders = new ArrayList<>();
while (parentFile != null) {
String parentFilePath = fileSeparatorReversed ? parentFile.getPath().replace("/", "\\") : parentFile.getPath();
FileFolder folder = buildFileFolder(parentFilePath, externalSourceName);
folders.add(folder);
parentFile = parentFile.getParentFile();
}
return folders;
} | /open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEngineFolderHierarchyHandler.java |
robustness-copilot_data_596 | /**
* Return the isotope pattern normalized to the highest abundance.
*
* @param isotopeP The IsotopePattern object to normalize
* @return The IsotopePattern normalized
*/
public static IsotopePattern normalize(IsotopePattern isotopeP){
IsotopeContainer isoHighest = null;
double biggestAbundance = 0;
/* Extraction of the isoContainer with the highest abundance */
for (IsotopeContainer isoContainer : isotopeP.getIsotopes()) {
double abundance = isoContainer.getIntensity();
if (biggestAbundance < abundance) {
biggestAbundance = abundance;
isoHighest = isoContainer;
}
}
/* Normalize */
IsotopePattern isoNormalized = new IsotopePattern();
for (IsotopeContainer isoContainer : isotopeP.getIsotopes()) {
double inten = isoContainer.getIntensity() / isoHighest.getIntensity();
IsotopeContainer icClone;
try {
icClone = (IsotopeContainer) isoContainer.clone();
icClone.setIntensity(inten);
if (isoHighest.equals(isoContainer))
isoNormalized.setMonoIsotope(icClone);
else
isoNormalized.addIsotope(icClone);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
isoNormalized.setCharge(isotopeP.getCharge());
return isoNormalized;
} | /tool/formula/src/main/java/org/openscience/cdk/formula/IsotopePatternManipulator.java |
robustness-copilot_data_597 | /**
* Replace the AtomContainer at a specific position (array has to be large enough).
*
* @param position position in array for AtomContainer
* @param container the replacement AtomContainer
*/
public void replaceAtomContainer(int position, IAtomContainer container){
IAtomContainer old = atomContainers[position];
old.removeListener(this);
atomContainers[position] = container;
container.addListener(this);
notifyChanged();
} | /base/data/src/main/java/org/openscience/cdk/AtomContainerSet.java |
robustness-copilot_data_598 | /**
* Returns all the indices a bit set may have. Can be used for
* cheap for-each loops (i.e. no boxing/unboxing).
* @return All the indices a BitSet has [0..63]
*/
public static short[] allIndices(){
short[] retVal = new short[64];
for (short s = 0; s < 64; s++) retVal[s] = s;
return retVal;
} | /src/main/java/edu/harvard/iq/dataverse/util/BitSet.java |
robustness-copilot_data_599 | /**
* Method that can be called to serialize this node and
* all of its descendants using specified JSON generator.
*/
public void serialize(JsonGenerator g, SerializerProvider provider) throws IOException{
@SuppressWarnings("deprecation")
boolean trimEmptyArray = (provider != null) && !provider.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS);
g.writeStartObject(this);
for (Map.Entry<String, JsonNode> en : _children.entrySet()) {
BaseJsonNode value = (BaseJsonNode) en.getValue();
if (trimEmptyArray && value.isArray() && value.isEmpty(provider)) {
continue;
}
g.writeFieldName(en.getKey());
value.serialize(g, provider);
}
g.writeEndObject();
} | /src/main/java/com/fasterxml/jackson/databind/node/ObjectNode.java |
robustness-copilot_data_600 | /**
* Validates input, resulting in a instance of {@link ValidationResult} which provides details on all validations performed (success, error, warning).
*
* @param input The object instance to be validated.
*
* @return A {@link ValidationResult} which details the success, error, and warning validation results.
*/
public ValidationResult validate(TInput input){
ValidationResult result = new ValidationResult();
if (rules != null) {
rules.forEach(it -> {
ValidationRule.Result attempt = it.evaluate(input);
if (attempt.passed()) {
result.addResult(Validated.valid(it));
} else {
result.addResult(Validated.invalid(it, it.getFailureMessage(), attempt.getDetails()));
}
});
}
return result;
} | /modules/openapi-generator-core/src/main/java/org/openapitools/codegen/validation/GenericValidator.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.