id stringlengths 25 27 | content stringlengths 190 15.4k | max_stars_repo_path stringlengths 31 217 |
|---|---|---|
robustness-copilot_data_201 | /**
* Calculate sp3/sp2 hybridization ratio in the supplied {@link IAtomContainer}.
*
* @param container The AtomContainer for which this descriptor is to be calculated.
* @return The ratio of sp3 to sp2 carbons
*/
public DescriptorValue calculate(IAtomContainer container){
try {
IAtomContainer clone = (IAtomContainer) container.clone();
AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(clone);
int nsp2 = 0;
int nsp3 = 0;
for (IAtom atom : clone.atoms()) {
if (atom.getAtomicNumber() != IElement.C)
continue;
if (atom.getHybridization() == Hybridization.SP2)
nsp2++;
else if (atom.getHybridization() == Hybridization.SP3)
nsp3++;
}
double ratio = nsp3 / (double) (nsp2 + nsp3);
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new DoubleResult(ratio), getDescriptorNames());
} catch (CloneNotSupportedException e) {
return getDummyDescriptorValue(e);
} catch (CDKException e) {
return getDummyDescriptorValue(e);
}
} | /descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/HybridizationRatioDescriptor.java |
robustness-copilot_data_202 | /**
* Select the lowest ring number for use in SMARTS.
*
* @return ring number
* @throws IllegalStateException all ring numbers are used
*/
private int chooseRingNumber(){
for (int i = 1; i < rnums.length; i++) {
if (rnums[i] == 0) {
rnums[i] = 1;
return i;
}
}
throw new IllegalStateException("No more ring numbers available!");
} | /tool/smarts/src/main/java/org/openscience/cdk/smarts/SmartsFragmentExtractor.java |
robustness-copilot_data_203 | /**
* Check max time different seconds tolerable between job server and registry center.
*
* @throws JobExecutionEnvironmentException throe JobExecutionEnvironmentException if exceed max time different seconds
*/
public void checkMaxTimeDiffSecondsTolerable() throws JobExecutionEnvironmentException{
int maxTimeDiffSeconds = load(true).getMaxTimeDiffSeconds();
if (0 > maxTimeDiffSeconds) {
return;
}
long timeDiff = Math.abs(timeService.getCurrentMillis() - jobNodeStorage.getRegistryCenterTime());
if (timeDiff > maxTimeDiffSeconds * 1000L) {
throw new JobExecutionEnvironmentException("Time different between job server and register center exceed '%s' seconds, max time different is '%s' seconds.", timeDiff / 1000, maxTimeDiffSeconds);
}
} | /elasticjob-lite/elasticjob-lite-core/src/main/java/org/apache/shardingsphere/elasticjob/lite/internal/config/ConfigurationService.java |
robustness-copilot_data_204 | /**
* Find the 2nd terminus stop (1st terminus is at index 0 per definition).
*
* Returns stop index instead of the stop, in order to cater for stops which are
* served multiple times
*
* @param stops
* @return index of the stop which is half way on the route from start stop over
* all stops back to the start stop
*
* @author gleich
*
*/
public static final int findSecondTerminusStop(ArrayList<TransitStopFacility> stops){
double totalDistance = 0;
Map<Integer, Double> distFromStart2StopIndex = new HashMap<>();
TransitStopFacility previousStop = stops.get(0);
for (int i = 0; i < stops.size(); i++) {
TransitStopFacility currentStop = stops.get(i);
totalDistance = totalDistance + CoordUtils.calcEuclideanDistance(previousStop.getCoord(), currentStop.getCoord());
distFromStart2StopIndex.put(i, totalDistance);
previousStop = currentStop;
}
// add leg from last to first stop
totalDistance = totalDistance + CoordUtils.calcEuclideanDistance(previousStop.getCoord(), stops.get(0).getCoord());
// first terminus is first stop in stops, other terminus is stop half way on the
// circular route beginning at the first stop
for (int i = 1; i < stops.size(); i++) {
if (distFromStart2StopIndex.get(i) >= totalDistance / 2) {
if (Math.abs(totalDistance / 2 - distFromStart2StopIndex.get(i - 1)) > Math.abs(totalDistance / 2 - distFromStart2StopIndex.get(i))) {
// -> if both Math.abs() are equal the previous stop (i-1) is returned
return i;
} else {
return i - 1;
}
}
}
return 0;
} | /contribs/minibus/src/main/java/org/matsim/contrib/minibus/genericUtils/TerminusStopFinder.java |
robustness-copilot_data_205 | /**
* Evaluates the simple chi index for a set of fragments.
*
* @param atomContainer The target <code>AtomContainer</code>
* @param fragLists A list of fragments
* @return The simple chi index
*/
public static double evalSimpleIndex(IAtomContainer atomContainer, List<List<Integer>> fragLists){
double sum = 0;
for (List<Integer> fragList : fragLists) {
double prod = 1.0;
for (Integer atomSerial : fragList) {
IAtom atom = atomContainer.getAtom(atomSerial);
int nconnected = atomContainer.getConnectedBondsCount(atom);
prod = prod * nconnected;
}
if (prod != 0)
sum += 1.0 / Math.sqrt(prod);
}
return sum;
} | /descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/ChiIndexUtils.java |
robustness-copilot_data_206 | /**
* Returns whether the appender is valid is valid for use in a threshold definition.
*/
public synchronized boolean hasAppender(String appender){
return _appenders.contains(appender) || (_parent != null && _parent.hasAppender(appender));
} | /modules/cells/src/main/java/dmg/util/logback/FilterThresholdSet.java |
robustness-copilot_data_207 | /**
* Clones this bond object, including clones of the atoms between which the
* bond is defined.
*
* @return The cloned object
*/
public IBond clone() throws CloneNotSupportedException{
Bond clone = (Bond) super.clone();
if (atoms != null) {
clone.atoms = new IAtom[atoms.length];
for (int f = 0; f < atoms.length; f++) {
if (atoms[f] != null) {
clone.atoms[f] = (IAtom) ((IAtom) atoms[f]).clone();
}
}
}
return clone;
} | /base/data/src/main/java/org/openscience/cdk/Bond.java |
robustness-copilot_data_208 | /**
* Method for registering {@link ValueInstantiator} to use when deserializing
* instances of type <code>beanType</code>.
*<p>
* Instantiator is
* registered when module is registered for <code>ObjectMapper</code>.
*/
public SimpleModule addValueInstantiator(Class<?> beanType, ValueInstantiator inst){
_checkNotNull(beanType, "class to register value instantiator for");
_checkNotNull(inst, "value instantiator");
if (_valueInstantiators == null) {
_valueInstantiators = new SimpleValueInstantiators();
}
_valueInstantiators = _valueInstantiators.addValueInstantiator(beanType, inst);
return this;
} | /src/main/java/com/fasterxml/jackson/databind/module/SimpleModule.java |
robustness-copilot_data_209 | /**
* The method calculates the bond total Partial charge of a given bond
* It is needed to call the addExplicitHydrogensToSatisfyValency method from the class tools.HydrogenAdder.
*
*@param ac AtomContainer
*@return return the sigma electronegativity
*/
public DescriptorValue calculate(IBond bond, IAtomContainer ac){
Double originalCharge1 = bond.getBegin().getCharge();
String originalAtomtypeName1 = bond.getBegin().getAtomTypeName();
Integer originalNeighborCount1 = bond.getBegin().getFormalNeighbourCount();
IAtomType.Hybridization originalHybridization1 = bond.getBegin().getHybridization();
Integer originalValency1 = bond.getBegin().getValency();
Double originalCharge2 = bond.getEnd().getCharge();
String originalAtomtypeName2 = bond.getEnd().getAtomTypeName();
Integer originalNeighborCount2 = bond.getEnd().getFormalNeighbourCount();
IAtomType.Hybridization originalHybridization2 = bond.getEnd().getHybridization();
Integer originalValency2 = bond.getEnd().getValency();
Double originalBondOrderSum1 = bond.getBegin().getBondOrderSum();
Order originalMaxBondOrder1 = bond.getBegin().getMaxBondOrder();
Double originalBondOrderSum2 = bond.getEnd().getBondOrderSum();
Order originalMaxBondOrder2 = bond.getEnd().getMaxBondOrder();
if (!isCachedAtomContainer(ac)) {
try {
AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(ac);
if (lpeChecker) {
LonePairElectronChecker lpcheck = new LonePairElectronChecker();
lpcheck.saturate(ac);
}
} catch (CDKException e) {
return getDummyDescriptorValue(e);
}
if (maxIterations != -1)
peoe.setMaxGasteigerIters(maxIterations);
if (maxIterations != -1)
pepe.setMaxGasteigerIters(maxIterations);
if (maxResonStruc != -1)
pepe.setMaxResoStruc(maxResonStruc);
try {
peoe.assignGasteigerMarsiliSigmaPartialCharges(ac, true);
List<Double> peoeBond = new ArrayList<Double>();
for (Iterator<IBond> it = ac.bonds().iterator(); it.hasNext(); ) {
IBond bondi = it.next();
double result = Math.abs(bondi.getBegin().getCharge() - bondi.getEnd().getCharge());
peoeBond.add(result);
}
for (Iterator<IAtom> it = ac.atoms().iterator(); it.hasNext(); ) it.next().setCharge(0.0);
pepe.assignGasteigerPiPartialCharges(ac, true);
for (int i = 0; i < ac.getBondCount(); i++) {
IBond bondi = ac.getBond(i);
double result = Math.abs(bondi.getBegin().getCharge() - bondi.getEnd().getCharge());
cacheDescriptorValue(bondi, ac, new DoubleResult(peoeBond.get(i) + result));
}
} catch (Exception e) {
return getDummyDescriptorValue(e);
}
}
bond.getBegin().setCharge(originalCharge1);
bond.getBegin().setAtomTypeName(originalAtomtypeName1);
bond.getBegin().setHybridization(originalHybridization1);
bond.getBegin().setValency(originalValency1);
bond.getBegin().setFormalNeighbourCount(originalNeighborCount1);
bond.getEnd().setCharge(originalCharge2);
bond.getEnd().setAtomTypeName(originalAtomtypeName2);
bond.getEnd().setHybridization(originalHybridization2);
bond.getEnd().setValency(originalValency2);
bond.getEnd().setFormalNeighbourCount(originalNeighborCount2);
bond.getBegin().setMaxBondOrder(originalMaxBondOrder1);
bond.getBegin().setBondOrderSum(originalBondOrderSum1);
bond.getEnd().setMaxBondOrder(originalMaxBondOrder2);
bond.getEnd().setBondOrderSum(originalBondOrderSum2);
return getCachedDescriptorValue(bond) != null ? new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), getCachedDescriptorValue(bond), NAMES) : null;
} | /descriptor/qsarbond/src/main/java/org/openscience/cdk/qsar/descriptors/bond/BondPartialTChargeDescriptor.java |
robustness-copilot_data_210 | /**
* Create a new checksum instance for an already computed digest of a particular type.
*
* @param digest the input must have the following format:
* <type>:<hexadecimal digest>
* @throws IllegalArgumentException if argument has wrong form
* @throws NullPointerException if argument is null
*/
public static Checksum parseChecksum(String digest){
requireNonNull(digest, "value may not be null");
int del = digest.indexOf(DELIMITER);
if (del < 1) {
throw new IllegalArgumentException("Not a dCache checksum: " + digest);
}
String type = digest.substring(0, del);
String checksum = digest.substring(del + 1);
return new Checksum(ChecksumType.getChecksumType(type), checksum);
} | /modules/common/src/main/java/org/dcache/util/Checksum.java |
robustness-copilot_data_211 | /**
* Test if the domain is deployed under Istio environment.
*
* @return istioEnabled
*/
boolean isIstioEnabled(){
return Optional.ofNullable(configuration).map(Configuration::getIstio).map(Istio::getEnabled).orElse(false);
} | /operator/src/main/java/oracle/kubernetes/weblogic/domain/model/DomainSpec.java |
robustness-copilot_data_212 | /**
* Returns true if one of the servers in the cluster has the specified name.
*
* @param serverName the name to look for
* @return true or false
*/
public boolean hasNamedServer(String serverName){
return getServerConfigs().stream().anyMatch(c -> serverName.equals(c.getName()));
} | /operator/src/main/java/oracle/kubernetes/operator/wlsconfig/WlsClusterConfig.java |
robustness-copilot_data_213 | /**
* Checks if the agent has a valid transport URI set.
*
* @param agent Agent to check
* @return true if the Agent's transport URI is in the proper form
*/
private boolean isDispatcherTransportURI(final Agent agent){
final String transportURI = agent.getConfiguration().getTransportURI();
return (StringUtils.startsWith(transportURI, HTTP) || StringUtils.startsWith(transportURI, HTTPS));
} | /bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/DispatcherFlushFilter.java |
robustness-copilot_data_214 | /**
* An iterator over {@code FileSegment} for the {@code DocumentCollection} iterable.
* A collection is comprised of one or more file segments.
*/
public final Iterator<FileSegment<T>> iterator(){
List<Path> paths = discover(this.path);
Iterator<Path> pathsIterator = paths.iterator();
return new Iterator<>() {
Path segmentPath;
FileSegment<T> segment;
@Override
public boolean hasNext() {
if (segment != null) {
return true;
}
if (!pathsIterator.hasNext()) {
return false;
} else {
try {
segmentPath = pathsIterator.next();
segment = createFileSegment(segmentPath);
} catch (IOException e) {
return false;
}
}
return true;
}
@Override
public FileSegment<T> next() throws NoSuchElementException {
if (!hasNext()) {
throw new NoSuchElementException("No more file segments to read.");
} else {
FileSegment<T> seg = segment;
segment = null;
return seg;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
} | /src/main/java/io/anserini/collection/DocumentCollection.java |
robustness-copilot_data_215 | /**
* Factory method used to create {@link MappingIterator} instances;
* either default, or custom subtype.
*
* @since 2.5
*/
protected MappingIterator<T> _newIterator(JsonParser p, DeserializationContext ctxt, JsonDeserializer<?> deser, boolean parserManaged){
return new MappingIterator<T>(_valueType, p, ctxt, deser, parserManaged, _valueToUpdate);
} | /src/main/java/com/fasterxml/jackson/databind/ObjectReader.java |
robustness-copilot_data_216 | /**
* Add extended tetrahedral stereo configuration to the Beam GraphBuilder.
*
* @param et stereo element specifying tetrahedral configuration
* @param gb the current graph builder
* @param indices atom indices
*/
private static void addExtendedTetrahedralConfiguration(ExtendedTetrahedral et, GraphBuilder gb, Map<IAtom, Integer> indices){
IAtom[] ligands = et.peripherals();
int u = indices.get(et.focus());
int[] vs = new int[] { indices.get(ligands[0]), indices.get(ligands[1]), indices.get(ligands[2]), indices.get(ligands[3]) };
gb.extendedTetrahedral(u).lookingFrom(vs[0]).neighbors(vs[1], vs[2], vs[3]).winding(et.winding() == CLOCKWISE ? Configuration.CLOCKWISE : Configuration.ANTI_CLOCKWISE).build();
} | /storage/smiles/src/main/java/org/openscience/cdk/smiles/CDKToBeam.java |
robustness-copilot_data_217 | /**
* Expands the given Node in the routing algorithm; may be overridden in
* sub-classes.
*
* @param outNode
* The Node to be expanded.
* @param toNode
* The target Node of the route.
* @param pendingNodes
* The set of pending nodes so far.
*/
protected void relaxNode(final Node outNode, final Node toNode, final RouterPriorityQueue<Node> pendingNodes){
DijkstraNodeData outData = getData(outNode);
double currTime = outData.getTime();
double currCost = outData.getCost();
if (this.pruneDeadEnds) {
PreProcessDijkstra.DeadEndData ddOutData = getPreProcessData(outNode);
for (Link l : outNode.getOutLinks().values()) {
relaxNodeLogic(l, pendingNodes, currTime, currCost, toNode, ddOutData);
}
} else {
for (Link l : outNode.getOutLinks().values()) {
relaxNodeLogic(l, pendingNodes, currTime, currCost, toNode, null);
}
}
} | /matsim/src/main/java/org/matsim/core/router/Dijkstra.java |
robustness-copilot_data_218 | /** Build a reverse index for every join column in the table. */
private List<Index> buildIndexesForJoinColumns(List<Integer> joinColumnIndexes, Table table){
return joinColumnIndexes.stream().map(c -> indexFor(table, c)).collect(Collectors.toList());
} | /core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java |
robustness-copilot_data_219 | /**
* Randomly generates a single, connected, correctly bonded structure from
* a number of fragments. IMPORTANT: The AtomContainers in the set must be
* connected. If an AtomContainer is disconnected, no valid result will
* be formed
* @param atomContainers The fragments to generate for.
* @return The newly formed structure.
* @throws CDKException No valid result could be formed.
*/
public IAtomContainer generate(IAtomContainerSet atomContainers) throws CDKException{
int iteration = 0;
boolean structureFound = false;
do {
iteration++;
boolean bondFormed;
do {
bondFormed = false;
for (IAtomContainer ac : atomContainers.atomContainers()) {
for (IAtom atom : AtomContainerManipulator.getAtomArray(ac)) {
if (!satCheck.isSaturated(atom, ac)) {
IAtom partner = getAnotherUnsaturatedNode(atom, ac, atomContainers);
if (partner != null) {
IAtomContainer toadd = AtomContainerSetManipulator.getRelevantAtomContainer(atomContainers, partner);
double cmax1 = satCheck.getCurrentMaxBondOrder(atom, ac);
double cmax2 = satCheck.getCurrentMaxBondOrder(partner, toadd);
double max = Math.min(cmax1, cmax2);
// (double)Math.round(Math.random() * max)
double order = Math.min(Math.max(1.0, max), 3.0);
logger.debug("cmax1, cmax2, max, order: " + cmax1 + ", " + cmax2 + ", " + max + ", " + order);
if (toadd != ac) {
atomContainers.removeAtomContainer(toadd);
ac.add(toadd);
}
ac.addBond(ac.getBuilder().newInstance(IBond.class, atom, partner, BondManipulator.createBondOrder(order)));
bondFormed = true;
}
}
}
}
} while (bondFormed);
if (atomContainers.getAtomContainerCount() == 1 && satCheck.allSaturated(atomContainers.getAtomContainer(0))) {
structureFound = true;
}
} while (!structureFound && iteration < 5);
if (atomContainers.getAtomContainerCount() == 1 && satCheck.allSaturated(atomContainers.getAtomContainer(0))) {
structureFound = true;
}
if (!structureFound)
throw new CDKException("Could not combine the fragments to combine a valid, satured structure");
return atomContainers.getAtomContainer(0);
} | /tool/structgen/src/main/java/org/openscience/cdk/structgen/stochastic/PartialFilledStructureMerger.java |
robustness-copilot_data_220 | /**
* Gets structure from InChI, and converts InChI library data structure
* into an IAtomContainer.
*
* @throws CDKException
*/
protected void generateAtomContainerFromInchi(IChemObjectBuilder builder) throws CDKException{
InchiInput input = output.getInchiInput();
molecule = builder.newInstance(IAtomContainer.class);
Map<InchiAtom, IAtom> inchiCdkAtomMap = new HashMap<InchiAtom, IAtom>();
List<InchiAtom> atoms = input.getAtoms();
for (int i = 0; i < atoms.size(); i++) {
InchiAtom iAt = atoms.get(i);
IAtom cAt = builder.newInstance(IAtom.class);
inchiCdkAtomMap.put(iAt, cAt);
cAt.setID("a" + i);
cAt.setAtomicNumber(Elements.ofString(iAt.getElName()).number());
cAt.setFormalCharge(iAt.getCharge());
cAt.setImplicitHydrogenCount(iAt.getImplicitHydrogen());
int isotopicMass = iAt.getIsotopicMass();
if (isotopicMass != 0) {
if (isotopicMass > ISOTOPIC_SHIFT_THRESHOLD) {
try {
int massNumber = Isotopes.getInstance().getMajorIsotope(cAt.getAtomicNumber()).getMassNumber();
cAt.setMassNumber(massNumber + (isotopicMass - ISOTOPIC_SHIFT_FLAG));
} catch (IOException e) {
throw new CDKException("Could not load Isotopes data", e);
}
} else {
cAt.setMassNumber(isotopicMass);
}
}
molecule.addAtom(cAt);
cAt = molecule.getAtom(molecule.getAtomCount() - 1);
addHydrogenIsotopes(builder, cAt, 2, iAt.getImplicitDeuterium());
addHydrogenIsotopes(builder, cAt, 3, iAt.getImplicitTritium());
}
List<InchiBond> bonds = input.getBonds();
for (int i = 0; i < bonds.size(); i++) {
InchiBond iBo = bonds.get(i);
IBond cBo = builder.newInstance(IBond.class);
IAtom atO = inchiCdkAtomMap.get(iBo.getStart());
IAtom atT = inchiCdkAtomMap.get(iBo.getEnd());
cBo.setAtoms(new IAtom[] { atO, atT });
InchiBondType type = iBo.getType();
switch(type) {
case SINGLE:
cBo.setOrder(IBond.Order.SINGLE);
break;
case DOUBLE:
cBo.setOrder(IBond.Order.DOUBLE);
break;
case TRIPLE:
cBo.setOrder(IBond.Order.TRIPLE);
break;
case ALTERN:
cBo.setIsInRing(true);
break;
default:
throw new CDKException("Unknown bond type: " + type);
}
InchiBondStereo stereo = iBo.getStereo();
switch(stereo) {
case NONE:
cBo.setStereo(IBond.Stereo.NONE);
break;
case SINGLE_1DOWN:
cBo.setStereo(IBond.Stereo.DOWN);
break;
case SINGLE_1UP:
cBo.setStereo(IBond.Stereo.UP);
break;
case SINGLE_2DOWN:
cBo.setStereo(IBond.Stereo.DOWN_INVERTED);
break;
case SINGLE_2UP:
cBo.setStereo(IBond.Stereo.UP_INVERTED);
break;
case SINGLE_1EITHER:
cBo.setStereo(IBond.Stereo.UP_OR_DOWN);
break;
case SINGLE_2EITHER:
cBo.setStereo(IBond.Stereo.UP_OR_DOWN_INVERTED);
break;
}
molecule.addBond(cBo);
}
List<InchiStereo> stereos = input.getStereos();
for (int i = 0; i < stereos.size(); i++) {
InchiStereo stereo0d = stereos.get(i);
if (stereo0d.getType() == InchiStereoType.Tetrahedral || stereo0d.getType() == InchiStereoType.Allene) {
InchiAtom central = stereo0d.getCentralAtom();
InchiAtom[] neighbours = stereo0d.getAtoms();
IAtom focus = inchiCdkAtomMap.get(central);
IAtom[] neighbors = new IAtom[] { inchiCdkAtomMap.get(neighbours[0]), inchiCdkAtomMap.get(neighbours[1]), inchiCdkAtomMap.get(neighbours[2]), inchiCdkAtomMap.get(neighbours[3]) };
ITetrahedralChirality.Stereo stereo;
if (stereo0d.getParity() == InchiStereoParity.ODD) {
stereo = ITetrahedralChirality.Stereo.ANTI_CLOCKWISE;
} else if (stereo0d.getParity() == InchiStereoParity.EVEN) {
stereo = ITetrahedralChirality.Stereo.CLOCKWISE;
} else {
continue;
}
IStereoElement stereoElement = null;
if (stereo0d.getType() == InchiStereoType.Tetrahedral) {
stereoElement = builder.newInstance(ITetrahedralChirality.class, focus, neighbors, stereo);
} else if (stereo0d.getType() == InchiStereoType.Allene) {
IAtom[] peripherals = neighbors;
IAtom[] terminals = ExtendedTetrahedral.findTerminalAtoms(molecule, focus);
for (IAtom terminal : terminals) {
if (peripherals[1].equals(terminal)) {
peripherals[1] = findOtherSinglyBonded(molecule, terminal, peripherals[0]);
} else if (peripherals[2].equals(terminal)) {
peripherals[2] = findOtherSinglyBonded(molecule, terminal, peripherals[3]);
} else if (peripherals[0].equals(terminal)) {
peripherals[0] = findOtherSinglyBonded(molecule, terminal, peripherals[1]);
} else if (peripherals[3].equals(terminal)) {
peripherals[3] = findOtherSinglyBonded(molecule, terminal, peripherals[2]);
}
}
stereoElement = new ExtendedTetrahedral(focus, peripherals, stereo);
}
assert stereoElement != null;
molecule.addStereoElement(stereoElement);
} else if (stereo0d.getType() == InchiStereoType.DoubleBond) {
boolean extended = false;
InchiAtom[] neighbors = stereo0d.getAtoms();
IAtom x = inchiCdkAtomMap.get(neighbors[0]);
IAtom a = inchiCdkAtomMap.get(neighbors[1]);
IAtom b = inchiCdkAtomMap.get(neighbors[2]);
IAtom y = inchiCdkAtomMap.get(neighbors[3]);
IBond stereoBond = molecule.getBond(a, b);
if (stereoBond == null) {
extended = true;
IBond tmp = null;
stereoBond = ExtendedCisTrans.findCentralBond(molecule, a);
if (stereoBond == null)
continue;
IAtom[] ends = ExtendedCisTrans.findTerminalAtoms(molecule, stereoBond);
assert ends != null;
if (ends[0] != a)
flip(stereoBond);
} else {
if (!stereoBond.getBegin().equals(a))
flip(stereoBond);
}
int config = IStereoElement.TOGETHER;
if (stereo0d.getParity() == InchiStereoParity.EVEN)
config = IStereoElement.OPPOSITE;
if (extended) {
molecule.addStereoElement(new ExtendedCisTrans(stereoBond, new IBond[] { molecule.getBond(x, a), molecule.getBond(b, y) }, config));
} else {
molecule.addStereoElement(new DoubleBondStereochemistry(stereoBond, new IBond[] { molecule.getBond(x, a), molecule.getBond(b, y) }, config));
}
}
}
} | /storage/inchi/src/main/java/org/openscience/cdk/inchi/InChIToStructure.java |
robustness-copilot_data_221 | /**
* Does a layout of all aliphatic parts connected to the parts of the molecule
* that have already been laid out. Starts at the first bond with unplaced
* neighbours and stops when a ring is encountered.
*
* @throws CDKException if an error occurs
*/
private void layoutAcyclicParts() throws CDKException{
logger.debug("Start of handleAliphatics");
int safetyCounter = 0;
IAtomContainer unplacedAtoms = null;
IAtomContainer placedAtoms = null;
IAtomContainer longestUnplacedChain = null;
IAtom atom = null;
Vector2d direction = null;
Vector2d startVector = null;
boolean done;
do {
safetyCounter++;
done = false;
atom = getNextAtomWithAliphaticUnplacedNeigbors();
if (atom != null) {
unplacedAtoms = getUnplacedAtoms(atom);
placedAtoms = getPlacedAtoms(atom);
longestUnplacedChain = atomPlacer.getLongestUnplacedChain(molecule, atom);
logger.debug("---start of longest unplaced chain---");
try {
logger.debug("Start at atom no. " + (molecule.indexOf(atom) + 1));
logger.debug(AtomPlacer.listNumbers(molecule, longestUnplacedChain));
} catch (Exception exc) {
logger.debug(exc);
}
logger.debug("---end of longest unplaced chain---");
if (longestUnplacedChain.getAtomCount() > 1) {
if (placedAtoms.getAtomCount() > 1) {
logger.debug("More than one atoms placed already");
logger.debug("trying to place neighbors of atom " + (molecule.indexOf(atom) + 1));
atomPlacer.distributePartners(atom, placedAtoms, GeometryUtil.get2DCenter(placedAtoms), unplacedAtoms, bondLength);
direction = new Vector2d(longestUnplacedChain.getAtom(1).getPoint2d());
startVector = new Vector2d(atom.getPoint2d());
direction.sub(startVector);
logger.debug("Done placing neighbors of atom " + (molecule.indexOf(atom) + 1));
} else {
logger.debug("Less than or equal one atoms placed already");
logger.debug("Trying to get next bond vector.");
direction = atomPlacer.getNextBondVector(atom, placedAtoms.getAtom(0), GeometryUtil.get2DCenter(molecule), true);
}
for (int f = 1; f < longestUnplacedChain.getAtomCount(); f++) {
longestUnplacedChain.getAtom(f).setFlag(CDKConstants.ISPLACED, false);
}
atomPlacer.placeLinearChain(longestUnplacedChain, direction, bondLength);
} else {
done = true;
}
} else {
done = true;
}
} while (!done && safetyCounter <= molecule.getAtomCount());
logger.debug("End of handleAliphatics");
} | /tool/sdg/src/main/java/org/openscience/cdk/layout/StructureDiagramGenerator.java |
robustness-copilot_data_222 | /**
* Registers rendering parameters from {@link IGenerator}s
* with this model.
*
* @param generator
*/
public void registerParameters(IGenerator<? extends IChemObject> generator){
for (IGeneratorParameter<?> param : generator.getParameters()) {
try {
renderingParameters.put(param.getClass().getName(), param.getClass().newInstance());
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException("Could not create a copy of rendering parameter.");
}
}
} | /display/render/src/main/java/org/openscience/cdk/renderer/RendererModel.java |
robustness-copilot_data_223 | /**
* Method to use for adding mix-in annotations to use for augmenting
* specified class or interface. All annotations from
* <code>mixinSource</code> are taken to override annotations
* that <code>target</code> (or its supertypes) has.
*
* @param target Class (or interface) whose annotations to effectively override
* @param mixinSource Class (or interface) whose annotations are to
* be "added" to target's annotations, overriding as necessary
*
* @since 2.5
*/
public ObjectMapper addMixIn(Class<?> target, Class<?> mixinSource){
_mixIns.addLocalDefinition(target, mixinSource);
return this;
} | /src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java |
robustness-copilot_data_224 | /**
* Decode coordinates that have been placed in a byte buffer.
*
* @param str the string to decode
* @return array of coordinates
*/
static Point2d[] decodeCoordinates(String str){
if (str.startsWith("|(")) {
int end = str.indexOf(')', 2);
if (end < 0)
return new Point2d[0];
String[] strs = str.substring(2, end).split(";");
Point2d[] points = new Point2d[strs.length];
for (int i = 0; i < strs.length; i++) {
String coord = strs[i];
int first = coord.indexOf(',');
int second = coord.indexOf(',', first + 1);
String x = coord.substring(0, first);
String y = coord.substring(first + 1, second);
if (x.isEmpty())
x = "0";
if (y.isEmpty())
y = "0";
points[i] = new Point2d(Double.parseDouble(x), Double.parseDouble(y));
}
return points;
} else {
String[] strs = str.split(", ");
Point2d[] points = new Point2d[strs.length / 2];
for (int i = 0; i < strs.length; i += 2) {
points[i / 2] = new Point2d(Double.parseDouble(strs[i]), Double.parseDouble(strs[i + 1]));
}
return points;
}
} | /tool/sdg/src/main/java/org/openscience/cdk/layout/IdentityTemplateLibrary.java |
robustness-copilot_data_225 | /**
* Convenience function to resize the outline and maintain the existing
* center point.
*
* @param scaleX scale x-axis
* @param scaleY scale y-axis
* @return resized outline
*/
TextOutline resize(final double scaleX, final double scaleY){
final Point2D center = getCenter();
final AffineTransform transform = new AffineTransform();
transform.translate(center.getX(), center.getY());
transform.scale(scaleX, scaleY);
transform.translate(-center.getX(), -center.getY());
return transform(transform);
} | /display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/TextOutline.java |
robustness-copilot_data_226 | /**
* Mark all values in row i allowing it to be reset later.
*
* @param i row index
* @param marking the marking to store (should be negative)
*/
void markRow(int i, int marking){
for (int j = (i * mCols), end = j + mCols; j < end; j++) if (data[j] > 0)
data[j] = marking;
} | /base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/CompatibilityMatrix.java |
robustness-copilot_data_227 | /**
* Put the order the List of IIsotope according the probability occurrence.
*
* @param isotopes_TO The List of IIsotope
* @return The list of IIsotope ordered
*/
private List<IIsotope> orderList(List<IIsotope> isotopes_TO){
List<IIsotope> newOrderList = new ArrayList<IIsotope>();
for (int i = 0; i < orderElements.length; i++) {
String symbol = orderElements[i];
Iterator<IIsotope> itIso = isotopes_TO.iterator();
while (itIso.hasNext()) {
IIsotope isotopeToCo = itIso.next();
if (isotopeToCo.getSymbol().equals(symbol)) {
newOrderList.add(isotopeToCo);
}
}
}
return newOrderList;
} | /legacy/src/main/java/org/openscience/cdk/formula/MassToFormulaTool.java |
robustness-copilot_data_228 | /**
* Sets the converter for reading attributes of the specified class.
*
* @param clazz
* @param converter
* @return the previously registered converter for this class, or <code>null</code> if none was set before.
*/
public AttributeConverter<?> putAttributeConverter(final Class<?> clazz, final AttributeConverter<?> converter){
return this.converter.putAttributeConverter(clazz, converter);
} | /matsim/src/main/java/org/matsim/utils/objectattributes/ObjectAttributesXmlReader.java |
robustness-copilot_data_229 | /**
* Query has sharding info in offline servers or not.
*
* @return has sharding info in offline servers or not
*/
public boolean hasShardingInfoInOfflineServers(){
List<String> onlineInstances = jobNodeStorage.getJobNodeChildrenKeys(InstanceNode.ROOT);
int shardingTotalCount = configService.load(true).getShardingTotalCount();
for (int i = 0; i < shardingTotalCount; i++) {
if (!onlineInstances.contains(jobNodeStorage.getJobNodeData(ShardingNode.getInstanceNode(i)))) {
return true;
}
}
return false;
} | /elasticjob-lite/elasticjob-lite-core/src/main/java/org/apache/shardingsphere/elasticjob/lite/internal/sharding/ShardingService.java |
robustness-copilot_data_230 | /**
* Applies the given function to each compound tag in a compound-list subtag, if that subtag
* exists.
*
* @param key the key to look up
* @param consumer the function to apply
* @return true if the tag exists and was iterated over (even if it was empty); false otherwise
*/
public boolean iterateCompoundList(@NonNls String key, Consumer<? super CompoundTag> consumer){
return readCompoundList(key, compoundTags -> compoundTags.forEach(consumer));
} | /src/main/java/net/glowstone/util/nbt/CompoundTag.java |
robustness-copilot_data_231 | /**
* Melt implements the 'tidy' melt operation as described in these papers by Hadley Wickham.
*
* <p>Tidy concepts: {@see https://www.jstatsoft.org/article/view/v059i10}
*
* <p>Cast function details: {@see https://www.jstatsoft.org/article/view/v021i12}
*
* <p>In short, melt turns columns into rows, but in a particular way. Used with the cast method,
* it can help make data tidy. In a tidy dataset, every variable is a column and every observation
* a row.
*
* <p>This method returns a table that contains all the data in this table, but organized such
* that there is a set of identifier variables (columns) and a single measured variable (column).
* For example, given a table with columns:
*
* <p>patient_id, gender, age, weight, temperature,
*
* <p>it returns a table with the columns:
*
* <p>patient_id, variable, value
*
* <p>In the new format, the strings age, weight, and temperature have become cells in the
* measurement table, such that a single row in the source table might look like this in the
* result table:
*
* <p>1234, gender, male 1234, age, 42 1234, weight, 186 1234, temperature, 97.4
*
* <p>This kind of structure often makes for a good intermediate format for performing subsequent
* transformations. It is especially useful when combined with the {@link #cast()} operation
*
* @param idVariables A list of column names intended to be used as identifiers. In he example,
* only patient_id would be an identifier
* @param measuredVariables A list of columns intended to be used as measured variables. All
* columns must have the same type
* @param dropMissing drop any row where the value is missing
*/
public Table melt(List<String> idVariables, List<NumericColumn<?>> measuredVariables, Boolean dropMissing){
Table result = Table.create(name);
for (String idColName : idVariables) {
result.addColumns(column(idColName).type().create(idColName));
}
result.addColumns(StringColumn.create(MELT_VARIABLE_COLUMN_NAME), DoubleColumn.create(MELT_VALUE_COLUMN_NAME));
List<String> measureColumnNames = measuredVariables.stream().map(Column::name).collect(Collectors.toList());
TableSliceGroup slices = splitOn(idVariables.toArray(new String[0]));
for (TableSlice slice : slices) {
for (Row row : slice) {
for (String colName : measureColumnNames) {
if (!dropMissing || !row.isMissing(colName)) {
writeIdVariables(idVariables, result, row);
result.stringColumn(MELT_VARIABLE_COLUMN_NAME).append(colName);
double value = row.getNumber(colName);
result.doubleColumn(MELT_VALUE_COLUMN_NAME).append(value);
}
}
}
}
return result;
} | /core/src/main/java/tech/tablesaw/api/Table.java |
robustness-copilot_data_232 | /**
* Returns a StringColumn with the year and week-of-year derived from this column concatenated
* into a String that will sort lexicographically in temporal order.
*
* <p>This simplifies the production of plots and tables that aggregate values into standard
* temporal units (e.g., you want monthly data but your source data is more than a year long and
* you don't want months from different years aggregated together).
*/
StringColumn hourMinute(){
StringColumn newColumn = StringColumn.create(this.name() + " hour & minute");
for (int r = 0; r < this.size(); r++) {
long c1 = this.getLongInternal(r);
if (DateTimeColumn.valueIsMissing(c1)) {
newColumn.append(StringColumnType.missingValueIndicator());
} else {
String hm = Strings.padStart(String.valueOf(getHour(c1)), 2, '0');
hm = hm + ":" + Strings.padStart(String.valueOf(getMinute(c1)), 2, '0');
newColumn.append(hm);
}
}
return newColumn;
} | /core/src/main/java/tech/tablesaw/columns/datetimes/DateTimeMapFunctions.java |
robustness-copilot_data_233 | /**
* Finds the cluster of links <pre>startLink</pre> is part of. The cluster
* contains all links which can be reached starting at <code>startLink</code>
* and from where it is also possible to return again to <code>startLink</code>.
*
* @param startLink the link to start building the cluster
* @param modes the set of modes that are allowed to
* @return cluster of links <pre>startLink</pre> is part of
*/
private Map<Id<Link>, Link> findCluster(final Link startLink, final Set<String> modes){
final Map<Id<Link>, DoubleFlagRole> linkRoles = new HashMap<>(this.network.getLinks().size());
ArrayList<Node> pendingForward = new ArrayList<>();
ArrayList<Node> pendingBackward = new ArrayList<>();
TreeMap<Id<Link>, Link> clusterLinks = new TreeMap<>();
pendingForward.add(startLink.getToNode());
pendingBackward.add(startLink.getFromNode());
while (pendingForward.size() > 0) {
int idx = pendingForward.size() - 1;
Node currNode = pendingForward.remove(idx);
for (Link link : currNode.getOutLinks().values()) {
if (intersectingSets(modes, link.getAllowedModes())) {
DoubleFlagRole r = getDoubleFlag(link, linkRoles);
if (!r.forwardFlag) {
r.forwardFlag = true;
pendingForward.add(link.getToNode());
}
}
}
}
while (pendingBackward.size() > 0) {
int idx = pendingBackward.size() - 1;
Node currNode = pendingBackward.remove(idx);
for (Link link : currNode.getInLinks().values()) {
if (intersectingSets(modes, link.getAllowedModes())) {
DoubleFlagRole r = getDoubleFlag(link, linkRoles);
if (!r.backwardFlag) {
r.backwardFlag = true;
pendingBackward.add(link.getFromNode());
if (r.forwardFlag) {
clusterLinks.put(link.getId(), link);
}
}
}
}
}
return clusterLinks;
} | /matsim/src/main/java/org/matsim/core/network/algorithms/MultimodalNetworkCleaner.java |
robustness-copilot_data_234 | /**
* Generates the introspector job name based on the given domainUid.
*
* @param domainUid domainUid
* @param serverName WebLogic server name
* @return String introspector job name
*/
public static String toExternalServiceName(String domainUid, String serverName){
return toDns1123LegalName(String.format(EXTERNAL_SERVICE_PATTERN, domainUid, serverName, getExternalServiceNameSuffix()));
} | /operator/src/main/java/oracle/kubernetes/operator/helpers/LegalNames.java |
robustness-copilot_data_235 | /**
* Queues a 'picture' message to the socket (or actor), so it can be sent.
*
* @param picture The picture is a string that defines the type of each frame.
* This makes it easy to send a complex multiframe message in
* one call. The picture can contain any of these characters,
* each corresponding to zero or one arguments:
*
* <table>
* <caption> </caption>
* <tr><td>i = int (stores signed integer)</td></tr>
* <tr><td>1 = byte (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>c = byte[]</td></tr>
* <tr><td>f = ZFrame</td></tr>
* <tr><td>m = ZMsg (sends all frames in the ZMsg)<b>Has to be the last element of the picture</b></td></tr>
* <tr><td>z = sends zero-sized frame (0 arguments)</td></tr>
* </table>
* Note that s, b, f and m are encoded the same way and the choice is
* offered as a convenience to the sender, which may or may not already
* have data in a ZFrame or ZMsg. Does not change or take ownership of
* any arguments.
*
* Also see {@link #recvPicture(Socket, String)}} how to recv a
* multiframe picture.
* @param args Arguments according to the picture
* @return true if successful, false if sending failed for any reason
*/
public boolean sendPicture(Socket socket, String picture, Object... args){
if (!FORMAT.matcher(picture).matches()) {
throw new ZMQException(picture + " is not in expected format " + FORMAT.pattern(), ZError.EPROTO);
}
ZMsg msg = new ZMsg();
for (int pictureIndex = 0, argIndex = 0; pictureIndex < picture.length(); pictureIndex++, argIndex++) {
char pattern = picture.charAt(pictureIndex);
switch(pattern) {
case 'i':
{
msg.add(String.format("%d", (int) args[argIndex]));
break;
}
case '1':
{
msg.add(String.format("%d", (0xff) & (int) args[argIndex]));
break;
}
case '2':
{
msg.add(String.format("%d", (0xffff) & (int) args[argIndex]));
break;
}
case '4':
{
msg.add(String.format("%d", (0xffffffff) & (int) args[argIndex]));
break;
}
case '8':
{
msg.add(String.format("%d", (long) args[argIndex]));
break;
}
case 's':
{
msg.add((String) args[argIndex]);
break;
}
case 'b':
case 'c':
{
msg.add((byte[]) args[argIndex]);
break;
}
case 'f':
{
msg.add((ZFrame) args[argIndex]);
break;
}
case 'm':
{
ZMsg msgParm = (ZMsg) args[argIndex];
while (msgParm.size() > 0) {
msg.add(msgParm.pop());
}
break;
}
case 'z':
{
msg.add((byte[]) null);
argIndex--;
break;
}
default:
assert (false) : "invalid picture element '" + pattern + "'";
}
}
return msg.send(socket, false);
} | /src/main/java/org/zeromq/proto/ZPicture.java |
robustness-copilot_data_236 | /**
* Position the charge label on the top right of either the element or hydrogen label. Where the
* charge is placed depends on the number of hydrogens and their position relative to the
* element symbol.
*
* @param hydrogens number of hydrogen
* @param position position of hydrogen
* @param charge the charge label outline (to be positioned)
* @param element the element label outline
* @param hydrogen the hydrogen label outline
* @return positioned charge label
*/
TextOutline positionChargeLabel(int hydrogens, HydrogenPosition position, TextOutline charge, TextOutline element, TextOutline hydrogen){
final Rectangle2D chargeBounds = charge.getBounds();
Rectangle2D referenceBounds = element.getBounds();
if (hydrogens > 0 && (position == Left || position == Right))
referenceBounds = hydrogen.getBounds();
if (position == Left)
return charge.translate((referenceBounds.getMinX() - padding) - chargeBounds.getMaxX(), (referenceBounds.getMinY() - (chargeBounds.getHeight() / 2)) - chargeBounds.getMinY());
else
return charge.translate((referenceBounds.getMaxX() + padding) - chargeBounds.getMinX(), (referenceBounds.getMinY() - (chargeBounds.getHeight() / 2)) - chargeBounds.getMinY());
} | /display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardAtomGenerator.java |
robustness-copilot_data_237 | /**
* Gererates the plain-text email sections for sets of Health Check Execution Results.
*
* @param title The section title
* @param results the Health Check Execution Results to render as plain text
* @return the String for this section to be embedded in the e-mail
*/
protected String resultToPlainText(final String title, final List<HealthCheckExecutionResult> results){
final StringBuilder sb = new StringBuilder();
sb.append(title);
sb.append(System.lineSeparator());
if (results.size() == 0) {
sb.append("No " + StringUtils.lowerCase(title) + " could be found!");
sb.append(System.lineSeparator());
} else {
sb.append(StringUtils.repeat("-", NUM_DASHES));
sb.append(System.lineSeparator());
for (final HealthCheckExecutionResult result : results) {
sb.append(StringUtils.rightPad("[ " + result.getHealthCheckResult().getStatus().name() + " ]", HEALTH_CHECK_STATUS_PADDING));
sb.append(" ");
sb.append(result.getHealthCheckMetadata().getTitle());
sb.append(System.lineSeparator());
}
}
return sb.toString();
} | /bundle/src/main/java/com/adobe/acs/commons/hc/impl/HealthCheckStatusEmailer.java |
robustness-copilot_data_238 | /**
* Returns the Iterator to atoms making up this bond.
* Iterator.remove() is not implemented.
*
* @return An Iterator to atoms participating in this bond
* @see #setAtoms
*/
public Iterable<IAtom> atoms(){
return new Iterable<IAtom>() {
@Override
public Iterator<IAtom> iterator() {
return new AtomsIterator();
}
};
} | /base/data/src/main/java/org/openscience/cdk/Bond.java |
robustness-copilot_data_239 | /**
* Create the schema type entity, with the corresponding schema attributes and relationships if it doesn't exist or
* updates the existing one.
*
* @param userId the name of the calling user
* @param schemaType the schema type values
* @param externalSourceName the unique name of the external source
*
* @return unique identifier of the schema type in the repository
*
* @throws InvalidParameterException the bean properties are invalid
* @throws UserNotAuthorizedException user not authorized to issue this request
* @throws PropertyServerException problem accessing the property server
*/
public String upsertSchemaType(String userId, SchemaType schemaType, String externalSourceName) throws InvalidParameterException, PropertyServerException, UserNotAuthorizedException{
final String methodName = "upsertSchemaType";
invalidParameterHandler.validateUserId(userId, methodName);
invalidParameterHandler.validateName(schemaType.getQualifiedName(), QUALIFIED_NAME_PROPERTY_NAME, methodName);
invalidParameterHandler.validateName(schemaType.getDisplayName(), DISPLAY_NAME_PROPERTY_NAME, methodName);
Optional<EntityDetail> originalSchemaTypeEntity = findSchemaTypeEntity(userId, schemaType.getQualifiedName());
SchemaTypeBuilder schemaTypeBuilder = getSchemaTypeBuilder(schemaType);
String externalSourceGUID = dataEngineRegistrationHandler.getExternalDataEngine(userId, externalSourceName);
String schemaTypeGUID;
if (originalSchemaTypeEntity.isEmpty()) {
schemaTypeGUID = schemaTypeHandler.addSchemaType(userId, externalSourceGUID, externalSourceName, schemaTypeBuilder, methodName);
} else {
schemaTypeGUID = originalSchemaTypeEntity.get().getGUID();
EntityDetail updatedSchemaTypeEntity = buildSchemaTypeEntityDetail(schemaTypeGUID, schemaType);
EntityDetailDifferences entityDetailDifferences = repositoryHelper.getEntityDetailDifferences(originalSchemaTypeEntity.get(), updatedSchemaTypeEntity, true);
if (entityDetailDifferences.hasInstancePropertiesDifferences()) {
schemaTypeHandler.updateSchemaType(userId, externalSourceGUID, externalSourceName, schemaTypeGUID, SCHEMA_TYPE_GUID_PARAMETER_NAME, schemaTypeBuilder);
}
}
dataEngineSchemaAttributeHandler.upsertSchemaAttributes(userId, schemaType.getAttributeList(), externalSourceName, externalSourceGUID, schemaTypeGUID);
return schemaTypeGUID;
} | /open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEngineSchemaTypeHandler.java |
robustness-copilot_data_240 | /**
* This method multiply all the element over a value.
*
* @param formula Formula to correct
* @param factor Factor to multiply
* @return Formula with the correction
*/
private static String muliplier(String formula, int factor){
String finalformula = "";
String recentElementSymbol = "";
String recentElementCountString = "0";
for (int f = 0; f < formula.length(); f++) {
char thisChar = formula.charAt(f);
if (f < formula.length()) {
if (thisChar >= 'A' && thisChar <= 'Z') {
recentElementSymbol = String.valueOf(thisChar);
recentElementCountString = "0";
}
if (thisChar >= 'a' && thisChar <= 'z') {
recentElementSymbol += thisChar;
}
if (thisChar >= '0' && thisChar <= '9') {
recentElementCountString += thisChar;
}
}
if (f == formula.length() - 1 || (formula.charAt(f + 1) >= 'A' && formula.charAt(f + 1) <= 'Z')) {
Integer recentElementCount = Integer.valueOf(recentElementCountString);
if (recentElementCount == 0)
finalformula += recentElementSymbol + factor;
else
finalformula += recentElementSymbol + recentElementCount * factor;
}
}
return finalformula;
} | /tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java |
robustness-copilot_data_241 | /**
* Removes a single instance of the specified element from this
* queue, if it is present.
*
* @return <tt>true</tt> if the queue contained the specified
* element.
*/
public boolean remove(E value){
if (value == null)
return false;
int index = indices[this.getIndex(value)];
if (index < 0) {
return false;
} else {
if (classicalRemove) {
boolean decreasedKey = decreaseKey(value, Double.NEGATIVE_INFINITY);
if (decreasedKey && data[0] == value) {
this.poll();
return true;
} else
return false;
} else {
siftDownUp(index);
indices[this.getIndex(value)] = -1;
this.modCount++;
return true;
}
}
} | /matsim/src/main/java/org/matsim/core/router/priorityqueue/BinaryMinHeap.java |
robustness-copilot_data_242 | /**
* Parse the input parameters into the form needed to call workflowInstanceRemover. The results are set into
* instance variables. Method is package scope for unit testing.
*
* @throws ParseException
* if the date is in an invalid format.
* @throws PatternSyntaxException
* if the payloads contain illegal patterns
*/
void parseParameters() throws ParseException{
if (payloadPaths != null) {
payloads = payloadPaths.stream().map(Pattern::compile).collect(Collectors.toList());
}
if (StringUtils.isNotEmpty(olderThanVal)) {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date d = sdf.parse(olderThanVal);
olderThan = Calendar.getInstance();
olderThan.setTime(d);
}
workflowRemovalConfig = new WorkflowRemovalConfig(modelIds, statuses, payloads, olderThan, olderThanMillis);
workflowRemovalConfig.setBatchSize(BATCH_SIZE);
workflowRemovalConfig.setMaxDurationInMins(MAX_DURATION_MINS);
} | /bundle/src/main/java/com/adobe/acs/commons/mcp/impl/processes/WorkflowRemover.java |
robustness-copilot_data_243 | /**
* Method that can be used to serialize any Java value as
* a byte array. Functionally equivalent to calling
* {@link #writeValue(Writer,Object)} with {@link java.io.ByteArrayOutputStream}
* and getting bytes, but more efficient.
* Encoding used will be UTF-8.
*<p>
* Note: prior to version 2.1, throws clause included {@link IOException}; 2.1 removed it.
*/
public byte[] writeValueAsBytes(Object value) throws JsonProcessingException{
try (ByteArrayBuilder bb = new ByteArrayBuilder(_jsonFactory._getBufferRecycler())) {
_writeValueAndClose(createGenerator(bb, JsonEncoding.UTF8), value);
final byte[] result = bb.toByteArray();
bb.release();
return result;
} catch (JsonProcessingException e) {
throw e;
} catch (IOException e) {
throw JsonMappingException.fromUnexpectedIOE(e);
}
} | /src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java |
robustness-copilot_data_244 | /**
* Utility method for shifting a specified value in an index to the back
* (see {@link #permutation(int[])}).
*
* @param neighbors list of neighbors
* @param v the value to shift to the back
* @return <i>neighbors</i> array
*/
static int[] moveToBack(int[] neighbors, int v){
int j = 0;
for (int i = 0; i < neighbors.length; i++) {
if (neighbors[i] != v) {
neighbors[j++] = neighbors[i];
}
}
neighbors[neighbors.length - 1] = v;
return neighbors;
} | /tool/hash/src/main/java/org/openscience/cdk/hash/stereo/GeometricDoubleBondEncoderFactory.java |
robustness-copilot_data_245 | /**
* Reads the property block from the {@code input} setting the values in the
* container.
*
* @param input input resource
* @param container the structure with atoms / bonds present
* @param nAtoms the number of atoms in the atoms block
* @throws IOException low-level IO error
*/
void readPropertiesFast(final BufferedReader input, final IAtomContainer container, final int nAtoms) throws IOException, CDKException{
String line;
int offset = container.getAtomCount() - nAtoms;
Map<Integer, Sgroup> sgroups = new LinkedHashMap<>();
LINES: while ((line = input.readLine()) != null) {
int index, count, lnOffset;
Sgroup sgroup;
int length = line.length();
final PropertyKey key = PropertyKey.of(line);
switch(key) {
case ATOM_ALIAS:
index = readMolfileInt(line, 3) - 1;
final String label = input.readLine();
if (label == null)
return;
label(container, offset + index, label);
break;
case ATOM_VALUE:
index = readMolfileInt(line, 3) - 1;
final String comment = line.substring(7);
container.getAtom(offset + index).setProperty(CDKConstants.COMMENT, comment);
break;
case GROUP_ABBREVIATION:
final String group = input.readLine();
if (group == null)
return;
break;
case LEGACY_ATOM_LIST:
index = readUInt(line, 0, 3) - 1;
{
boolean negate = line.charAt(3) == 'T' || line.charAt(4) == 'T';
Expr expr = new Expr(Expr.Type.TRUE);
StringBuilder sb = new StringBuilder();
for (int i = 11; i < line.length(); i += 4) {
int atomicNumber = readUInt(line, i, 3);
expr.or(new Expr(Expr.Type.ELEMENT, atomicNumber));
}
if (negate)
expr.negate();
IAtom atom = container.getAtom(index);
if (AtomRef.deref(atom) instanceof QueryAtom) {
QueryAtom ref = (QueryAtom) AtomRef.deref(atom);
ref.setExpression(expr);
} else {
QueryAtom queryAtom = new QueryAtom(expr);
queryAtom.setPoint2d(atom.getPoint2d());
queryAtom.setPoint3d(atom.getPoint3d());
container.setAtom(index, queryAtom);
}
}
break;
case M_ALS:
index = readUInt(line, 7, 3) - 1;
{
boolean negate = line.charAt(13) == 'T' || line.charAt(14) == 'T';
Expr expr = new Expr(Expr.Type.TRUE);
StringBuilder sb = new StringBuilder();
for (int i = 16; i < line.length(); i++) {
if (line.charAt(i) != ' ') {
sb.append(line.charAt(i));
} else if (sb.length() != 0) {
int elem = Elements.ofString(sb.toString()).number();
if (elem != 0)
expr.or(new Expr(Expr.Type.ELEMENT, elem));
sb.setLength(0);
}
}
if (sb.length() != 0) {
int elem = Elements.ofString(sb.toString()).number();
if (elem != 0)
expr.or(new Expr(Expr.Type.ELEMENT, elem));
}
if (negate)
expr.negate();
IAtom atom = container.getAtom(index);
if (AtomRef.deref(atom) instanceof QueryAtom) {
QueryAtom ref = (QueryAtom) AtomRef.deref(atom);
ref.setExpression(expr);
} else {
QueryAtom queryAtom = new QueryAtom(expr);
queryAtom.setPoint2d(atom.getPoint2d());
queryAtom.setPoint3d(atom.getPoint3d());
container.setAtom(index, queryAtom);
}
}
break;
case M_CHG:
count = readUInt(line, 6, 3);
for (int i = 0, st = 10; i < count && st + 7 <= length; i++, st += 8) {
index = readMolfileInt(line, st) - 1;
int charge = readMolfileInt(line, st + 4);
container.getAtom(offset + index).setFormalCharge(charge);
}
break;
case M_ISO:
count = readUInt(line, 6, 3);
for (int i = 0, st = 10; i < count && st + 7 <= length; i++, st += 8) {
index = readMolfileInt(line, st) - 1;
int mass = readMolfileInt(line, st + 4);
if (mass < 0)
handleError("Absolute mass number should be >= 0, " + line);
else
container.getAtom(offset + index).setMassNumber(mass);
}
break;
case M_RAD:
count = readUInt(line, 6, 3);
for (int i = 0, st = 10; i < count && st + 7 <= length; i++, st += 8) {
index = readMolfileInt(line, st) - 1;
int value = readMolfileInt(line, st + 4);
SPIN_MULTIPLICITY multiplicity = SPIN_MULTIPLICITY.ofValue(value);
container.getAtom(offset + index).setProperty(CDKConstants.SPIN_MULTIPLICITY, multiplicity);
for (int e = 0; e < multiplicity.getSingleElectrons(); e++) container.addSingleElectron(offset + index);
}
break;
case M_RGP:
count = readUInt(line, 6, 3);
for (int i = 0, st = 10; i < count && st + 7 <= length; i++, st += 8) {
index = readMolfileInt(line, st) - 1;
int number = readMolfileInt(line, st + 4);
label(container, offset + index, "R" + number);
}
break;
case M_ZZC:
if (mode == Mode.STRICT) {
throw new CDKException("Atom property ZZC is illegal in STRICT mode");
}
index = readMolfileInt(line, 7) - 1;
String atomLabel = line.substring(11);
container.getAtom(offset + index).setProperty(CDKConstants.ACDLABS_LABEL, atomLabel);
break;
case M_STY:
count = readMolfileInt(line, 6);
for (int i = 0; i < count; i++) {
lnOffset = 10 + (i * 8);
index = readMolfileInt(line, lnOffset);
if (mode == Mode.STRICT && sgroups.containsKey(index))
handleError("STY line must appear before any other line that supplies Sgroup information");
sgroup = new Sgroup();
sgroups.put(index, sgroup);
SgroupType type = SgroupType.parseCtabKey(line.substring(lnOffset + 4, lnOffset + 7));
if (type != null)
sgroup.setType(type);
}
break;
case M_SST:
count = readMolfileInt(line, 6);
for (int i = 0, st = 10; i < count && st + 7 <= length; i++, st += 8) {
sgroup = ensureSgroup(sgroups, readMolfileInt(line, st));
if (mode == Mode.STRICT && sgroup.getType() != SgroupType.CtabCopolymer)
handleError("SST (Sgroup Subtype) specified for a non co-polymer group");
String sst = line.substring(st + 4, st + 7);
if (mode == Mode.STRICT && !("ALT".equals(sst) || "RAN".equals(sst) || "BLO".equals(sst)))
handleError("Invalid sgroup subtype: " + sst + " expected (ALT, RAN, or BLO)");
sgroup.putValue(SgroupKey.CtabSubType, sst);
}
break;
case M_SAL:
sgroup = ensureSgroup(sgroups, readMolfileInt(line, 7));
count = readMolfileInt(line, 10);
for (int i = 0, st = 14; i < count && st + 3 <= length; i++, st += 4) {
index = readMolfileInt(line, st) - 1;
sgroup.addAtom(container.getAtom(offset + index));
}
break;
case M_SBL:
sgroup = ensureSgroup(sgroups, readMolfileInt(line, 7));
count = readMolfileInt(line, 10);
for (int i = 0, st = 14; i < count && st + 3 <= length; i++, st += 4) {
index = readMolfileInt(line, st) - 1;
sgroup.addBond(container.getBond(offset + index));
}
break;
case M_SPL:
count = readMolfileInt(line, 6);
for (int i = 0, st = 10; i < count && st + 6 <= length; i++, st += 8) {
sgroup = ensureSgroup(sgroups, readMolfileInt(line, st));
sgroup.addParent(ensureSgroup(sgroups, readMolfileInt(line, st + 4)));
}
break;
case M_SCN:
count = readMolfileInt(line, 6);
for (int i = 0, st = 10; i < count && st + 6 <= length; i++, st += 8) {
sgroup = ensureSgroup(sgroups, readMolfileInt(line, st));
String con = line.substring(st + 4, Math.min(length, st + 7)).trim();
if (mode == Mode.STRICT && !("HH".equals(con) || "HT".equals(con) || "EU".equals(con)))
handleError("Unknown SCN type (expected: HH, HT, or EU) was " + con);
sgroup.putValue(SgroupKey.CtabConnectivity, con);
}
break;
case M_SDI:
sgroup = ensureSgroup(sgroups, readMolfileInt(line, 7));
count = readMolfileInt(line, 10);
assert count == 4;
sgroup.addBracket(new SgroupBracket(readMDLCoordinate(line, 13), readMDLCoordinate(line, 23), readMDLCoordinate(line, 33), readMDLCoordinate(line, 43)));
break;
case M_SMT:
sgroup = ensureSgroup(sgroups, readMolfileInt(line, 7));
sgroup.putValue(SgroupKey.CtabSubScript, line.substring(11).trim());
break;
case M_SBT:
count = readMolfileInt(line, 6);
for (int i = 0, st = 10; i < count && st + 7 <= length; i++, st += 8) {
sgroup = ensureSgroup(sgroups, readMolfileInt(line, st));
sgroup.putValue(SgroupKey.CtabBracketStyle, readMolfileInt(line, st + 4));
}
break;
case M_SDS:
if ("EXP".equals(line.substring(7, 10))) {
count = readMolfileInt(line, 10);
for (int i = 0, st = 14; i < count && st + 3 <= length; i++, st += 4) {
sgroup = ensureSgroup(sgroups, readMolfileInt(line, st));
sgroup.putValue(SgroupKey.CtabExpansion, true);
}
} else if (mode == Mode.STRICT) {
handleError("Expected EXP to follow SDS tag");
}
break;
case M_SPA:
sgroup = ensureSgroup(sgroups, readMolfileInt(line, 7));
count = readMolfileInt(line, 10);
Collection<IAtom> parentAtomList = sgroup.getValue(SgroupKey.CtabParentAtomList);
if (parentAtomList == null) {
sgroup.putValue(SgroupKey.CtabParentAtomList, parentAtomList = new HashSet<IAtom>());
}
for (int i = 0, st = 14; i < count && st + 3 <= length; i++, st += 4) {
index = readMolfileInt(line, st) - 1;
parentAtomList.add(container.getAtom(offset + index));
}
break;
case M_SNC:
count = readMolfileInt(line, 6);
for (int i = 0, st = 10; i < count && st + 7 <= length; i++, st += 8) {
sgroup = ensureSgroup(sgroups, readMolfileInt(line, st));
sgroup.putValue(SgroupKey.CtabComponentNumber, readMolfileInt(line, st + 4));
}
break;
case M_SDT:
sgroup = ensureSgroup(sgroups, readMolfileInt(line, 7));
if (length < 11)
break;
String name = line.substring(11, Math.min(41, length)).trim();
sgroup.putValue(SgroupKey.DataFieldName, name);
if (length < 41)
break;
String fmt = line.substring(41, Math.min(43, length)).trim();
if (fmt.length() == 1 && fmt.charAt(0) != 'F' && fmt.charAt(0) != 'N' && fmt.charAt(0) != 'T')
handleError("Invalid Data Sgroup field format: " + fmt);
if (!fmt.isEmpty())
sgroup.putValue(SgroupKey.DataFieldFormat, fmt);
if (length < 43)
break;
String units = line.substring(43, Math.min(63, length)).trim();
if (!units.isEmpty())
sgroup.putValue(SgroupKey.DataFieldUnits, units);
break;
case M_SDD:
break;
case M_SCD:
case M_SED:
sgroup = ensureSgroup(sgroups, readMolfileInt(line, 7));
String data = line.substring(11, Math.min(79, length));
String curr = sgroup.getValue(SgroupKey.Data);
if (curr != null)
data = curr + data;
sgroup.putValue(SgroupKey.Data, data);
break;
case M_END:
break LINES;
}
}
for (IAtom atom : container.atoms()) {
if (atom.getMassNumber() != null && atom.getMassNumber() < 0) {
handleError("Unstable use of mass delta on " + atom.getSymbol() + " please use M ISO");
atom.setMassNumber(null);
}
}
if (!sgroups.isEmpty()) {
List<Sgroup> sgroupOrgList = new ArrayList<>(sgroups.values());
List<Sgroup> sgroupCpyList = new ArrayList<>(sgroupOrgList.size());
for (int i = 0; i < sgroupOrgList.size(); i++) {
Sgroup cpy = sgroupOrgList.get(i).downcast();
sgroupCpyList.add(cpy);
}
for (int i = 0; i < sgroupOrgList.size(); i++) {
Sgroup newSgroup = sgroupCpyList.get(i);
Set<Sgroup> oldParents = new HashSet<>(newSgroup.getParents());
newSgroup.removeParents(oldParents);
for (Sgroup parent : oldParents) {
newSgroup.addParent(sgroupCpyList.get(sgroupOrgList.indexOf(parent)));
}
}
container.setProperty(CDKConstants.CTAB_SGROUPS, sgroupCpyList);
}
} | /storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Reader.java |
robustness-copilot_data_246 | /**
* Process the Web request and (optionally) delegate to the next
* {@code ShenyuPlugin} through the given {@link ShenyuPluginChain}.
*
* @param exchange the current server exchange
* @param chain provides a way to delegate to the next plugin
* @return {@code Mono<Void>} to indicate when request processing is complete
*/
public Mono<Void> execute(final ServerWebExchange exchange, final ShenyuPluginChain chain){
String pluginName = named();
PluginData pluginData = BaseDataCache.getInstance().obtainPluginData(pluginName);
if (pluginData != null && pluginData.getEnabled()) {
final Collection<SelectorData> selectors = BaseDataCache.getInstance().obtainSelectorData(pluginName);
if (CollectionUtils.isEmpty(selectors)) {
return handleSelectorIfNull(pluginName, exchange, chain);
}
SelectorData selectorData = matchSelector(exchange, selectors);
if (Objects.isNull(selectorData)) {
return handleSelectorIfNull(pluginName, exchange, chain);
}
selectorLog(selectorData, pluginName);
List<RuleData> rules = BaseDataCache.getInstance().obtainRuleData(selectorData.getId());
if (CollectionUtils.isEmpty(rules)) {
return handleRuleIfNull(pluginName, exchange, chain);
}
RuleData rule;
if (selectorData.getType() == SelectorTypeEnum.FULL_FLOW.getCode()) {
// get last
rule = rules.get(rules.size() - 1);
} else {
rule = matchRule(exchange, rules);
}
if (Objects.isNull(rule)) {
return handleRuleIfNull(pluginName, exchange, chain);
}
ruleLog(rule, pluginName);
return doExecute(exchange, chain, selectorData, rule);
}
return chain.execute(exchange);
} | /shenyu-plugin/shenyu-plugin-base/src/main/java/org/apache/shenyu/plugin/base/AbstractShenyuPlugin.java |
robustness-copilot_data_247 | /**
* Factory method for constructing {@link ObjectReader} that will
* read values of a type {@code List<type>}.
* Functionally same as:
*<pre>
* readerFor(type[].class);
*</pre>
*
* @since 2.11
*/
public ObjectReader readerForArrayOf(Class<?> type){
return _newReader(getDeserializationConfig(), _typeFactory.constructArrayType(type), null, null, _injectableValues);
} | /src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java |
robustness-copilot_data_248 | /**
* Reads the introspector config map for the specified domain, populating the following packet entries.
* INTROSPECTION_STATE_LABEL the value of the domain's 'introspectVersion' when this map was created
*
* @param ns the namespace of the domain
* @param domainUid the unique domain ID
* @return a step to do the processing.
*/
public static Step readIntrospectionVersionStep(String ns, String domainUid){
String configMapName = getIntrospectorConfigMapName(domainUid);
return new CallBuilder().readConfigMapAsync(configMapName, ns, domainUid, new ReadIntrospectionVersionStep());
} | /operator/src/main/java/oracle/kubernetes/operator/helpers/ConfigMapHelper.java |
robustness-copilot_data_249 | /**
* writes a single frame in XYZ format to the Writer.
* @param mol the Molecule to write
*/
public void writeMolecule(IAtomContainer mol) throws IOException{
String st = "";
boolean writecharge = true;
try {
String s1 = "" + mol.getAtomCount();
writer.write(s1, 0, s1.length());
writer.write('\n');
String s2 = mol.getTitle();
if (s2 != null) {
writer.write(s2, 0, s2.length());
}
writer.write('\n');
Iterator<IAtom> atoms = mol.atoms().iterator();
while (atoms.hasNext()) {
IAtom a = atoms.next();
st = a.getSymbol();
Point3d p3 = a.getPoint3d();
if (p3 != null) {
st = st + "\t" + (p3.x < 0 ? "" : " ") + fsb.format(p3.x) + "\t" + (p3.y < 0 ? "" : " ") + fsb.format(p3.y) + "\t" + (p3.z < 0 ? "" : " ") + fsb.format(p3.z);
} else {
st = st + "\t " + fsb.format(0.0) + "\t " + fsb.format(0.0) + "\t " + fsb.format(0.0);
}
if (writecharge) {
double ct = a.getCharge() == CDKConstants.UNSET ? 0.0 : a.getCharge();
st = st + "\t" + ct;
}
writer.write(st, 0, st.length());
writer.write('\n');
}
} catch (IOException e) {
logger.error("Error while writing file: ", e.getMessage());
logger.debug(e);
}
} | /storage/io/src/main/java/org/openscience/cdk/io/XYZWriter.java |
robustness-copilot_data_250 | /** {@inheritDoc}
* Function is called by the main program and serves as a starting point for the comparison procedure.
*
* @param shouldMatchBonds
*/
public synchronized void searchMCS(boolean shouldMatchBonds){
List<List<Integer>> mappings = null;
try {
if (source.getAtomCount() >= target.getAtomCount()) {
mappings = new MCSPlus().getOverlaps(source, target, shouldMatchBonds);
} else {
flagExchange = true;
mappings = new MCSPlus().getOverlaps(target, source, shouldMatchBonds);
}
PostFilter.filter(mappings);
setAllMapping();
setAllAtomMapping();
setFirstMapping();
setFirstAtomMapping();
} catch (CDKException e) {
mappings = null;
}
} | /legacy/src/main/java/org/openscience/cdk/smsd/algorithm/mcsplus/MCSPlusHandler.java |
robustness-copilot_data_251 | /**
* Save the inputstream to a binary property under the cache entry node.
* @throws RepositoryException
*/
private void populateBinaryContent() throws RepositoryException{
final Node contents = getOrCreateByPath(entryNode, JCRHttpCacheStoreConstants.PATH_CONTENTS, JcrConstants.NT_FILE, JcrConstants.NT_FILE);
final Node jcrContent = getOrCreateByPath(contents, JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE, JcrConstants.NT_RESOURCE);
final Binary binary = session.getValueFactory().createBinary(cacheContent.getInputDataStream());
jcrContent.setProperty(JcrConstants.JCR_DATA, binary);
jcrContent.setProperty(JcrConstants.JCR_MIMETYPE, cacheContent.getContentType());
} | /bundle/src/main/java/com/adobe/acs/commons/httpcache/store/jcr/impl/writer/EntryNodeWriter.java |
robustness-copilot_data_252 | /**
* Find all the resources needed for the package definition.
*
* @param resourceResolver the resource resolver to find the resources
* @param language the Query language
* @param statement the Query statement
* @param relPath the relative path to resolve against query result nodes for package resources
* @return a unique set of paths to include in the package
* @throws RepositoryException
*/
public List<Resource> findResources(final ResourceResolver resourceResolver, final String language, final String statement, final String relPath) throws RepositoryException{
if (StringUtils.isEmpty(statement)) {
return Collections.emptyList();
}
final String[] lines = StringUtils.split(statement, '\n');
if (QUERY_BUILDER.equalsIgnoreCase(language)) {
return getResourcesFromQueryBuilder(resourceResolver, lines, relPath);
} else if (LIST.equalsIgnoreCase(language)) {
return getResourcesFromList(resourceResolver, lines, relPath);
} else {
return getResourcesFromQuery(resourceResolver, language, statement, relPath);
}
} | /bundle/src/main/java/com/adobe/acs/commons/util/impl/QueryHelperImpl.java |
robustness-copilot_data_253 | /**
* Creates asynchronous step to read WebLogic server state from a particular pod.
*
* @param info the domain presence
* @param pod The pod
* @param serverName Server name
* @param timeoutSeconds Timeout in seconds
* @return Created step
*/
private static Step createServerStatusReaderStep(DomainPresenceInfo info, V1Pod pod, String serverName, long timeoutSeconds){
return new ServerStatusReaderStep(info, pod, serverName, timeoutSeconds, new ServerHealthStep(serverName, pod, null));
} | /operator/src/main/java/oracle/kubernetes/operator/ServerStatusReader.java |
robustness-copilot_data_254 | /**
* Find a a Location obove or below the specified Location, which is on ground.
*
* <p>The returned Location will be at the center of the block, X and Y wise.
*
* @param spawn The Location a safe spawn position should be found at.
* @return The location to spawn the player at.
*/
private static Location findSafeSpawnLocation(Location spawn){
World world = spawn.getWorld();
int blockX = spawn.getBlockX();
int blockY = spawn.getBlockY();
int blockZ = spawn.getBlockZ();
int highestY = world.getHighestBlockYAt(blockX, blockZ);
int y = blockY;
boolean wasPreviousSafe = false;
for (; y <= highestY; y++) {
Material type = world.getBlockAt(blockX, y, blockZ).getType();
boolean safe = Material.AIR.equals(type);
if (wasPreviousSafe && safe) {
y--;
break;
}
wasPreviousSafe = safe;
}
return new Location(world, blockX + 0.5, y, blockZ + 0.5);
} | /src/main/java/net/glowstone/entity/GlowPlayer.java |
robustness-copilot_data_255 | /**
* Checks an atom to see if it should be drawn. There are three reasons
* not to draw an atom - a) no coordinates, b) an invisible hydrogen or
* c) an invisible carbon.
*
* @param atom the atom to check
* @param container the atom container the atom is part of
* @param model the renderer model
* @return true if the atom should be drawn
*/
protected boolean canDraw(IAtom atom, IAtomContainer container, RendererModel model){
if (!hasCoordinates(atom)) {
return false;
}
if (invisibleHydrogen(atom, model)) {
return false;
}
if (invisibleCarbon(atom, container, model)) {
return false;
}
return true;
} | /display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/BasicAtomGenerator.java |
robustness-copilot_data_256 | /**
* Convert the serialized JSON data found in the node property to Resources.
*
* @return the list of children sorting using the comparator.
* @throws InvalidDataFormatException
*/
private List<SyntheticChildAsPropertyResource> deserialize() throws InvalidDataFormatException{
final long start = System.currentTimeMillis();
final String propertyData = this.resource.getValueMap().get(this.propertyName, EMPTY_JSON);
List<SyntheticChildAsPropertyResource> resources;
resources = deserializeToSyntheticChildResources(JsonObjectUtil.toJsonObject(propertyData));
if (this.comparator != null) {
Collections.sort(resources, this.comparator);
}
log.debug("Get operation for [ {} ] in [ {} ms ]", this.resource.getPath() + "/" + this.propertyName, System.currentTimeMillis() - start);
return resources;
} | /bundle/src/main/java/com/adobe/acs/commons/synth/children/ChildrenAsPropertyResource.java |
robustness-copilot_data_257 | /**
* Step through the record, character by character, extracting each column and enduring that escaped double quotes
* and other tricks found in CSV files are handled.
*
* @param fileRecord a single record from the CSV file store
* @return an array of column values extracted from the record
*/
private List<String> parseRecord(String fileRecord){
if ((fileRecord == null) || (fileRecord.isEmpty())) {
return null;
}
List<String> result = new ArrayList<>();
StringBuffer currentValue = new StringBuffer();
boolean inQuotes = false;
boolean startCollectingCharacters = false;
boolean doubleQuotesInColumn = false;
char[] characters = fileRecord.toCharArray();
for (char character : characters) {
if (inQuotes) {
startCollectingCharacters = true;
if (character == quoteChar) {
inQuotes = false;
doubleQuotesInColumn = false;
} else {
if (character == '\"') {
if (!doubleQuotesInColumn) {
currentValue.append(character);
doubleQuotesInColumn = true;
}
} else {
currentValue.append(character);
}
}
} else {
if (character == quoteChar) {
inQuotes = true;
if (characters[0] != '"' && quoteChar == '\"') {
currentValue.append('"');
}
if (startCollectingCharacters) {
currentValue.append('"');
}
} else if (character == delimiterChar) {
result.add(currentValue.toString());
currentValue = new StringBuffer();
startCollectingCharacters = false;
} else if (character == '\n') {
break;
} else if (character != '\r') {
currentValue.append(character);
}
}
}
result.add(currentValue.toString());
return result;
} | /open-metadata-implementation/adapters/open-connectors/data-store-connectors/file-connectors/csv-file-connector/src/main/java/org/odpi/openmetadata/adapters/connectors/datastore/csvfile/CSVFileStoreConnector.java |
robustness-copilot_data_258 | /**
* Construct the folder structure in which a data file is stored all the way to the SoftwareServerCapability. Care is
* taken to maintain uniqueness of the relationship NestedFile that is between the file and the first folder.
*
* @param fileGuid data file guid
* @param pathName file path
* @param externalSourceGuid external source guid
* @param externalSourceName external source name
* @param userId user id
* @param methodName method name
*
* @throws InvalidParameterException if invalid parameters
* @throws PropertyServerException if errors in repository
* @throws UserNotAuthorizedException if user not authorized
*/
public void upsertFolderHierarchy(String fileGuid, String pathName, String externalSourceGuid, String externalSourceName, String userId, String methodName) throws InvalidParameterException, PropertyServerException, UserNotAuthorizedException{
if (StringUtils.isEmpty(pathName)) {
return;
}
validateParameters(fileGuid, externalSourceGuid, externalSourceName, userId, methodName);
List<FileFolder> folders = extractFolders(pathName, externalSourceName, methodName);
String folderGuid = "";
String previousEntityGuid = fileGuid;
String relationshipTypeName = NESTED_FILE_TYPE_NAME;
for (FileFolder folder : folders) {
if (relationshipTypeName.equals(NESTED_FILE_TYPE_NAME)) {
deleteExistingNestedFileRelationships(fileGuid, externalSourceGuid, externalSourceName, userId, methodName);
}
folderGuid = upsertFolder(externalSourceGuid, externalSourceName, folder, userId, methodName);
dataEngineCommonHandler.upsertExternalRelationship(userId, folderGuid, previousEntityGuid, relationshipTypeName, FILE_FOLDER_TYPE_NAME, externalSourceName, null);
previousEntityGuid = folderGuid;
relationshipTypeName = FOLDER_HIERARCHY_TYPE_NAME;
}
dataEngineCommonHandler.upsertExternalRelationship(userId, externalSourceGuid, folderGuid, SERVER_ASSET_USE_TYPE_NAME, SOFTWARE_SERVER_CAPABILITY_TYPE_NAME, externalSourceName, null);
} | /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_259 | /**
* Flip the storage order of atoms in a bond.
* @param bond the bond
*/
private void flip(IBond bond){
bond.setAtoms(new IAtom[] { bond.getEnd(), bond.getBegin() });
} | /storage/inchi/src/main/java/org/openscience/cdk/inchi/InChIToStructure.java |
robustness-copilot_data_260 | /**
* Formats an integer to fit into the connection table and changes it
* to a String.
*
* @param x The int to be formated
* @param n Length of the String
* @return The String to be written into the connectiontable
*/
protected static String formatMDLInt(int x, int n){
char[] buf = new char[n];
Arrays.fill(buf, ' ');
String val = Integer.toString(x);
if (val.length() > n)
val = "0";
int off = n - val.length();
for (int i = 0; i < val.length(); i++) buf[off + i] = val.charAt(i);
return new String(buf);
} | /storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Writer.java |
robustness-copilot_data_261 | /**
* Convert the a character (from an MDL V2000 input) to a charge value:
* 1 = +1, 2 = +2, 3 = +3, 4 = doublet radical, 5 = -1, 6 = -2, 7 = -3.
*
* @param c a character
* @return formal charge
*/
private static int toCharge(final char c){
switch(c) {
case '1':
return +3;
case '2':
return +2;
case '3':
return +1;
case '4':
return 0;
case '5':
return -1;
case '6':
return -2;
case '7':
return -3;
}
return 0;
} | /storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Reader.java |
robustness-copilot_data_262 | /**
* Returns a selection for all records that don't match both of the given functions. In other
* words, if both sel1 and sel2 are true, the record as a whole is false, and if either (or both)
* of sel1 or sel2 is {@code false}, the record as a whole is {@code true}.
*/
public static Function<Table, Selection> notBoth(Function<Table, Selection> sel1, Function<Table, Selection> sel2){
return new Not(both(sel1, sel2));
} | /core/src/main/java/tech/tablesaw/api/QuerySupport.java |
robustness-copilot_data_263 | /**
* Looking if the Atom belongs to the halogen family.
*
* @param atom The IAtom
* @return True, if it belongs
*/
private boolean familyHalogen(IAtom atom){
String symbol = atom.getSymbol();
return symbol.equals("F") || symbol.equals("Cl") || symbol.equals("Br") || symbol.equals("I");
} | /descriptor/qsaratomic/src/main/java/org/openscience/cdk/qsar/descriptors/atomic/IPAtomicHOSEDescriptor.java |
robustness-copilot_data_264 | /**
* Adds the specified module / config-group with the specified name to the
* configuration.
* <p></p>
* This is the typical way to "materialize" material that, so far, exists only as Map, into a specialized module.
* @param specializedConfigModule
*
* @throws IllegalArgumentException
* if a config-group with the specified name already exists.
*/
public final void addModule(final ConfigGroup specializedConfigModule){
String name = specializedConfigModule.getName();
if (name == null || name.isEmpty()) {
throw new RuntimeException("cannot insert module with empty name");
}
ConfigGroup m = this.modules.get(name);
if (m != null) {
if (m.getClass() == ConfigGroup.class && specializedConfigModule.getClass() != ConfigGroup.class) {
copyTo(m, specializedConfigModule);
this.modules.put(name, specializedConfigModule);
} else {
throw new IllegalArgumentException("Module " + name + " exists already.");
}
}
this.modules.put(name, specializedConfigModule);
} | /matsim/src/main/java/org/matsim/core/config/Config.java |
robustness-copilot_data_265 | /**
* Determine the length of the line excluding trailing whitespace.
*
* @param str a string
* @return the length when trailing white space is removed
*/
static int length(final String str){
int i = str.length() - 1;
while (i >= 0 && str.charAt(i) == ' ') {
i--;
}
return i + 1;
} | /storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Reader.java |
robustness-copilot_data_266 | /**
* Run the {@link OnDeployScript}, if it has not previously been run successfully.
* @param resourceResolver the resource resolver to use when running
* @param script the script to run.
* @return true if the script is executed, false if it has previous been run successfully
*/
protected boolean runScript(ResourceResolver resourceResolver, OnDeployScript script){
Resource statusResource = getOrCreateStatusTrackingResource(resourceResolver, script.getClass());
String status = getScriptStatus(statusResource);
if (status == null || status.equals(SCRIPT_STATUS_FAIL)) {
trackScriptStart(statusResource);
try {
script.execute(resourceResolver);
logger.info("On-deploy script completed successfully: {}", statusResource.getPath());
trackScriptEnd(statusResource, SCRIPT_STATUS_SUCCESS, "");
return true;
} catch (Exception e) {
String errMsg = "On-deploy script failed: " + statusResource.getPath();
logger.error(errMsg, e);
resourceResolver.revert();
trackScriptEnd(statusResource, SCRIPT_STATUS_FAIL, ExceptionUtils.getStackTrace(e.getCause()));
throw new OnDeployEarlyTerminationException(new RuntimeException(errMsg));
}
} else if (!status.equals(SCRIPT_STATUS_SUCCESS)) {
String errMsg = "On-deploy script is already running or in an otherwise unknown state: " + statusResource.getPath() + " - status: " + status;
logger.error(errMsg);
throw new OnDeployEarlyTerminationException(new RuntimeException(errMsg));
} else {
logger.debug("Skipping on-deploy script, as it is already complete: {}", statusResource.getPath());
}
return false;
} | /bundle/src/main/java/com/adobe/acs/commons/ondeploy/impl/OnDeployExecutorImpl.java |
robustness-copilot_data_267 | /**
* Get all paths of lengths 0 to the specified length.
*
* This method will find all paths upto length N starting from each atom in the molecule and return the unique set
* of such paths.
*
* @param container The molecule to search
* @return A map of path strings, keyed on themselves
*/
private Integer[] findPaths(IAtomContainer container){
ShortestPathWalker walker = new ShortestPathWalker(container);
List<Integer> paths = new ArrayList<Integer>();
int patternIndex = 0;
for (String s : walker.paths()) {
int toHashCode = s.hashCode();
paths.add(patternIndex, toHashCode);
patternIndex++;
}
IRingSet sssr = Cycles.essential(container).toRingSet();
RingSetManipulator.sort(sssr);
for (Iterator<IAtomContainer> it = sssr.atomContainers().iterator(); it.hasNext(); ) {
IAtomContainer ring = it.next();
int toHashCode = String.valueOf(ring.getAtomCount()).hashCode();
paths.add(patternIndex, toHashCode);
patternIndex++;
}
List<String> l = new ArrayList<String>();
for (Iterator<IAtom> it = container.atoms().iterator(); it.hasNext(); ) {
IAtom atom = it.next();
int charge = atom.getFormalCharge() == null ? 0 : atom.getFormalCharge();
if (charge != 0) {
l.add(atom.getSymbol().concat(String.valueOf(charge)));
}
}
Collections.sort(l);
int toHashCode = l.hashCode();
paths.add(patternIndex, toHashCode);
patternIndex++;
l = new ArrayList<String>();
for (Iterator<IAtom> it = container.atoms().iterator(); it.hasNext(); ) {
IAtom atom = it.next();
int st = atom.getStereoParity() == null ? 0 : atom.getStereoParity();
if (st != 0) {
l.add(atom.getSymbol().concat(String.valueOf(st)));
}
}
Collections.sort(l);
toHashCode = l.hashCode();
paths.add(patternIndex, toHashCode);
patternIndex++;
if (container.getSingleElectronCount() > 0) {
StringBuilder radicalInformation = new StringBuilder();
radicalInformation.append("RAD: ").append(String.valueOf(container.getSingleElectronCount()));
paths.add(patternIndex, radicalInformation.toString().hashCode());
patternIndex++;
}
if (container.getLonePairCount() > 0) {
StringBuilder lpInformation = new StringBuilder();
lpInformation.append("LP: ").append(String.valueOf(container.getLonePairCount()));
paths.add(patternIndex, lpInformation.toString().hashCode());
patternIndex++;
}
return paths.toArray(new Integer[paths.size()]);
} | /descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/ShortestPathFingerprinter.java |
robustness-copilot_data_268 | /**
* Method that can be used to find primitive type for given class if (but only if)
* it is either wrapper type or primitive type; returns {@code null} if type is neither.
*
* @since 2.7
*/
public static Class<?> primitiveType(Class<?> type){
if (type.isPrimitive()) {
return type;
}
if (type == Integer.class) {
return Integer.TYPE;
}
if (type == Long.class) {
return Long.TYPE;
}
if (type == Boolean.class) {
return Boolean.TYPE;
}
if (type == Double.class) {
return Double.TYPE;
}
if (type == Float.class) {
return Float.TYPE;
}
if (type == Byte.class) {
return Byte.TYPE;
}
if (type == Short.class) {
return Short.TYPE;
}
if (type == Character.class) {
return Character.TYPE;
}
return null;
} | /src/main/java/com/fasterxml/jackson/databind/util/ClassUtil.java |
robustness-copilot_data_269 | /**
* Checks if the hook has content meaning as it has at least attachment or result with error message.
*
* @return <code>true</code> if the hook has content otherwise <code>false</code>
*/
public boolean hasContent(){
if (embeddings.length > 0) {
// assuming that if the embedding exists then it is not empty
return true;
}
if (StringUtils.isNotBlank(result.getErrorMessage())) {
return true;
}
// TODO: hook with 'output' should be treated as empty or not?
return false;
} | /src/main/java/net/masterthought/cucumber/json/Hook.java |
robustness-copilot_data_270 | /**
* Obtain the InChI auxiliary info for the provided structure using
* using the specified InChI options.
*
* @param container the structure to obtain the numbers of
* @return auxiliary info
* @throws CDKException the inchi could not be generated
*/
static String auxInfo(IAtomContainer container, INCHI_OPTION... options) throws CDKException{
InChIGeneratorFactory factory = InChIGeneratorFactory.getInstance();
boolean org = factory.getIgnoreAromaticBonds();
factory.setIgnoreAromaticBonds(true);
InChIGenerator gen = factory.getInChIGenerator(container, Arrays.asList(options));
factory.setIgnoreAromaticBonds(org);
if (gen.getReturnStatus() != INCHI_RET.OKAY && gen.getReturnStatus() != INCHI_RET.WARNING)
throw new CDKException("Could not generate InChI Numbers: " + gen.getMessage());
return gen.getAuxInfo();
} | /storage/inchi/src/main/java/org/openscience/cdk/graph/invariant/InChINumbersTools.java |
robustness-copilot_data_271 | /**
* Calculates the orbits of the atoms of the molecule.
*
* @return a list of orbits
*/
public List<Orbit> calculateOrbits(){
List<Orbit> orbits = new ArrayList<Orbit>();
List<SymmetryClass> symmetryClasses = super.getSymmetryClasses();
for (SymmetryClass symmetryClass : symmetryClasses) {
Orbit orbit = new Orbit(symmetryClass.getSignatureString(), -1);
for (int atomIndex : symmetryClass) {
orbit.addAtom(atomIndex);
}
orbits.add(orbit);
}
return orbits;
} | /descriptor/signature/src/main/java/org/openscience/cdk/signature/MoleculeSignature.java |
robustness-copilot_data_272 | /**
* Checks if the agent has valid CQ-Action-Scope: ResourceOnly header.
*
* @param agent Agent to check
* @return true if the Agent's headers contain the expected values
*/
private boolean isResourceOnly(final Agent agent){
final ValueMap properties = agent.getConfiguration().getProperties();
final String[] headers = properties.get(AgentConfig.PROTOCOL_HTTP_HEADERS, new String[] {});
for (final String header : headers) {
if (StringUtils.equals(header, CQ_SCOPE_ACTION_HEADER)) {
return true;
}
}
return false;
} | /bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/DispatcherFlushFilter.java |
robustness-copilot_data_273 | /**
* Format local date time from timestamp local date time.
*
* @param timestamp the timestamp
* @return the local date time
*/
public static LocalDateTime formatLocalDateTimeFromTimestamp(final Long timestamp){
return LocalDateTime.ofEpochSecond(timestamp / 1000, 0, ZoneOffset.ofHours(8));
} | /shenyu-common/src/main/java/org/apache/shenyu/common/utils/DateUtils.java |
robustness-copilot_data_274 | /**
* Appends an empty row and returns a Row object indexed to the newly added row so values can be
* set.
*
* <p>Intended usage:
*
* <p>for (int i = 0; ...) { Row row = table.appendRow(); row.setString("name", "Bob");
* row.setFloat("IQ", 123.4f); ...etc. }
*/
public Row appendRow(){
for (final Column<?> column : columnList) {
column.appendMissing();
}
return row(rowCount() - 1);
} | /core/src/main/java/tech/tablesaw/api/Table.java |
robustness-copilot_data_275 | /**
* Computes the (expected or planned) activity end time, depending on the configured time interpretation.
*/
public static OptionalTime decideOnActivityEndTime(Activity act, double now, Config config){
return decideOnActivityEndTime(act, now, config.plans().getActivityDurationInterpretation());
} | /matsim/src/main/java/org/matsim/core/population/PopulationUtils.java |
robustness-copilot_data_276 | /**
* Aggregates a set of checksum entries into a single checksum value.
* @param checksums the checksums
* @return the checksum value
*/
protected String aggregateChecksums(final Map<String, String> checksums){
if (checksums.isEmpty()) {
return null;
}
StringBuilder data = new StringBuilder();
for (Map.Entry<String, String> entry : checksums.entrySet()) {
data.append(entry.getKey() + "=" + entry.getValue());
}
return DigestUtils.sha1Hex(data.toString());
} | /bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/ChecksumGeneratorImpl.java |
robustness-copilot_data_277 | /**
* Adds an automatically calculated offset to the coordinates of all atoms
* such that all coordinates are positive and the smallest x or y coordinate
* is exactly zero.
* See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
*
*@param atomCon AtomContainer for which all the atoms are translated to
* positive coordinates
*/
public static void translateAllPositive(IAtomContainer atomCon){
double minX = Double.MAX_VALUE;
double minY = Double.MAX_VALUE;
Iterator<IAtom> atoms = atomCon.atoms().iterator();
while (atoms.hasNext()) {
IAtom atom = (IAtom) atoms.next();
if (atom.getPoint2d() != null) {
if (atom.getPoint2d().x < minX) {
minX = atom.getPoint2d().x;
}
if (atom.getPoint2d().y < minY) {
minY = atom.getPoint2d().y;
}
}
}
logger.debug("Translating: minx=" + minX + ", minY=" + minY);
translate2D(atomCon, minX * -1, minY * -1);
} | /legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java |
robustness-copilot_data_278 | /**
* Compute the permutation parity of the values {@code vs}. The parity is
* whether we need to do an odd or even number of swaps to put the values in
* sorted order.
*
* @param vs values
* @return parity of the permutation (odd = -1, even = +1)
*/
private int permutationParity(int[] vs){
int n = 0;
for (int i = 0; i < vs.length; i++) for (int j = i + 1; j < vs.length; j++) if (vs[i] > vs[j])
n++;
return (n & 0x1) == 1 ? -1 : 1;
} | /base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/StereoMatch.java |
robustness-copilot_data_279 | /**
* Test whether the subtag with the given key is of {@link List} type.
*
* @param key the key to look up
* @param type the {@link TagType} of the list's elements
* @return true if the subtag exists and is a {@link List}; false otherwise
*/
public boolean isList(@NonNls String key, TagType type){
if (!is(key, ListTag.class)) {
return false;
}
ListTag tag = getTag(key, ListTag.class);
return tag.getChildType() == type;
} | /src/main/java/net/glowstone/util/nbt/CompoundTag.java |
robustness-copilot_data_280 | /**
* Count and find first heavy atom(s) (non Hydrogens) in a chain.
*
* @param molecule the reference molecule for searching the chain
* @param chain chain to be searched
* @return the atom number of the first heavy atom the number of heavy atoms in the chain
*/
public int[] findHeavyAtomsInChain(IAtomContainer molecule, IAtomContainer chain){
int[] heavy = { -1, -1 };
int hc = 0;
for (int i = 0; i < chain.getAtomCount(); i++) {
if (isHeavyAtom(chain.getAtom(i))) {
if (heavy[0] < 0) {
heavy[0] = molecule.indexOf(chain.getAtom(i));
}
hc++;
}
}
heavy[1] = hc;
return heavy;
} | /tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomPlacer3D.java |
robustness-copilot_data_281 | /**
* Makes sure that the travel times "make sense".
* <p></p>
* Imagine short bin sizes (e.g. 5min), small links (e.g. 300 veh/hour)
* and small sample sizes (e.g. 2%). This would mean that effectively
* in the simulation only 6 vehicles can pass the link in one hour,
* one every 10min. So, the travel time in one time slot could be
* >= 10min if two cars enter the link at the same time. If no car
* enters in the next time bin, the travel time in that time bin should
* still be >=5 minutes (10min - binSize), and not freespeedTraveltime,
* because actually every car entering the link in this bin will be behind
* the car entered before, which still needs >=5min until it can leave.
* <p></p>
* This method ensures that the travel time in a time bin
* cannot be smaller than the travel time in the bin before minus the
* bin size.
*
*/
private void consolidateData(final TravelTimeData data){
synchronized (data) {
if (data.isNeedingConsolidation()) {
// initialize prevTravelTime with ttime from time bin 0 and time 0. (The interface comment already states that
// having both as argument does not make sense.)
double prevTravelTime = data.getTravelTime(0, 0.0);
// changed (1, 0.0) to (0, 0.0) since Michal has convinced me (by a test) that using "1" is wrong
// because you get the wrong result for time slot number 1. This change does not affect the existing
// unit tests. kai, oct'11
// go from time slot 1 forward in time:
for (int i = 1; i < this.numSlots; i++) {
// once more the getter is weird since it needs both the time slot and the time:
double travelTime = data.getTravelTime(i, i * this.timeSlice);
// if the travel time in the previous time slice was X, then now it is X-S, where S is the time slice:
double minTravelTime = prevTravelTime - this.timeSlice;
// if the travel time that has been measured so far is less than that minimum travel time, then do something:
if (travelTime < minTravelTime) {
// (set the travel time to the smallest possible travel time that makes sense according to the argument above)
travelTime = minTravelTime;
data.setTravelTime(i, travelTime);
}
prevTravelTime = travelTime;
}
data.setNeedsConsolidation(false);
}
}
} | /matsim/src/main/java/org/matsim/core/trafficmonitoring/TravelTimeCalculator.java |
robustness-copilot_data_282 | /**
* Attempts to discover classes that are assignable to the type provided. In the case
* that an interface is provided this method will collect implementations. In the case
* of a non-interface class, subclasses will be collected. Accumulated classes can be
* accessed by calling {@link #getClasses()}.
*
* @param parent
* the class of interface to find subclasses or implementations of
* @param packageNames
* one or more package names to scan (including subpackages) for classes
* @return the resolver util
*/
public ResolverUtil<T> findImplementations(Class<?> parent, String... packageNames){
if (packageNames == null) {
return this;
}
Test test = new IsA(parent);
for (String pkg : packageNames) {
find(test, pkg);
}
return this;
} | /src/main/java/org/apache/ibatis/io/ResolverUtil.java |
robustness-copilot_data_283 | /**
* Checks if one of the loaded templates is a substructure in the given
* Molecule. If so, it assigns the coordinates from the template to the
* respective atoms in the Molecule, and marks the atoms as ISPLACED.
*
* @param molecule The molecule to be check for potential templates
* @return True if there was a possible mapping
*/
public boolean mapTemplates(IAtomContainer molecule) throws CDKException{
for (Pattern anonPattern : elemPatterns) {
for (Map<IAtom, IAtom> atoms : anonPattern.matchAll(molecule).toAtomMap()) {
for (Map.Entry<IAtom, IAtom> e : atoms.entrySet()) {
e.getValue().setPoint2d(new Point2d(e.getKey().getPoint2d()));
e.getValue().setFlag(CDKConstants.ISPLACED, true);
}
if (!atoms.isEmpty())
return true;
}
}
for (Pattern anonPattern : anonPatterns) {
for (Map<IAtom, IAtom> atoms : anonPattern.matchAll(molecule).toAtomMap()) {
for (Map.Entry<IAtom, IAtom> e : atoms.entrySet()) {
e.getValue().setPoint2d(new Point2d(e.getKey().getPoint2d()));
e.getValue().setFlag(CDKConstants.ISPLACED, true);
}
if (!atoms.isEmpty())
return true;
}
}
return false;
} | /tool/sdg/src/main/java/org/openscience/cdk/layout/TemplateHandler.java |
robustness-copilot_data_284 | /**
* Check whether the node is marked as count station. If that is the case, migrate its count data to outCounts and mark it as non modifiable
* @param node The node to be checked
*/
private void checkNodeIsMarkedAsCountStation(Node node){
Link linkToBlock = null;
if (this.shortNameMap.keySet().contains(node.getId().toString())) {
// node is marked as count station
if (node.getInLinks().size() == 1 && node.getOutLinks().size() == 1) {
// ok, node has one in and one outLink, so put the count station on the shorter one and block it
// Prefer the inLink, if both have the same length
for (Link inLink : node.getInLinks().values()) {
for (Link outLink : node.getOutLinks().values()) {
if (inLink.getLength() > outLink.getLength()) {
linkToBlock = outLink;
} else {
linkToBlock = inLink;
}
break;
}
break;
}
// check, if count data is present
Id<Link> shortNameId = Id.create(this.shortNameMap.get(node.getId().toString()), Link.class);
if (this.outCounts.getCount(shortNameId) == null) {
// Count station wasn't added to outCounts, yet
Count<Link> oldCount = this.inCounts.getCount(shortNameId);
if (oldCount == null) {
// count station was mapped, but data can not be provided, do nothing
// TODO [AN] Check, if linkToBlock can be removed
} else {
// create new count with correct locId and migrate data
if (linkToBlock != null) {
this.outCounts.createAndAddCount(linkToBlock.getId(), oldCount.getCsLabel());
Count<Link> newCount = this.outCounts.getCount(linkToBlock.getId());
newCount.setCoord(oldCount.getCoord());
for (Volume volume : oldCount.getVolumes().values()) {
newCount.createVolume(volume.getHourOfDayStartingWithOne(), volume.getValue());
}
}
}
} else {
// count station was already processed and moved to outCounts
}
} else {
log.warn("Count station " + this.shortNameMap.get(node.getId().toString()) + " is registerd to node " + node.getId().toString() + " which has " + node.getInLinks().size() + " inLinks and " + node.getOutLinks().size() + " outLinks. Can only map one to one. Removing count station from counts data.");
}
}
// everything worked fine, check if a link was blocked
if (linkToBlock != null) {
this.linksBlockedByFacility.add(linkToBlock.getId().toString());
}
} | /contribs/vsp/src/main/java/playground/vsp/andreas/osmBB/PTCountsNetworkSimplifier.java |
robustness-copilot_data_285 | /**
* Tests if the electron count matches the Hückel 4n+2 rule.
*/
private static boolean isHueckelValid(IAtomContainer singleRing) throws CDKException{
int electronCount = 0;
for (IAtom ringAtom : singleRing.atoms()) {
if (ringAtom.getHybridization() != CDKConstants.UNSET && (ringAtom.getHybridization() == Hybridization.SP2) || ringAtom.getHybridization() == Hybridization.PLANAR3) {
// for example, a carbon
// note: the double bond is in the ring, that has been tested earlier
// FIXME: this does assume bond orders to be resolved too, when detecting
// sprouting double bonds
if ("N.planar3".equals(ringAtom.getAtomTypeName())) {
electronCount += 2;
} else if ("N.minus.planar3".equals(ringAtom.getAtomTypeName())) {
electronCount += 2;
} else if ("N.amide".equals(ringAtom.getAtomTypeName())) {
electronCount += 2;
} else if ("S.2".equals(ringAtom.getAtomTypeName())) {
electronCount += 2;
} else if ("S.planar3".equals(ringAtom.getAtomTypeName())) {
electronCount += 2;
} else if ("C.minus.planar".equals(ringAtom.getAtomTypeName())) {
electronCount += 2;
} else if ("O.planar3".equals(ringAtom.getAtomTypeName())) {
electronCount += 2;
} else if ("N.sp2.3".equals(ringAtom.getAtomTypeName())) {
electronCount += 1;
} else {
if (factory == null) {
factory = AtomTypeFactory.getInstance("org/openscience/cdk/dict/data/cdk-atom-types.owl", ringAtom.getBuilder());
}
IAtomType type = factory.getAtomType(ringAtom.getAtomTypeName());
Object property = type.getProperty(CDKConstants.PI_BOND_COUNT);
if (property != null && property instanceof Integer) {
electronCount += ((Integer) property).intValue();
}
}
} else if (ringAtom.getHybridization() != null && ringAtom.getHybridization() == Hybridization.SP3 && getLonePairCount(ringAtom) > 0) {
// for example, a nitrogen or oxygen
electronCount += 2;
}
}
return (electronCount % 4 == 2) && (electronCount > 2);
} | /legacy/src/main/java/org/openscience/cdk/aromaticity/DoubleBondAcceptingAromaticityDetector.java |
robustness-copilot_data_286 | /**
* Returns the largest ("top") n values in the column. Does not change the order in this column
*
* @param n The maximum number of records to return. The actual number will be smaller if n is
* greater than the number of observations in the column
* @return A list, possibly empty, of the largest observations
*/
public List<LocalTime> top(int n){
List<LocalTime> top = new ArrayList<>();
int[] values = data.toIntArray();
IntArrays.parallelQuickSort(values, IntComparators.OPPOSITE_COMPARATOR);
for (int i = 0; i < n && i < values.length; i++) {
top.add(PackedLocalTime.asLocalTime(values[i]));
}
return top;
} | /core/src/main/java/tech/tablesaw/api/TimeColumn.java |
robustness-copilot_data_287 | /**
* Check whether the cloud job is disabled or not.
*
* @param jobName job name
* @return true is disabled, otherwise not
*/
public boolean isDisabled(@Param(name = "jobName", source = ParamSource.PATH) final String jobName){
return facadeService.isJobDisabled(jobName);
} | /elasticjob-cloud/elasticjob-cloud-scheduler/src/main/java/org/apache/shardingsphere/elasticjob/cloud/console/controller/CloudJobController.java |
robustness-copilot_data_288 | /**
* Pops and pushes its ways through the InChI connection table to build up a simple molecule.
* @param inputInchi user input InChI
* @param inputMolecule user input molecule
* @param inchiAtomsByPosition
* @return molecule with single bonds and no hydrogens.
*/
private IAtomContainer connectAtoms(String inputInchi, IAtomContainer inputMolecule, Map<Integer, IAtom> inchiAtomsByPosition) throws CDKException{
String inchi = inputInchi;
inchi = inchi.substring(inchi.indexOf('/') + 1);
inchi = inchi.substring(inchi.indexOf('/') + 1);
String connections = inchi.substring(1, inchi.indexOf('/'));
Pattern connectionPattern = Pattern.compile("(-|\\(|\\)|,|([0-9])*)");
Matcher match = connectionPattern.matcher(connections);
Stack<IAtom> atomStack = new Stack<IAtom>();
IAtomContainer inchiMolGraph = inputMolecule.getBuilder().newInstance(IAtomContainer.class);
boolean pop = false;
boolean push = true;
while (match.find()) {
String group = match.group();
push = true;
if (!group.isEmpty()) {
if (group.matches("[0-9]*")) {
IAtom atom = inchiAtomsByPosition.get(Integer.valueOf(group));
if (!inchiMolGraph.contains(atom))
inchiMolGraph.addAtom(atom);
IAtom prevAtom = null;
if (atomStack.size() != 0) {
if (pop) {
prevAtom = atomStack.pop();
} else {
prevAtom = atomStack.get(atomStack.size() - 1);
}
IBond bond = inputMolecule.getBuilder().newInstance(IBond.class, prevAtom, atom, IBond.Order.SINGLE);
inchiMolGraph.addBond(bond);
}
if (push) {
atomStack.push(atom);
}
} else if (group.equals("-")) {
pop = true;
push = true;
} else if (group.equals(",")) {
atomStack.pop();
pop = false;
push = false;
} else if (group.equals("(")) {
pop = false;
push = true;
} else if (group.equals(")")) {
atomStack.pop();
pop = true;
push = true;
} else {
throw new CDKException("Unexpected token " + group + " in connection table encountered.");
}
}
}
for (IAtom at : inchiAtomsByPosition.values()) {
if (!inchiMolGraph.contains(at))
inchiMolGraph.addAtom(at);
}
return inchiMolGraph;
} | /tool/tautomer/src/main/java/org/openscience/cdk/tautomers/InChITautomerGenerator.java |
robustness-copilot_data_289 | /**
* Calculates the FMF descriptor value for the given {@link IAtomContainer}.
*
* @param container An {@link org.openscience.cdk.interfaces.IAtomContainer} for which this descriptor
* should be calculated
* @return An object of {@link org.openscience.cdk.qsar.DescriptorValue} that contains the
* calculated FMF descriptor value as well as specification details
*/
public DescriptorValue calculate(IAtomContainer container){
// don't mod original
container = clone(container);
MurckoFragmenter fragmenter = new MurckoFragmenter(true, 3);
DoubleResult result;
try {
fragmenter.generateFragments(container);
IAtomContainer[] framework = fragmenter.getFrameworksAsContainers();
IAtomContainer[] ringSystems = fragmenter.getRingSystemsAsContainers();
if (framework.length == 1) {
result = new DoubleResult(framework[0].getAtomCount() / (double) container.getAtomCount());
} else if (framework.length == 0 && ringSystems.length == 1) {
result = new DoubleResult(ringSystems[0].getAtomCount() / (double) container.getAtomCount());
} else
result = new DoubleResult(0.0);
} catch (CDKException e) {
result = new DoubleResult(Double.NaN);
}
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), result, getDescriptorNames());
} | /descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/FMFDescriptor.java |
robustness-copilot_data_290 | /**
* Create job running context from job configuration and execution type.
*
* @param cloudJobConfig cloud job configuration
* @param type execution type
* @return Job running context
*/
public static JobContext from(final CloudJobConfiguration cloudJobConfig, final ExecutionType type){
int shardingTotalCount = cloudJobConfig.getJobConfig().getShardingTotalCount();
List<Integer> shardingItems = new ArrayList<>(shardingTotalCount);
for (int i = 0; i < shardingTotalCount; i++) {
shardingItems.add(i);
}
return new JobContext(cloudJobConfig, shardingItems, type);
} | /elasticjob-cloud/elasticjob-cloud-scheduler/src/main/java/org/apache/shardingsphere/elasticjob/cloud/scheduler/context/JobContext.java |
robustness-copilot_data_291 | /**
* Utility to determine if the specified mass is the major isotope for the given atomic number.
*
* @param number atomic number
* @param mass atomic mass
* @return the mass is the major mass for the atomic number
*/
private boolean isMajorIsotope(int number, int mass){
try {
IIsotope isotope = Isotopes.getInstance().getMajorIsotope(number);
return isotope != null && isotope.getMassNumber().equals(mass);
} catch (IOException e) {
return false;
}
} | /display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/StandardAtomGenerator.java |
robustness-copilot_data_292 | /**
* Convenience method for generateChecksums(session, path, new DefaultChecksumGeneratorOptions()).
*
* @param session the session
* @param path tthe root path to generate checksums for
* @return the map of abs path ~> checksums
* @throws RepositoryException
* @throws IOException
*/
public Map<String, String> generateChecksums(Session session, String path) throws RepositoryException, IOException{
return generateChecksums(session, path, new DefaultChecksumGeneratorOptions());
} | /bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/ChecksumGeneratorImpl.java |
robustness-copilot_data_293 | /**
* Generate the next pseudorandom number for the provided <i>seed</i>.
*
* @param seed random number seed
* @return the next pseudorandom number
*/
long next(long seed){
seed = seed ^ seed << 21;
seed = seed ^ seed >>> 35;
return seed ^ seed << 4;
} | /tool/hash/src/main/java/org/openscience/cdk/hash/Xorshift.java |
robustness-copilot_data_294 | /**
* Return the variable name by removing invalid characters and proper escaping if
* it's a reserved word.
*
* @param name the variable name
* @return the sanitized variable name
*/
public String toVarName(final String name){
if (reservedWords.contains(name)) {
return escapeReservedWord(name);
} else if (name.chars().anyMatch(character -> specialCharReplacements.containsKey(String.valueOf((char) character)))) {
return escape(name, specialCharReplacements, null, null);
}
return name;
} | /modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java |
robustness-copilot_data_295 | /**
* Check a permutation to see if it is better, equal, or worse than the
* current best.
*
* @param perm the permutation to check
* @return BETTER, EQUAL, or WORSE
*/
private Result compareRowwise(Permutation perm){
int m = perm.size();
for (int i = 0; i < m - 1; i++) {
for (int j = i + 1; j < m; j++) {
int x = getConnectivity(best.get(i), best.get(j));
int y = getConnectivity(perm.get(i), perm.get(j));
if (x > y)
return Result.WORSE;
if (x < y)
return Result.BETTER;
}
}
return Result.EQUAL;
} | /tool/group/src/main/java/org/openscience/cdk/group/AbstractDiscretePartitionRefiner.java |
robustness-copilot_data_296 | /**
* Returns the "contents" field of a document based on an internal Lucene docid.
* The method is named to be consistent with Lucene's {@link IndexReader#document(int)}, contra Java's standard
* method naming conventions.
*
* @param ldocid internal Lucene docid
* @return the "contents" field the document
*/
public String documentContents(int ldocid){
try {
return reader.document(ldocid).get(IndexArgs.CONTENTS);
} catch (Exception e) {
return null;
}
} | /src/main/java/io/anserini/search/SimpleImpactSearcher.java |
robustness-copilot_data_297 | /**
* Get sandbox of the cloud job by app name.
*
* @param appName application name
* @return sandbox info
* @throws JsonParseException parse json exception
*/
public Collection<Map<String, String>> sandbox(@Param(name = "appName", source = ParamSource.QUERY) final String appName) throws JsonParseException{
Preconditions.checkArgument(!Strings.isNullOrEmpty(appName), "Lack param 'appName'");
return mesosStateService.sandbox(appName);
} | /elasticjob-cloud/elasticjob-cloud-scheduler/src/main/java/org/apache/shardingsphere/elasticjob/cloud/console/controller/CloudOperationController.java |
robustness-copilot_data_298 | /**
* Push frame plus empty frame to front of message, before 1st frame.
* Message takes ownership of frame, will destroy it when message is sent.
* @param frame
*/
public ZMsg wrap(ZFrame frame){
if (frame != null) {
push(new ZFrame(""));
push(frame);
}
return this;
} | /src/main/java/org/zeromq/ZMsg.java |
robustness-copilot_data_299 | /**
* Find out if the PortAlias 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 process 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
*/
public Optional<EntityDetail> findPortAliasEntity(String userId, String qualifiedName) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException{
return dataEngineCommonHandler.findEntity(userId, qualifiedName, PORT_ALIAS_TYPE_NAME);
} | /open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEnginePortHandler.java |
robustness-copilot_data_300 | /**
* Determines if all this {@link IAtomContainer}'s atoms contain 3D coordinates. If any atom
* is null or has unset 3D coordinates this method will return false. If the provided
* container is null false is returned.
*
* @param container the atom container to examine
*
* @return indication that all 3D coordinates are available
*
* @see org.openscience.cdk.interfaces.IAtom#getPoint3d()
*/
public static boolean has3DCoordinates(IAtomContainer container){
if (container == null || container.getAtomCount() == 0)
return Boolean.FALSE;
for (IAtom atom : container.atoms()) {
if (atom == null || atom.getPoint3d() == null)
return Boolean.FALSE;
}
return Boolean.TRUE;
} | /legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.