id stringlengths 25 27 | content stringlengths 190 15.4k | max_stars_repo_path stringlengths 31 217 |
|---|---|---|
robustness-copilot_data_401 | /**
* Create CollectionMembership relationships between a Process asset and a Collection. Verifies that the
* relationship is not present before creating it
*
* @param userId the name of the calling user
* @param processGUID the unique identifier of the process
* @param collectionGUID the unique identifier of the collection
* @param externalSourceName the unique name of the external source
*
* @throws InvalidParameterException the bean properties are invalid
* @throws UserNotAuthorizedException user not authorized to issue this request
* @throws PropertyServerException problem accessing the property server
*/
public void addCollectionMembershipRelationship(String userId, String processGUID, String collectionGUID, String externalSourceName) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException{
dataEngineCommonHandler.upsertExternalRelationship(userId, processGUID, collectionGUID, REFERENCEABLE_TO_COLLECTION_TYPE_NAME, COLLECTION_TYPE_NAME, externalSourceName, null);
} | /open-metadata-implementation/access-services/data-engine/data-engine-server/src/main/java/org/odpi/openmetadata/accessservices/dataengine/server/handlers/DataEngineCollectionHandler.java |
robustness-copilot_data_402 | /**
* Helper method for finding wrapper type for given primitive type (why isn't
* there one in JDK?).
* NOTE: throws {@link IllegalArgumentException} if given type is NOT primitive
* type (caller has to check).
*/
public static Class<?> wrapperType(Class<?> primitiveType){
if (primitiveType == Integer.TYPE) {
return Integer.class;
}
if (primitiveType == Long.TYPE) {
return Long.class;
}
if (primitiveType == Boolean.TYPE) {
return Boolean.class;
}
if (primitiveType == Double.TYPE) {
return Double.class;
}
if (primitiveType == Float.TYPE) {
return Float.class;
}
if (primitiveType == Byte.TYPE) {
return Byte.class;
}
if (primitiveType == Short.TYPE) {
return Short.class;
}
if (primitiveType == Character.TYPE) {
return Character.class;
}
throw new IllegalArgumentException("Class " + primitiveType.getName() + " is not a primitive type");
} | /src/main/java/com/fasterxml/jackson/databind/util/ClassUtil.java |
robustness-copilot_data_403 | /**
* Checks if the agent has a valid dispatcher headers.
*
* @param agent Agent to check
* @return true if the Agent's headers contain the proper values
*/
private boolean isDispatcherHeaders(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.startsWith(header, CQ_ACTION_HEADER)) {
return true;
}
}
return false;
} | /bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/DispatcherFlushFilter.java |
robustness-copilot_data_404 | /**
* Checks if the find possible distance is the minimal one.
*
* @param minimalAdditionalDistance
* @param possibleAdditionalDistance
* @return the minimal transport distance
*/
private double findMinimalDistance(double minimalAdditionalDistance, double possibleAdditionalDistance){
if (minimalAdditionalDistance == 0)
minimalAdditionalDistance = possibleAdditionalDistance;
else if (possibleAdditionalDistance < minimalAdditionalDistance)
minimalAdditionalDistance = possibleAdditionalDistance;
return minimalAdditionalDistance;
} | /contribs/freight/src/main/java/org/matsim/contrib/freight/jsprit/DistanceConstraint.java |
robustness-copilot_data_405 | /**
* Returns a one line string representation of this Container. This method is
* conform RFC #9.
*
* @return The string representation of this Container
*/
public String toString(){
StringBuffer resultString = new StringBuffer(32);
resultString.append("Bond(").append(this.hashCode());
if (getOrder() != null) {
resultString.append(", #O:").append(getOrder());
}
resultString.append(", #S:").append(getStereo());
if (getAtomCount() > 0) {
resultString.append(", #A:").append(getAtomCount());
for (int i = 0; i < atomCount; i++) {
resultString.append(", ").append(atoms[i] == null ? "null" : atoms[i].toString());
}
}
resultString.append(", ").append(super.toString());
resultString.append(')');
return resultString.toString();
} | /base/silent/src/main/java/org/openscience/cdk/silent/Bond.java |
robustness-copilot_data_406 | /**
* Utility for find the first directional edge incident to a vertex. If
* there are no directional labels then null is returned.
*
* @param g graph from Beam
* @param u the vertex for which to find
* @return first directional edge (or null if none)
*/
private Edge findDirectionalEdge(Graph g, int u){
List<Edge> edges = g.edges(u);
if (edges.size() == 1)
return null;
Edge first = null;
for (Edge e : edges) {
Bond b = e.bond();
if (b == Bond.UP || b == Bond.DOWN) {
if (first == null)
first = e;
else if (((first.either() == e.either()) == (first.bond() == b)))
return null;
}
}
return first;
} | /storage/smiles/src/main/java/org/openscience/cdk/smiles/BeamToCDK.java |
robustness-copilot_data_407 | /**
* Returns true if the specified YAML string matches this configuration, ignoring unknown fields
* and field ordering. Note that ordering of elements in arrays is considered significant for this comparison.
* @param yaml a monitoring exporter configuration to compare to this object.
*/
public boolean matchesYaml(String yaml){
final String thisJson = toJson();
final String otherJson = createFromYaml(yaml).toJson();
return JsonParser.parseString(thisJson).equals(JsonParser.parseString(otherJson));
} | /operator/src/main/java/oracle/kubernetes/weblogic/domain/model/MonitoringExporterConfiguration.java |
robustness-copilot_data_408 | /** Returns the natural log of the values in this column as a NumberColumn. */
DoubleColumn logN(){
DoubleColumn newColumn = DoubleColumn.create(name() + "[logN]", size());
for (int i = 0; i < size(); i++) {
newColumn.set(i, Math.log(getDouble(i)));
}
return newColumn;
} | /core/src/main/java/tech/tablesaw/columns/numbers/NumberMapFunctions.java |
robustness-copilot_data_409 | /**
* Returns a StringColumn with the year and day-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 yearDay(){
StringColumn newColumn = StringColumn.create(this.name() + " year & month");
for (int r = 0; r < this.size(); r++) {
long c1 = this.getLongInternal(r);
if (DateTimeColumn.valueIsMissing(c1)) {
newColumn.append(StringColumnType.missingValueIndicator());
} else {
String ym = String.valueOf(getYear(c1));
ym = ym + "-" + Strings.padStart(String.valueOf(getDayOfYear(c1)), 3, '0');
newColumn.append(ym);
}
}
return newColumn;
} | /core/src/main/java/tech/tablesaw/columns/datetimes/DateTimeMapFunctions.java |
robustness-copilot_data_410 | /**
* The method returns partial charges assigned to an heavy atom and its protons through Gasteiger Marsili
* It is needed to call the addExplicitHydrogensToSatisfyValency method from the class tools.HydrogenAdder.
*
*@param atom The IAtom for which the DescriptorValue is requested
*@param ac AtomContainer
*@return an array of doubles with partial charges of [heavy, proton_1 ... proton_n]
*/
public DescriptorValue calculate(IAtom atom, IAtomContainer ac){
neighboors = ac.getConnectedAtomsList(atom);
IAtomContainer clone;
try {
clone = (IAtomContainer) ac.clone();
} catch (CloneNotSupportedException e) {
return getDummyDescriptorValue(e);
}
try {
peoe = new GasteigerMarsiliPartialCharges();
peoe.setMaxGasteigerIters(6);
peoe.assignGasteigerMarsiliSigmaPartialCharges(clone, true);
} catch (Exception exception) {
return getDummyDescriptorValue(exception);
}
IAtom localAtom = clone.getAtom(ac.indexOf(atom));
neighboors = clone.getConnectedAtomsList(localAtom);
DoubleArrayResult protonPartialCharge = new DoubleArrayResult(MAX_PROTON_COUNT);
assert (neighboors.size() < MAX_PROTON_COUNT);
protonPartialCharge.add(localAtom.getCharge());
int hydrogenNeighbors = 0;
for (IAtom neighboor : neighboors) {
if (neighboor.getAtomicNumber() == IElement.H) {
hydrogenNeighbors++;
protonPartialCharge.add(neighboor.getCharge());
}
}
int remainder = MAX_PROTON_COUNT - (hydrogenNeighbors + 1);
for (int i = 0; i < remainder; i++) protonPartialCharge.add(Double.NaN);
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), protonPartialCharge, getDescriptorNames());
} | /descriptor/qsaratomic/src/main/java/org/openscience/cdk/qsar/descriptors/atomic/ProtonTotalPartialChargeDescriptor.java |
robustness-copilot_data_411 | /**
* CTfile specification is ambiguous as to how parity values should be written
* for implicit hydrogens. Old applications (Symyx Draw) seem to push any
* hydrogen to (implied) the last position but newer applications
* (Accelrys/BioVia Draw) only do so for implicit hydrogens (makes more sense).
*
* To avoid the ambiguity for those who read 0D stereo (bad anyways) we
* actually do push all hydrogens atoms to the back of the atom list giving
* them highest value (4) when writing parity values.
*
* @param mol molecule
* @param atomToIdx mapping that will be filled with the output index
* @return the output order of atoms
*/
private IAtom[] pushHydrogensToBack(IAtomContainer mol, Map<IChemObject, Integer> atomToIdx){
assert atomToIdx.isEmpty();
IAtom[] atoms = new IAtom[mol.getAtomCount()];
for (IAtom atom : mol.atoms()) {
if (atom.getAtomicNumber() == 1)
continue;
atoms[atomToIdx.size()] = atom;
atomToIdx.put(atom, atomToIdx.size() + 1);
}
for (IAtom atom : mol.atoms()) {
if (atom.getAtomicNumber() != 1)
continue;
atoms[atomToIdx.size()] = atom;
atomToIdx.put(atom, atomToIdx.size() + 1);
}
return atoms;
} | /storage/ctab/src/main/java/org/openscience/cdk/io/MDLV3000Writer.java |
robustness-copilot_data_412 | /**
* Factory method for constructing a simple transformer based on
* prefix and/or suffix.
*/
public static NameTransformer simpleTransformer(final String prefix, final String suffix){
boolean hasPrefix = (prefix != null) && !prefix.isEmpty();
boolean hasSuffix = (suffix != null) && !suffix.isEmpty();
if (hasPrefix) {
if (hasSuffix) {
return new NameTransformer() {
@Override
public String transform(String name) {
return prefix + name + suffix;
}
@Override
public String reverse(String transformed) {
if (transformed.startsWith(prefix)) {
String str = transformed.substring(prefix.length());
if (str.endsWith(suffix)) {
return str.substring(0, str.length() - suffix.length());
}
}
return null;
}
@Override
public String toString() {
return "[PreAndSuffixTransformer('" + prefix + "','" + suffix + "')]";
}
};
}
return new NameTransformer() {
@Override
public String transform(String name) {
return prefix + name;
}
@Override
public String reverse(String transformed) {
if (transformed.startsWith(prefix)) {
return transformed.substring(prefix.length());
}
return null;
}
@Override
public String toString() {
return "[PrefixTransformer('" + prefix + "')]";
}
};
}
if (hasSuffix) {
return new NameTransformer() {
@Override
public String transform(String name) {
return name + suffix;
}
@Override
public String reverse(String transformed) {
if (transformed.endsWith(suffix)) {
return transformed.substring(0, transformed.length() - suffix.length());
}
return null;
}
@Override
public String toString() {
return "[SuffixTransformer('" + suffix + "')]";
}
};
}
return NOP;
} | /src/main/java/com/fasterxml/jackson/databind/util/NameTransformer.java |
robustness-copilot_data_413 | /**
* Converts a number like 1634 to the time value of 16:34:00.
*
* @param hhmm the time-representing number to convert.
* @return the time as seconds after midnight.
*/
public static double convertHHMMInteger(int hhmm){
int h = hhmm / 100;
int m = hhmm - (h * 100);
double seconds = Math.abs(h) * 3600 + m * 60;
return seconds;
} | /matsim/src/main/java/org/matsim/core/utils/misc/Time.java |
robustness-copilot_data_414 | /**
* Get bond order value as {@code int} value.
*
* @param bond The {@link IBond} for which the order is returned.
* @return 1 for a single bond, 2 for a double bond, 3 for a triple bond, 4 for a quadruple bond,
* and 0 for any other bond type.
*/
public static int convertBondOrder(IBond bond){
int value = 0;
switch(bond.getOrder()) {
case QUADRUPLE:
value = 4;
break;
case TRIPLE:
value = 3;
break;
case DOUBLE:
value = 2;
break;
case SINGLE:
value = 1;
break;
default:
value = 0;
}
return value;
} | /legacy/src/main/java/org/openscience/cdk/smsd/filters/ChemicalFilters.java |
robustness-copilot_data_415 | /**
* Read topics of TREC Microblog Tracks from 2011 to 2014 including:
* topics.microblog2011.txt
* topics.microblog2012.txt
* topics.microblog2013.txt
* topics.microblog2014.txt
* @return SortedMap where keys are query/topic IDs and values are title portions of the topics
* @throws IOException any io exception
*/
public SortedMap<Integer, Map<String, String>> read(BufferedReader bRdr) throws IOException{
SortedMap<Integer, Map<String, String>> map = new TreeMap<>();
Map<String, String> fields = new HashMap<>();
String number = "";
Matcher m;
String line;
while ((line = bRdr.readLine()) != null) {
line = line.trim();
if (line.startsWith("<num>") && line.endsWith("</num>")) {
m = NUM_PATTERN.matcher(line);
if (!m.find()) {
throw new IOException("Error parsing " + line);
}
number = m.group(1);
}
if (line.startsWith("<query>") && line.endsWith("</query>") || line.startsWith("<title>") && line.endsWith("</title>")) {
m = TITLE_PATTERN.matcher(line);
if (!m.find()) {
m = TITLE_PATTERN2.matcher(line);
if (!m.find()) {
throw new IOException("Error parsing " + line);
}
}
fields.put("title", m.group(1));
}
if (line.startsWith("<querytweettime>") && line.endsWith("</querytweettime>")) {
m = TWEETTIME_PATTERN.matcher(line);
if (!m.find()) {
throw new IOException("Error parsing " + line);
}
fields.put("time", m.group(1));
}
if (line.startsWith("</top>")) {
map.put(Integer.valueOf(number), fields);
fields = new HashMap<>();
}
}
return map;
} | /src/main/java/io/anserini/search/topicreader/MicroblogTopicReader.java |
robustness-copilot_data_416 | /**
* Copies the content from one stream to another stream.
*
* @param fromStream The stream containing the data to be copied
* @param toStream The stream the data should be written to
*
* @throws UncheckedIOException
*/
public static void copyStream(final InputStream fromStream, final OutputStream toStream) throws UncheckedIOException{
try {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fromStream.read(buffer)) != -1) {
toStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
} | /matsim/src/main/java/org/matsim/core/utils/io/IOUtils.java |
robustness-copilot_data_417 | /**
* Appends a placeholder indicating that some frames were not written.
*/
private void appendPlaceHolder(StringBuilder builder, int indent, int consecutiveExcluded, String message){
indent(builder, indent);
builder.append(ELLIPSIS).append(" ").append(consecutiveExcluded).append(" ").append(message).append(CoreConstants.LINE_SEPARATOR);
} | /src/main/java/net/logstash/logback/stacktrace/ShortenedThrowableConverter.java |
robustness-copilot_data_418 | /**
* Adds all the commonly used config-groups, also known as "core modules",
* to this config-instance. This should be called before reading any
* configuration from file.
*/
public void addCoreModules(){
this.global = new GlobalConfigGroup();
this.modules.put(GlobalConfigGroup.GROUP_NAME, this.global);
this.controler = new ControlerConfigGroup();
this.modules.put(ControlerConfigGroup.GROUP_NAME, this.controler);
this.qSimConfigGroup = new QSimConfigGroup();
this.modules.put(QSimConfigGroup.GROUP_NAME, this.qSimConfigGroup);
this.counts = new CountsConfigGroup();
this.modules.put(CountsConfigGroup.GROUP_NAME, this.counts);
this.charyparNagelScoring = new PlanCalcScoreConfigGroup();
this.modules.put(PlanCalcScoreConfigGroup.GROUP_NAME, this.charyparNagelScoring);
this.network = new NetworkConfigGroup();
this.modules.put(NetworkConfigGroup.GROUP_NAME, this.network);
this.plans = new PlansConfigGroup();
this.modules.put(PlansConfigGroup.GROUP_NAME, this.plans);
this.households = new HouseholdsConfigGroup();
this.modules.put(HouseholdsConfigGroup.GROUP_NAME, this.households);
this.parallelEventHandling = new ParallelEventHandlingConfigGroup();
this.modules.put(ParallelEventHandlingConfigGroup.GROUP_NAME, this.parallelEventHandling);
this.facilities = new FacilitiesConfigGroup();
this.modules.put(FacilitiesConfigGroup.GROUP_NAME, this.facilities);
this.strategy = new StrategyConfigGroup();
this.modules.put(StrategyConfigGroup.GROUP_NAME, this.strategy);
this.travelTimeCalculatorConfigGroup = new TravelTimeCalculatorConfigGroup();
this.modules.put(TravelTimeCalculatorConfigGroup.GROUPNAME, this.travelTimeCalculatorConfigGroup);
this.scenarioConfigGroup = new ScenarioConfigGroup();
this.modules.put(ScenarioConfigGroup.GROUP_NAME, this.scenarioConfigGroup);
this.plansCalcRoute = new PlansCalcRouteConfigGroup();
this.modules.put(PlansCalcRouteConfigGroup.GROUP_NAME, this.plansCalcRoute);
this.timeAllocationMutator = new TimeAllocationMutatorConfigGroup();
this.modules.put(TimeAllocationMutatorConfigGroup.GROUP_NAME, this.timeAllocationMutator);
this.vspExperimentalGroup = new VspExperimentalConfigGroup();
this.modules.put(VspExperimentalConfigGroup.GROUP_NAME, this.vspExperimentalGroup);
this.ptCounts = new PtCountsConfigGroup();
this.modules.put(PtCountsConfigGroup.GROUP_NAME, this.ptCounts);
this.transit = new TransitConfigGroup();
this.modules.put(TransitConfigGroup.GROUP_NAME, this.transit);
this.linkStats = new LinkStatsConfigGroup();
this.modules.put(LinkStatsConfigGroup.GROUP_NAME, this.linkStats);
this.transitRouter = new TransitRouterConfigGroup();
this.modules.put(TransitRouterConfigGroup.GROUP_NAME, this.transitRouter);
this.subtourModeChoice = new SubtourModeChoiceConfigGroup();
this.modules.put(SubtourModeChoiceConfigGroup.GROUP_NAME, this.subtourModeChoice);
this.vehicles = new VehiclesConfigGroup();
this.modules.put(VehiclesConfigGroup.GROUP_NAME, this.vehicles);
this.changeMode = new ChangeModeConfigGroup();
this.modules.put(ChangeModeConfigGroup.CONFIG_MODULE, this.changeMode);
this.modules.put(ChangeLegModeConfigGroup.CONFIG_MODULE, new ChangeLegModeConfigGroup());
// only to provide error messages. kai, may'16
this.jdeqSim = new JDEQSimConfigGroup();
this.modules.put(JDEQSimConfigGroup.NAME, this.jdeqSim);
this.hermes = new HermesConfigGroup();
this.modules.put(HermesConfigGroup.NAME, this.hermes);
this.addConfigConsistencyChecker(new VspConfigConsistencyCheckerImpl());
this.addConfigConsistencyChecker(new UnmaterializedConfigGroupChecker());
this.addConfigConsistencyChecker(new BeanValidationConfigConsistencyChecker());
} | /matsim/src/main/java/org/matsim/core/config/Config.java |
robustness-copilot_data_419 | /**
* Create an encoder for the {@link IDoubleBondStereochemistry} element.
*
* @param dbs stereo element from an atom container
* @param atomToIndex map of atoms to indices
* @param graph adjacency list of connected vertices
* @return a new geometry encoder
*/
private static GeometryEncoder encoder(IDoubleBondStereochemistry dbs, Map<IAtom, Integer> atomToIndex, int[][] graph){
IBond db = dbs.getStereoBond();
int u = atomToIndex.get(db.getBegin());
int v = atomToIndex.get(db.getEnd());
IBond[] bs = dbs.getBonds();
int[] us = new int[2];
int[] vs = new int[2];
us[0] = atomToIndex.get(bs[0].getOther(db.getBegin()));
us[1] = graph[u].length == 2 ? u : findOther(graph[u], v, us[0]);
vs[0] = atomToIndex.get(bs[1].getOther(db.getEnd()));
vs[1] = graph[v].length == 2 ? v : findOther(graph[v], u, vs[0]);
int parity = dbs.getStereo() == OPPOSITE ? +1 : -1;
GeometricParity geomParity = GeometricParity.valueOf(parity);
PermutationParity permParity = new CombinedPermutationParity(us[1] == u ? BasicPermutationParity.IDENTITY : new BasicPermutationParity(us), vs[1] == v ? BasicPermutationParity.IDENTITY : new BasicPermutationParity(vs));
return new GeometryEncoder(new int[] { u, v }, permParity, geomParity);
} | /tool/hash/src/main/java/org/openscience/cdk/hash/stereo/DoubleBondElementEncoderFactory.java |
robustness-copilot_data_420 | /**
* Given vectors for the hypotenuse and adjacent side of a right angled
* triangle and the length of the opposite side, determine how long the
* adjacent side size.
*
* @param hypotenuse vector for the hypotenuse
* @param adjacent vector for the adjacent side
* @param oppositeLength length of the opposite side of a triangle
* @return length of the adjacent side
*/
static double adjacentLength(Vector2d hypotenuse, Vector2d adjacent, double oppositeLength){
return Math.tan(hypotenuse.angle(adjacent)) * oppositeLength;
} | /display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/VecmathUtil.java |
robustness-copilot_data_421 | /**
* Validate that we can connect to the new SSL certificate posted on api.twilio.com.
*
* @throws CertificateValidationException if the connection fails
*/
public static void validateSslCertificate(){
final NetworkHttpClient client = new NetworkHttpClient();
final Request request = new Request(HttpMethod.GET, "https://api.twilio.com:8443");
try {
final Response response = client.makeRequest(request);
if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) {
throw new CertificateValidationException("Unexpected response from certificate endpoint", request, response);
}
} catch (final ApiException e) {
throw new CertificateValidationException("Could not get response from certificate endpoint", request);
}
} | /src/main/java/com/twilio/Twilio.java |
robustness-copilot_data_422 | /**
* Open a property file that is embedded as a Java resource and parse it.
*
* @param potentialPropertyFile location and file name of the property file
* @throws IOException if the file cannot be opened
* @throws CommandLineParsingException if an error occurs during parsing
*/
private void parseDefaultPropertyFileFromResource(File potentialPropertyFile) throws IOException, CommandLineParsingException{
try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(potentialPropertyFile.getAbsolutePath())) {
if (resourceAsStream != null) {
parsePropertiesFile(resourceAsStream);
}
}
} | /liquibase-core/src/main/java/liquibase/integration/commandline/Main.java |
robustness-copilot_data_423 | /**
* Invoke the specified visitor function for every schema that matches mimeType in the OpenAPI document.
*
* To avoid infinite recursion, referenced schemas are visited only once. When a referenced schema is visited,
* it is added to visitedSchemas.
*
* @param openAPI the OpenAPI document that contains schema objects.
* @param schema the root schema object to be visited.
* @param mimeType the mime type. TODO: does not seem to be used in a meaningful way.
* @param visitedSchemas the list of referenced schemas that have been visited.
* @param visitor the visitor function which is invoked for every visited schema.
*/
private static void visitSchema(OpenAPI openAPI, Schema schema, String mimeType, List<String> visitedSchemas, OpenAPISchemaVisitor visitor){
visitor.visit(schema, mimeType);
if (schema.get$ref() != null) {
String ref = getSimpleRef(schema.get$ref());
if (!visitedSchemas.contains(ref)) {
visitedSchemas.add(ref);
Schema referencedSchema = getSchemas(openAPI).get(ref);
if (referencedSchema != null) {
visitSchema(openAPI, referencedSchema, mimeType, visitedSchemas, visitor);
}
}
}
if (schema instanceof ComposedSchema) {
List<Schema> oneOf = ((ComposedSchema) schema).getOneOf();
if (oneOf != null) {
for (Schema s : oneOf) {
visitSchema(openAPI, s, mimeType, visitedSchemas, visitor);
}
}
List<Schema> allOf = ((ComposedSchema) schema).getAllOf();
if (allOf != null) {
for (Schema s : allOf) {
visitSchema(openAPI, s, mimeType, visitedSchemas, visitor);
}
}
List<Schema> anyOf = ((ComposedSchema) schema).getAnyOf();
if (anyOf != null) {
for (Schema s : anyOf) {
visitSchema(openAPI, s, mimeType, visitedSchemas, visitor);
}
}
} else if (schema instanceof ArraySchema) {
Schema itemsSchema = ((ArraySchema) schema).getItems();
if (itemsSchema != null) {
visitSchema(openAPI, itemsSchema, mimeType, visitedSchemas, visitor);
}
} else if (isMapSchema(schema)) {
Object additionalProperties = schema.getAdditionalProperties();
if (additionalProperties instanceof Schema) {
visitSchema(openAPI, (Schema) additionalProperties, mimeType, visitedSchemas, visitor);
}
}
if (schema.getNot() != null) {
visitSchema(openAPI, schema.getNot(), mimeType, visitedSchemas, visitor);
}
Map<String, Schema> properties = schema.getProperties();
if (properties != null) {
for (Schema property : properties.values()) {
visitSchema(openAPI, property, mimeType, visitedSchemas, visitor);
}
}
} | /modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java |
robustness-copilot_data_424 | /**
* Returns a table with n by m + 1 cells. The first column contains labels, the other cells
* contains the counts for every unique combination of values from the two specified columns in
* this table.
*/
public Table xTabCounts(String column1Name, String column2Name){
return CrossTab.counts(this, categoricalColumn(column1Name), categoricalColumn(column2Name));
} | /core/src/main/java/tech/tablesaw/api/Table.java |
robustness-copilot_data_425 | /**
* Convert a CDK {@link IBond} to the Beam edge label type.
*
* @param b cdk bond
* @return the edge label for the Beam edge
* @throws NullPointerException the bond order was null and the bond was
* not-aromatic
* @throws IllegalArgumentException the bond order could not be converted
*/
private static Bond toBeamEdgeLabel(IBond b, int flavour) throws CDKException{
if (SmiFlavor.isSet(flavour, SmiFlavor.UseAromaticSymbols) && b.isAromatic()) {
if (!b.getBegin().isAromatic() || !b.getEnd().isAromatic())
throw new IllegalStateException("Aromatic bond connects non-aromatic atomic atoms");
return Bond.AROMATIC;
}
if (b.getOrder() == null)
throw new CDKException("A bond had undefined order, possible query bond?");
IBond.Order order = b.getOrder();
switch(order) {
case SINGLE:
return Bond.SINGLE;
case DOUBLE:
return Bond.DOUBLE;
case TRIPLE:
return Bond.TRIPLE;
case QUADRUPLE:
return Bond.QUADRUPLE;
default:
if (!SmiFlavor.isSet(flavour, SmiFlavor.UseAromaticSymbols) && b.isAromatic())
throw new CDKException("Cannot write Kekulé SMILES output due to aromatic bond with unset bond order - molecule should be Kekulized");
throw new CDKException("Unsupported bond order: " + order);
}
} | /storage/smiles/src/main/java/org/openscience/cdk/smiles/CDKToBeam.java |
robustness-copilot_data_426 | /**
* Create a new CDK {@link IAtom} from the Beam Atom.
*
* @param beamAtom an Atom from the Beam ChemicalGraph
* @param hCount hydrogen count for the atom
* @return the CDK atom to have it's properties set
*/
IAtom toCDKAtom(Atom beamAtom, int hCount){
IAtom cdkAtom = newCDKAtom(beamAtom);
cdkAtom.setImplicitHydrogenCount(hCount);
cdkAtom.setFormalCharge(beamAtom.charge());
if (beamAtom.isotope() >= 0)
cdkAtom.setMassNumber(beamAtom.isotope());
if (beamAtom.aromatic())
cdkAtom.setIsAromatic(true);
if (beamAtom.atomClass() > 0)
cdkAtom.setProperty(ATOM_ATOM_MAPPING, beamAtom.atomClass());
return cdkAtom;
} | /storage/smiles/src/main/java/org/openscience/cdk/smiles/BeamToCDK.java |
robustness-copilot_data_427 | /**
* Create an index of atoms for the provided {@code container}.
*
* @param container the container to index the atoms of
* @return the index/lookup of atoms to the index they appear
*/
private static Map<IAtom, Integer> indexAtoms(IAtomContainer container){
Map<IAtom, Integer> map = new HashMap<>(2 * container.getAtomCount());
for (int i = 0; i < container.getAtomCount(); i++) map.put(container.getAtom(i), i);
return map;
} | /base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/StereoMatch.java |
robustness-copilot_data_428 | /**
* Calculates the Fsp<sup>3</sup> descriptor value for the given {@link IAtomContainer}.
*
* @param mol 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 Fsp<sup>3</sup> descriptor value
*/
public DescriptorValue calculate(IAtomContainer mol){
DoubleResult result;
try {
int nC = 0;
int nCSP3 = 0;
CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.getInstance(mol.getBuilder());
for (IAtom atom : mol.atoms()) {
if (atom.getAtomicNumber() == 6) {
nC++;
IAtomType matched = matcher.findMatchingAtomType(mol, atom);
if (matched != null && matched.getHybridization() == IAtomType.Hybridization.SP3) {
nCSP3++;
}
}
}
result = new DoubleResult(nC == 0 ? 0 : (double) nCSP3 / nC);
} 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/FractionalCSP3Descriptor.java |
robustness-copilot_data_429 | /**
* Update the resource with the properties from the row.
*
* @param resource Resource object of which the properties are to be modified.
* @param nodeInfo Map of properties from the row.
*/
private void populateMetadataFromRow(Resource resource, Map<String, Object> nodeInfo) throws RepositoryException{
LOG.debug("Start of populateMetadataFromRow");
ModifiableValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class);
Node node = resource.adaptTo(Node.class);
for (Map.Entry entry : nodeInfo.entrySet()) {
String key = (String) entry.getKey();
Object value = entry.getValue();
if (key != null && (mergeMode.overwriteProps || !resourceProperties.containsKey(key))) {
if (node.hasProperty(key) && node.getProperty(key).isMultiple() && mergeMode.appendArrays) {
appendArray(resourceProperties, entry);
} else if (value != null) {
resourceProperties.put(key, value);
}
}
}
LOG.debug("End of populateMetadataFromRow");
} | /bundle/src/main/java/com/adobe/acs/commons/mcp/impl/processes/DataImporter.java |
robustness-copilot_data_430 | /**
* Parses the list of character rules as defined in the database. Recall how
* configString is formatted: "UpperCase:1,LowerCase:1,Digit:1,Special:1"
*/
public static List<CharacterRule> parseConfigString(String configString){
List<CharacterRule> characterRules = new ArrayList<>();
String[] typePlusNums = configString.split(",");
for (String typePlusNum : typePlusNums) {
String[] configArray = typePlusNum.split(":");
String type = configArray[0];
String num = configArray[1];
EnglishCharacterData typeData = EnglishCharacterData.valueOf(type);
characterRules.add(new CharacterRule(typeData, new Integer(num)));
}
return characterRules;
} | /src/main/java/edu/harvard/iq/dataverse/validation/PasswordValidatorUtil.java |
robustness-copilot_data_431 | /**
* Create a pattern for the provided SMARTS - if the SMARTS is '?' a pattern
* is not created.
*
* @param smarts a smarts pattern
* @param builder chem object builder
* @return the pattern to match
*/
private Pattern createPattern(String smarts, IChemObjectBuilder builder) throws IOException{
SmartsPattern ptrn = SmartsPattern.create(smarts, builder);
ptrn.setPrepare(false);
return ptrn;
} | /descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/MACCSFingerprinter.java |
robustness-copilot_data_432 | /**
* Since durations were added later there is need to fill missing data for those statuses.
*/
private void fillMissingDurations(){
long[] extendedArray = new long[buildNumbers.length];
Arrays.fill(extendedArray, -1);
System.arraycopy(durations, 0, extendedArray, buildNumbers.length - durations.length, durations.length);
durations = extendedArray;
} | /src/main/java/net/masterthought/cucumber/Trends.java |
robustness-copilot_data_433 | /**
* Generate valid days of the month for the days of week expression. This method requires that you
* pass it a -1 for the reference value when starting to generate a sequence of day values. That allows
* it to handle the special case of which day of the month is the initial matching value.
*
* @param on The expression object giving us the particular day of week we need.
* @param year The year for the calculation.
* @param month The month for the calculation.
* @param reference This value must either be -1 indicating you are starting the sequence generation or an actual
* day of month that meets the day of week criteria. So a value previously returned by this method.
* @return
*/
private int generateNoneValues(final On on, final int year, final int month, final int reference){
// the day of week the first of the month is on
// 1-7
final int dowForFirstDoM = LocalDate.of(year, month, 1).getDayOfWeek().getValue();
// the day of week we need, normalize to jdk8time
final int requiredDoW = ConstantsMapper.weekDayMapping(mondayDoWValue, ConstantsMapper.JAVA8, on.getTime().getValue());
// the first day of the month
// day 1 from given month
int baseDay = 1;
// the difference between the days of week
final int diff = dowForFirstDoM - requiredDoW;
// //base day remains the same if diff is zero
if (diff < 0) {
baseDay = baseDay + Math.abs(diff);
}
if (diff > 0) {
baseDay = baseDay + 7 - diff;
}
// if baseDay is greater than the reference, we are returning the initial matching day value
// Fix issue #92
if (reference < 1) {
return baseDay;
}
while (baseDay <= reference) {
baseDay += 7;
}
return baseDay;
} | /src/main/java/com/cronutils/model/time/generator/OnDayOfWeekValueGenerator.java |
robustness-copilot_data_434 | /**
* Add data from a given CodegenModel that the oneOf implementor should implement. For example:
*
* @param cm model that the implementor should implement
* @param modelsImports imports of the given `cm`
*/
public void addFromInterfaceModel(CodegenModel cm, List<Map<String, String>> modelsImports){
// Add cm as implemented interface
additionalInterfaces.add(cm.classname);
// Add all vars defined on cm
// a "oneOf" model (cm) by default inherits all properties from its "interfaceModels",
// but we only want to add properties defined on cm itself
List<CodegenProperty> toAdd = new ArrayList<CodegenProperty>(cm.vars);
// note that we can't just toAdd.removeAll(m.vars) for every interfaceModel,
// as they might have different value of `hasMore` and thus are not equal
List<String> omitAdding = new ArrayList<String>();
if (cm.interfaceModels != null) {
for (CodegenModel m : cm.interfaceModels) {
for (CodegenProperty v : m.vars) {
omitAdding.add(v.baseName);
}
}
}
for (CodegenProperty v : toAdd) {
if (!omitAdding.contains(v.baseName)) {
additionalProps.add(v.clone());
}
}
// Add all imports of cm
for (Map<String, String> importMap : modelsImports) {
// we're ok with shallow clone here, because imports are strings only
additionalImports.add(new HashMap<String, String>(importMap));
}
} | /modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/OneOfImplementorAdditionalData.java |
robustness-copilot_data_435 | /**
* Given a bond length for a model, calculate the scale that will transform
* this length to the on screen bond length in RendererModel.
*
* @param modelBondLength the average bond length of the model
* @return the scale necessary to transform this to a screen bond
*/
public double calculateScaleForBondLength(double modelBondLength){
if (Double.isNaN(modelBondLength) || modelBondLength == 0) {
return DEFAULT_SCALE;
} else {
return rendererModel.getParameter(BondLength.class).getValue() / modelBondLength;
}
} | /display/renderbasic/src/main/java/org/openscience/cdk/renderer/AtomContainerRenderer.java |
robustness-copilot_data_436 | /**
* Method that subclasses may call for standard handling of an exception thrown when
* calling constructor or factory method. Will unwrap {@link ExceptionInInitializerError}
* and {@link InvocationTargetException}s, then call {@link #wrapAsJsonMappingException}.
*
* @since 2.7
*/
protected JsonMappingException rewrapCtorProblem(DeserializationContext ctxt, Throwable t){
if ((t instanceof ExceptionInInitializerError) || (t instanceof InvocationTargetException)) {
Throwable cause = t.getCause();
if (cause != null) {
t = cause;
}
}
return wrapAsJsonMappingException(ctxt, t);
} | /src/main/java/com/fasterxml/jackson/databind/deser/std/StdValueInstantiator.java |
robustness-copilot_data_437 | /**
* Find out if the SchemaType 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 schema type 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> findSchemaTypeEntity(String userId, String qualifiedName) throws UserNotAuthorizedException, PropertyServerException, InvalidParameterException{
return dataEngineCommonHandler.findEntity(userId, qualifiedName, SCHEMA_TYPE_TYPE_NAME);
} | /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_438 | /**
* Sum the components of two vectors, the input is not modified.
*
* @param a first vector
* @param b second vector
* @return scaled vector
*/
static Vector2d sum(final Tuple2d a, final Tuple2d b){
return new Vector2d(a.x + b.x, a.y + b.y);
} | /display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/VecmathUtil.java |
robustness-copilot_data_439 | /**
* Will not commit the response, but only make sure that the wrapped response's {@code flushBuffer()} is executed, once this {@link #close()} is called.
* This only affects output which is buffered, i.e. for unbuffered output the flush is not deferred.
* @throws IOException
*/
public void flushBuffer() throws IOException{
if (isBuffered()) {
log.debug("Prevent committing the response, it will be committed deferred, i.e. once this buffered response is closed");
if (log.isDebugEnabled()) {
Throwable t = new Throwable("");
log.debug("Stacktrace which triggered ServletResponse.flushBuffer()", t);
}
flushWrappedBuffer = true;
} else {
wrappedResponse.flushBuffer();
}
} | /bundle/src/main/java/com/adobe/acs/commons/util/BufferedServletOutput.java |
robustness-copilot_data_440 | /**
* Updates the last status reported for the specified server.
*
* @param serverName the name of the server
* @param status the new status
*/
public void updateLastKnownServerStatus(String serverName, String status){
getSko(serverName).getLastKnownStatus().getAndUpdate(lastKnownStatus -> {
LastKnownStatus updatedStatus = null;
if (status != null) {
updatedStatus = (lastKnownStatus != null && status.equals(lastKnownStatus.getStatus())) ? new LastKnownStatus(status, lastKnownStatus.getUnchangedCount() + 1) : new LastKnownStatus(status);
}
return updatedStatus;
});
} | /operator/src/main/java/oracle/kubernetes/operator/helpers/DomainPresenceInfo.java |
robustness-copilot_data_441 | /**
* Check if the type of the JsonNode's value is number based on the
* status of typeLoose flag.
*
* @param node the JsonNode to check
* @param config the SchemaValidatorsConfig to depend on
* @return boolean to indicate if it is a number
*/
public static boolean isNumber(JsonNode node, SchemaValidatorsConfig config){
if (node.isNumber()) {
return true;
} else if (config.isTypeLoose()) {
if (TypeFactory.getValueNodeType(node, config) == JsonType.STRING) {
return isNumeric(node.textValue());
}
}
return false;
} | /src/main/java/com/networknt/schema/TypeValidator.java |
robustness-copilot_data_442 | /**
* By snapping to the cardinal direction (compass point) of the provided
* vector, return the position opposite the 'snapped' coordinate.
*
* @param opposite position the hydrogen label opposite to this vector
* @return the position
*/
static HydrogenPosition usingCardinalDirection(final Vector2d opposite){
final double theta = Math.atan2(opposite.y, opposite.x);
final int direction = (int) Math.round(theta / (Math.PI / 4));
switch(direction) {
case -4:
case -3:
return Right;
case -2:
return Above;
case -1:
case 0:
case 1:
return Left;
case 2:
return Below;
case 3:
case 4:
return Right;
}
return Right;
} | /display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/HydrogenPosition.java |
robustness-copilot_data_443 | /**
* Transforms a point according to the current affine transformation,
* converting a world coordinate into a screen coordinate.
*
* @param xCoord x-coordinate of the world point to transform
* @param yCoord y-coordinate of the world point to transform
* @return the transformed screen coordinate
*/
public int[] transformPoint(double xCoord, double yCoord){
double[] src = new double[] { xCoord, yCoord };
double[] dest = new double[2];
this.transform.transform(src, 0, dest, 0, 1);
return new int[] { (int) dest[0], (int) dest[1] };
} | /display/renderawt/src/main/java/org/openscience/cdk/renderer/visitor/AbstractAWTDrawVisitor.java |
robustness-copilot_data_444 | /**
* Quick check to see whether <i>both</i> the links are shorter than the
* given threshold.
* @param linkA
* @param linkB
* @param thresholdLength
* @return true if <i>both</i> links are shorter than the given threshold,
* false otherwise.
*/
private boolean bothLinksAreShorterThanThreshold(Link linkA, Link linkB, double thresholdLength){
boolean hasTwoShortLinks = false;
if (linkA.getLength() < thresholdLength && linkB.getLength() < thresholdLength) {
hasTwoShortLinks = true;
}
return hasTwoShortLinks;
} | /matsim/src/main/java/org/matsim/core/network/algorithms/NetworkSimplifier.java |
robustness-copilot_data_445 | /**
* Labels the atom at the specified index with the provide label. If the
* atom was not already a pseudo atom then the original atom is replaced.
*
* @param container structure
* @param index atom index to replace
* @param label the label for the atom
* @see IPseudoAtom#setLabel(String)
*/
static void label(final IAtomContainer container, final int index, final String label){
final IAtom atom = container.getAtom(index);
final IPseudoAtom pseudoAtom = atom instanceof IPseudoAtom ? (IPseudoAtom) atom : container.getBuilder().newInstance(IPseudoAtom.class);
if (atom.equals(pseudoAtom)) {
pseudoAtom.setLabel(label);
} else {
pseudoAtom.setSymbol(label);
pseudoAtom.setAtomicNumber(atom.getAtomicNumber());
pseudoAtom.setPoint2d(atom.getPoint2d());
pseudoAtom.setPoint3d(atom.getPoint3d());
pseudoAtom.setMassNumber(atom.getMassNumber());
pseudoAtom.setFormalCharge(atom.getFormalCharge());
pseudoAtom.setValency(atom.getValency());
pseudoAtom.setLabel(label);
AtomContainerManipulator.replaceAtomByAtom(container, atom, pseudoAtom);
}
} | /storage/ctab/src/main/java/org/openscience/cdk/io/MDLV2000Reader.java |
robustness-copilot_data_446 | /**
* Index the stereo elements of the {@code container} into the the {@code
* elements} and {@code types} arrays. The {@code map} is used for looking
* up the index of atoms.
*
* @param map index of atoms
* @param elements array to fill with stereo elements
* @param types type of stereo element indexed
* @param container the container to index the elements of
* @return indices of atoms involved in stereo configurations
*/
private static int[] indexElements(Map<IAtom, Integer> map, IStereoElement[] elements, Type[] types, IAtomContainer container){
int[] indices = new int[container.getAtomCount()];
int nElements = 0;
for (IStereoElement element : container.stereoElements()) {
if (element instanceof ITetrahedralChirality) {
ITetrahedralChirality tc = (ITetrahedralChirality) element;
int idx = map.get(tc.getChiralAtom());
elements[idx] = element;
types[idx] = Type.Tetrahedral;
indices[nElements++] = idx;
} else if (element instanceof IDoubleBondStereochemistry) {
IDoubleBondStereochemistry dbs = (IDoubleBondStereochemistry) element;
int idx1 = map.get(dbs.getStereoBond().getBegin());
int idx2 = map.get(dbs.getStereoBond().getEnd());
elements[idx2] = elements[idx1] = element;
types[idx1] = types[idx2] = Type.Geometric;
indices[nElements++] = idx1;
}
}
return Arrays.copyOf(indices, nElements);
} | /base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/StereoMatch.java |
robustness-copilot_data_447 | /**
* Execute all numbering functions for the given slice setting values in the appropriate
* destination column.
*/
private void processNumberingFunctions(TableSlice slice){
for (String toColumn : query.getArgumentList().getNumberingFunctions().keySet()) {
if (rowComparator == null) {
throw new IllegalArgumentException("Cannot use Numbering Function without OrderBy");
}
FunctionCall<NumberingFunctions> functionCall = query.getArgumentList().getNumberingFunctions().get(toColumn);
NumberingFunctions numberingFunctions = functionCall.getFunction();
NumberingFunction function = numberingFunctions.getImplementation();
Column<Integer> destinationColumn = (Column<Integer>) destination.column(functionCall.getDestinationColumnName());
int prevRowNumber = -1;
for (Row row : slice) {
if (row.getRowNumber() == 0) {
function.addNextRow();
} else {
if (rowComparator.compare(slice.mappedRowNumber(prevRowNumber), slice.mappedRowNumber(row.getRowNumber())) == 0) {
function.addEqualRow();
} else {
function.addNextRow();
}
}
prevRowNumber = row.getRowNumber();
destinationColumn.set(slice.mappedRowNumber(row.getRowNumber()), function.getValue());
}
}
} | /core/src/main/java/tech/tablesaw/analytic/AnalyticQueryEngine.java |
robustness-copilot_data_448 | /**
* Loads all mandatory Scenario elements and
* if activated in config's scenario module/group
* optional elements.
* @return the Scenario
*/
Scenario loadScenario(){
// String currentDir = new File("tmp").getAbsolutePath();
// currentDir = currentDir.substring(0, currentDir.length() - 3);
// log.info("loading scenario from base directory: " + currentDir);
// the above is not used and thus only causing confusion in the log output. kai, sep'18
this.loadNetwork();
this.loadActivityFacilities();
this.loadPopulation();
// tests internally if the file is there
this.loadHouseholds();
// tests internally if the file is there
this.loadTransit();
// tests internally if the file is there
this.loadTransitVehicles();
if (this.config.vehicles().getVehiclesFile() != null) {
this.loadVehicles();
}
if (this.config.network().getLaneDefinitionsFile() != null) {
this.loadLanes();
}
return this.scenario;
} | /matsim/src/main/java/org/matsim/core/scenario/ScenarioLoaderImpl.java |
robustness-copilot_data_449 | /**
* This makes maps of matching atoms out of atom maps of matching bonds as produced by the get(Subgraph|Ismorphism)Maps methods.
*
* @param list The list produced by the getMap method.
* @param sourceGraph The first atom container. Must not be atom IQueryAtomContainer.
* @param targetGraph The second one (first and second as in getMap). May be an QueryAtomContaienr.
* @return A Vector of Vectors of CDKRMap objects of matching Atoms.
*/
public static List<List<CDKRMap>> makeAtomsMapsOfBondsMaps(List<List<CDKRMap>> list, IAtomContainer sourceGraph, IAtomContainer targetGraph){
if (list == null) {
return list;
}
if (targetGraph.getAtomCount() == 1) {
return list;
}
List<List<CDKRMap>> result = new ArrayList<List<CDKRMap>>();
for (List<CDKRMap> l2 : list) {
result.add(makeAtomsMapOfBondsMap(l2, sourceGraph, targetGraph));
}
return result;
} | /legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java |
robustness-copilot_data_450 | /**
* Check the validity of the parameters received for this activation.
*
* @param action The replication action specifying properties of the activation.
* @param path The path to the item to be activated.
* @throws ReplicationException Throws a replication exception if invalid.
*/
private void checkValidity(ReplicationAction action, String path) throws ReplicationException{
if (action.getType() != ReplicationActionType.ACTIVATE && action.getType() != ReplicationActionType.TEST) {
logErrorMessage("No re-fetch handling for replication action " + action.getType().getName());
throw new ReplicationException("No re-fetch handling for replication action " + action.getType().getName());
}
if (StringUtils.isEmpty(path)) {
logErrorMessage("No path found for re-fetch replication.");
throw new ReplicationException("No path found for re-fetch replication.");
}
if (!CONTENT_BUILDER_NAME.equals(action.getConfig().getSerializationType())) {
String message = "Serialization type '" + action.getConfig().getSerializationType() + "' not supported by Flush Re-Fetch Content Builder.";
logErrorMessage(message);
throw new ReplicationException(message);
}
} | /bundle/src/main/java/com/adobe/acs/commons/replication/dispatcher/impl/RefetchFlushContentBuilderImpl.java |
robustness-copilot_data_451 | /**
* Check to see if this permutation is the identity permutation.
*
* @return true if for all i, p[i] = i
*/
public boolean isIdentity(){
for (int i = 0; i < this.values.length; i++) {
if (this.values[i] != i) {
return false;
}
}
return true;
} | /tool/group/src/main/java/org/openscience/cdk/group/Permutation.java |
robustness-copilot_data_452 | /**
* Adds the specified element to this priority queue, with the given priority.
* @param o
* @param priority
* @return <tt>true</tt> if the element was added to the collection.
*/
public boolean add(final E o, final double priority){
if (o == null) {
throw new NullPointerException();
}
PseudoEntry<E> entry = new PseudoEntry<E>(o, priority);
if (this.lastEntry.containsKey(o)) {
return false;
}
if (this.delegate.add(entry)) {
this.lastEntry.put(o, entry);
return true;
}
// this should never happen
return false;
} | /matsim/src/main/java/org/matsim/core/utils/collections/PseudoRemovePriorityQueue.java |
robustness-copilot_data_453 | /**
* Overriding `adaptTo` to avoid using the original request as the adaptable.
*/
public AdapterType adaptTo(Class<AdapterType> type){
AdapterType result = null;
synchronized (this) {
result = (AdapterType) this.adaptersCache.get(type);
if (result == null) {
AdapterManager mgr = Activator.getAdapterManager();
if (mgr == null) {
LOG.warn("Unable to adapt request for path {} to {} because AdapterManager is null", this.resource.getPath(), type);
} else {
result = mgr.getAdapter(this, type);
}
if (result != null) {
this.adaptersCache.put(type, result);
}
}
return result;
}
} | /bundle/src/main/java/com/adobe/acs/commons/util/OverridePathSlingRequestWrapper.java |
robustness-copilot_data_454 | /**
* Returns true if the two maps of values match. A null map is considered to match an empty map.
*
* @param first the first map to compare
* @param second the second map to compare
* @return true if the maps match.
*/
static boolean mapEquals(Map<K, V> first, Map<K, V> second){
return Objects.equals(first, second) || (isNullOrEmpty(first) && isNullOrEmpty(second));
} | /operator/src/main/java/oracle/kubernetes/operator/helpers/KubernetesUtils.java |
robustness-copilot_data_455 | /**
* Converts an array of Regex strings into compiled Patterns.
*
* @param regexes the regex strings to compile into Patterns
* @return the list of compiled Patterns
*/
private List<Pattern> compileToPatterns(final List<String> regexes){
final List<Pattern> patterns = new ArrayList<Pattern>();
for (String regex : regexes) {
if (StringUtils.isNotBlank(regex)) {
patterns.add(Pattern.compile(regex));
}
}
return patterns;
} | /bundle/src/main/java/com/adobe/acs/commons/httpcache/config/impl/HttpCacheConfigImpl.java |
robustness-copilot_data_456 | /**
* Evaluate the LINGO similarity between two key,value sty;e fingerprints.
*
* The value will range from 0.0 to 1.0.
*
* @param features1
* @param features2
* @return similarity
*/
public static float calculate(Map<String, Integer> features1, Map<String, Integer> features2){
TreeSet<String> keys = new TreeSet<String>(features1.keySet());
keys.addAll(features2.keySet());
float sum = 0.0f;
for (String key : keys) {
Integer c1 = features1.get(key);
Integer c2 = features2.get(key);
c1 = c1 == null ? 0 : c1;
c2 = c2 == null ? 0 : c2;
sum += 1.0 - Math.abs(c1 - c2) / (c1 + c2);
}
return sum / keys.size();
} | /descriptor/fingerprint/src/main/java/org/openscience/cdk/similarity/LingoSimilarity.java |
robustness-copilot_data_457 | /**
* Access continue field, if any, from list metadata.
* @param result Kubernetes list result
* @return Continue value
*/
public static String accessContinue(Object result){
return Optional.ofNullable(result).filter(KubernetesListObject.class::isInstance).map(KubernetesListObject.class::cast).map(KubernetesListObject::getMetadata).map(V1ListMeta::getContinue).filter(Predicate.not(String::isEmpty)).orElse(null);
} | /operator/src/main/java/oracle/kubernetes/operator/calls/AsyncRequestStep.java |
robustness-copilot_data_458 | /**
* Checks if the atom can be involved in a double-bond.
* @param idx atom idx
* @return the atom at index (idx) is valid for a double bond
* @see <a href="http://www.inchi-trust.org/download/104/InChI_TechMan.pdf">Double bond stereochemistry, InChI Technical Manual</a>
*/
private boolean isCisTransEndPoint(int idx){
IAtom atom = container.getAtom(idx);
if (atom.getAtomicNumber() == null || atom.getFormalCharge() == null || atom.getImplicitHydrogenCount() == null)
return false;
final int chg = atom.getFormalCharge();
final int btypes = getBondTypes(idx);
switch(atom.getAtomicNumber()) {
case 6:
case 14:
case 32:
return chg == 0 && btypes == 0x0102;
case 7:
if (chg == 0)
return btypes == 0x0101;
if (chg == +1)
return btypes == 0x0102;
default:
return false;
}
} | /tool/sdg/src/main/java/org/openscience/cdk/layout/NonplanarBonds.java |
robustness-copilot_data_459 | /**
* Create an instance of a {@link ValidationRule} which should result in a warning should the evaluate of this rule fail.
*
* @param description A description to help differentiate this rule from others (not intended to be user-facing).
* @param failureMessage The message to be displayed in the event of a test failure (intended to be user-facing).
* @param fn The test condition to be applied as a part of this rule, when this function returns <code>true</code>,
* the evaluated instance will be considered "valid" according to this rule.
* @param <T> The type of the object being evaluated.
*
* @return A new instance of a {@link ValidationRule}
*/
public static ValidationRule warn(String description, String failureMessage, Function<T, Result> fn){
return new ValidationRule(Severity.WARNING, description, failureMessage, (Function<Object, Result>) fn);
} | /modules/openapi-generator-core/src/main/java/org/openapitools/codegen/validation/ValidationRule.java |
robustness-copilot_data_460 | /**
* Sort solution by ascending order of the fragment count.
*/
public synchronized void sortResultsByFragments(){
Map<Integer, Map<Integer, Integer>> allFragmentMCS = new TreeMap<Integer, Map<Integer, Integer>>();
Map<Integer, Map<IAtom, IAtom>> allFragmentAtomMCS = new TreeMap<Integer, Map<IAtom, IAtom>>();
Map<Integer, Double> stereoScoreMap = new TreeMap<Integer, Double>();
Map<Integer, Double> energyScoreMap = new TreeMap<Integer, Double>();
Map<Integer, Integer> fragmentScoreMap = new TreeMap<Integer, Integer>();
initializeMaps(allFragmentMCS, allFragmentAtomMCS, stereoScoreMap, fragmentScoreMap, energyScoreMap);
int minFragmentScore = 9999;
for (Integer key : allFragmentAtomMCS.keySet()) {
Map<IAtom, IAtom> mcsAtom = allFragmentAtomMCS.get(key);
int fragmentCount = getMappedMoleculeFragmentSize(mcsAtom);
fragmentScoreMap.put(key, fragmentCount);
if (minFragmentScore > fragmentCount) {
minFragmentScore = fragmentCount;
}
}
boolean flag = false;
if (minFragmentScore < 9999) {
flag = true;
clear();
}
int counter = 0;
for (Map.Entry<Integer, Integer> map : fragmentScoreMap.entrySet()) {
if (minFragmentScore == map.getValue().intValue()) {
addSolution(counter, map.getKey(), allFragmentAtomMCS, allFragmentMCS, stereoScoreMap, energyScoreMap, fragmentScoreMap);
counter++;
}
}
if (flag) {
firstSolution.putAll(allMCS.get(0));
firstAtomMCS.putAll(allAtomMCS.get(0));
clear(allFragmentMCS, allFragmentAtomMCS, stereoScoreMap, fragmentScoreMap, energyScoreMap);
}
} | /legacy/src/main/java/org/openscience/cdk/smsd/filters/ChemicalFilters.java |
robustness-copilot_data_461 | /**
* Executes the health check, catching and handling any exceptions raised by {@link #check()}.
*
* @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link
* Result} with a descriptive error message or exception
*/
Result execute(){
long start = clock().getTick();
Result result;
try {
result = check();
} catch (Exception e) {
result = Result.unhealthy(e);
}
result.setDuration(TimeUnit.MILLISECONDS.convert(clock().getTick() - start, TimeUnit.NANOSECONDS));
return result;
} | /metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java |
robustness-copilot_data_462 | /**
* Creates empty columns that will be filled in when the analytic aggregate or numbering functions
* are executed.
*/
private void addColumns(){
this.destination.addColumns(query.getArgumentList().createEmptyDestinationColumns(query.getTable().rowCount()).toArray(new Column<?>[0]));
} | /core/src/main/java/tech/tablesaw/analytic/AnalyticQueryEngine.java |
robustness-copilot_data_463 | /**
* Assign a 2D layout to the atom container using the contents of the library. If multiple
* coordinates are available the first is choosen.
*
* @param container structure representation
* @return a layout was assigned
*/
boolean assignLayout(IAtomContainer container){
try {
int n = container.getAtomCount();
int[] ordering = new int[n];
String smiles = cansmi(container, ordering);
for (Point2d[] points : templateMap.getOrDefault(smiles, Collections.emptyList())) {
for (int i = 0; i < n; i++) {
container.getAtom(i).setPoint2d(new Point2d(points[ordering[i]]));
}
return true;
}
} catch (CDKException e) {
}
return false;
} | /tool/sdg/src/main/java/org/openscience/cdk/layout/IdentityTemplateLibrary.java |
robustness-copilot_data_464 | /**
* Execute the ImageTransformers as specified by the Request's suffix segments against the Image layer.
*
* @param layer the Image layer
* @param imageTransformersWithParams the transforms and their params
* @return the transformed Image layer
*/
protected final Layer transform(Layer layer, final ValueMap imageTransformersWithParams){
for (final String type : imageTransformersWithParams.keySet()) {
if (StringUtils.equals(TYPE_QUALITY, type)) {
continue;
}
final ImageTransformer imageTransformer = this.imageTransformers.get(type);
if (imageTransformer == null) {
log.warn("Skipping transform. Missing ImageTransformer for type: {}", type);
continue;
}
final ValueMap transformParams = imageTransformersWithParams.get(type, EMPTY_PARAMS);
if (transformParams != null) {
layer = imageTransformer.transform(layer, transformParams);
}
}
return layer;
} | /bundle/src/main/java/com/adobe/acs/commons/images/impl/NamedTransformImageServlet.java |
robustness-copilot_data_465 | /**
* Returns a Pattern for matching the provided billing format.
* <p>
* Attributes are turned into named capturing groups.
*/
private static Pattern toPattern(String name, String format){
StringBuilder regex = new StringBuilder();
Matcher matcher = ATTRIBUTE_PATTERN.matcher(format);
int pos = 0;
while (matcher.find()) {
if (pos < matcher.start()) {
regex.append(Pattern.quote(format.substring(pos, matcher.start())));
}
String expression = matcher.group(1);
if (isIf(expression)) {
regex.append("(?:");
} else if (isElse(expression)) {
regex.append("|");
} else if (isEndIf(expression)) {
regex.append(")");
} else {
regex.append("(?<").append(toGroupName(expression)).append(">");
switch(expression) {
case "date":
regex.append(".+?");
break;
case "pnfsid":
regex.append("[0-9A-F]{24}(?:[0-9A-F]{12})?");
break;
case "filesize":
case "transferred":
case "connectionTime":
case "transactionTime":
case "queuingTime":
case "transferTime":
case "rc":
case "uid":
case "gid":
regex.append("-?\\d+");
break;
case "cached":
case "created":
regex.append("(?:true|false)");
break;
case "cellType":
switch(name) {
case "mover-info-message":
case "remove-file-info-message":
case "storage-info-message":
case "pool-hit-info-message":
regex.append("pool");
break;
case "door-request-info-message":
regex.append("door");
break;
default:
regex.append("\\w+");
break;
}
break;
case "cellName":
regex.append(".+?");
break;
case "type":
switch(name) {
case "mover-info-message":
regex.append("transfer");
break;
case "remove-file-info-message":
regex.append("remove");
break;
case "storage-info-message":
regex.append("(?:re)?store");
break;
case "pool-hit-info-message":
regex.append("hit");
break;
case "warning-pnfs-file-info-message":
regex.append("warning");
break;
default:
regex.append("\\w+");
break;
}
break;
default:
regex.append(".*?");
}
regex.append(")");
}
pos = matcher.end();
}
if (pos < format.length()) {
regex.append(Pattern.quote(format.substring(pos)));
}
return Pattern.compile(regex.toString(), Pattern.CASE_INSENSITIVE);
} | /modules/dcache/src/main/java/org/dcache/services/billing/text/BillingParserBuilder.java |
robustness-copilot_data_466 | /**
* Returns true if the current map is missing values from the required map. This method is
* typically used to compare labels and annotations against specifications derived from the
* domain.
*
* @param current a map of the values found in a Kubernetes resource
* @param required a map of the values specified for the resource by the domain
* @return true if there is a problem that must be fixed by patching
*/
static boolean isMissingValues(Map<String, String> current, Map<String, String> required){
if (!hasAllRequiredNames(current, required)) {
return true;
}
for (String name : required.keySet()) {
if (!Objects.equals(current.get(name), required.get(name))) {
return true;
}
}
return false;
} | /operator/src/main/java/oracle/kubernetes/operator/helpers/KubernetesUtils.java |
robustness-copilot_data_467 | /**
* Returns true if the given atom participates in this bond.
*
* @param atom The atom to be tested if it participates in this bond
* @return true if the atom participates in this bond
*/
public boolean contains(IAtom atom){
if (atoms == null)
return false;
for (IAtom localAtom : atoms) {
if (localAtom.equals(atom))
return true;
}
return false;
} | /base/silent/src/main/java/org/openscience/cdk/silent/Bond.java |
robustness-copilot_data_468 | /**
* Maps the function across all rows, storing the results into the provided Column.
*
* <p>The target column must have at least the same number of rows.
*
* @param fun function to map
* @param into Column into which results are set
* @return the provided Column
*/
C mapInto(Function<? super T, ? extends R> fun, C into){
for (int i = 0; i < size(); i++) {
if (isMissing(i)) {
into.setMissing(i);
} else {
into.set(i, fun.apply(get(i)));
}
}
return into;
} | /core/src/main/java/tech/tablesaw/columns/Column.java |
robustness-copilot_data_469 | /**
* Get set of attributes extracted from the search result.
*
* @param <T> type of extracted type.
* @param sre ldap search result.
* @param attr search result attribute.
* @param mapper mapping function to apply to each result element.
* @return set of attributes.
* @throws NamingException
*/
private static Set<T> extractAttributes(NamingEnumeration<SearchResult> sre, String attr, Function<String, T> mapper) throws NamingException{
Set<T> attrs = new HashSet<>();
while (sre.hasMore()) {
T v = mapper.apply((String) sre.next().getAttributes().get(attr).get());
attrs.add(v);
}
if (attrs.isEmpty()) {
throw new NoSuchElementException();
}
return attrs;
} | /modules/gplazma2-ldap/src/main/java/org/dcache/gplazma/plugins/Ldap.java |
robustness-copilot_data_470 | /**
* Refines the coarse partition <code>a</code> into a finer one.
*
* @param coarser the partition to refine
* @return a finer partition
*/
public Partition refine(Partition coarser){
Partition finer = new Partition(coarser);
blocksToRefine = new LinkedList<Set<Integer>>();
for (int i = 0; i < finer.size(); i++) {
blocksToRefine.add(finer.copyBlock(i));
}
int numberOfVertices = refinable.getVertexCount();
while (!blocksToRefine.isEmpty()) {
Set<Integer> t = blocksToRefine.remove();
currentBlockIndex = 0;
while (currentBlockIndex < finer.size() && finer.size() < numberOfVertices) {
if (!finer.isDiscreteCell(currentBlockIndex)) {
Map<Invariant, SortedSet<Integer>> invariants = getInvariants(finer, t);
split(invariants, finer);
}
currentBlockIndex++;
}
if (finer.size() == numberOfVertices) {
return finer;
}
}
return finer;
} | /tool/group/src/main/java/org/openscience/cdk/group/EquitablePartitionRefiner.java |
robustness-copilot_data_471 | /**
* Read a <code>ChemFile</code> from a file in PDB format. The molecules
* in the file are stored as <code>BioPolymer</code>s in the
* <code>ChemFile</code>. The residues are the monomers of the
* <code>BioPolymer</code>, and their names are the concatenation of the
* residue, chain id, and the sequence number. Separate chains (denoted by
* TER records) are stored as separate <code>BioPolymer</code> molecules.
*
* <p>Connectivity information is not currently read.
*
* @return The ChemFile that was read from the PDB file.
*/
private IChemFile readChemFile(IChemFile oFile){
IChemSequence oSeq = oFile.getBuilder().newInstance(IChemSequence.class);
IChemModel oModel = oFile.getBuilder().newInstance(IChemModel.class);
IAtomContainerSet oSet = oFile.getBuilder().newInstance(IAtomContainerSet.class);
String cCol;
PDBAtom oAtom;
PDBPolymer oBP = new PDBPolymer();
IAtomContainer molecularStructure = oFile.getBuilder().newInstance(IAtomContainer.class);
StringBuffer cResidue;
String oObj;
IMonomer oMonomer;
String cRead = "";
char chain = 'A';
IStrand oStrand;
int lineLength = 0;
boolean isProteinStructure = false;
atomNumberMap = new Hashtable<Integer, IAtom>();
if (readConnect.isSet()) {
bondsFromConnectRecords = new ArrayList<IBond>();
}
try {
do {
cRead = _oInput.readLine();
logger.debug("Read line: ", cRead);
if (cRead != null) {
lineLength = cRead.length();
if (lineLength < 6) {
cRead = cRead + " ";
}
cCol = cRead.substring(0, 6);
if ("SEQRES".equalsIgnoreCase(cCol)) {
isProteinStructure = true;
} else if ("ATOM ".equalsIgnoreCase(cCol)) {
oAtom = readAtom(cRead, lineLength);
if (isProteinStructure) {
cResidue = new StringBuffer(8);
oObj = oAtom.getResName();
if (oObj != null) {
cResidue = cResidue.append(oObj.trim());
}
oObj = oAtom.getChainID();
if (oObj != null) {
cResidue = cResidue.append(String.valueOf(chain));
}
oObj = oAtom.getResSeq();
if (oObj != null) {
cResidue = cResidue.append(oObj.trim());
}
String strandName = oAtom.getChainID();
if (strandName == null || strandName.length() == 0) {
strandName = String.valueOf(chain);
}
oStrand = oBP.getStrand(strandName);
if (oStrand == null) {
oStrand = new PDBStrand();
oStrand.setStrandName(strandName);
oStrand.setID(String.valueOf(chain));
}
oMonomer = oBP.getMonomer(cResidue.toString(), String.valueOf(chain));
if (oMonomer == null) {
PDBMonomer monomer = new PDBMonomer();
monomer.setMonomerName(cResidue.toString());
monomer.setMonomerType(oAtom.getResName());
monomer.setChainID(oAtom.getChainID());
monomer.setICode(oAtom.getICode());
monomer.setResSeq(oAtom.getResSeq());
oMonomer = monomer;
}
oBP.addAtom(oAtom, oMonomer, oStrand);
} else {
molecularStructure.addAtom(oAtom);
}
if (readConnect.isSet() && atomNumberMap.put(oAtom.getSerial(), oAtom) != null) {
logger.warn("Duplicate serial ID found for atom: ", oAtom);
}
logger.debug("Added ATOM: ", oAtom);
} else if ("HETATM".equalsIgnoreCase(cCol)) {
oAtom = readAtom(cRead, lineLength);
oAtom.setHetAtom(true);
if (isProteinStructure) {
oBP.addAtom(oAtom);
} else {
molecularStructure.addAtom(oAtom);
}
if (atomNumberMap.put(oAtom.getSerial(), oAtom) != null) {
logger.warn("Duplicate serial ID found for atom: ", oAtom);
}
logger.debug("Added HETATM: ", oAtom);
} else if ("TER ".equalsIgnoreCase(cCol)) {
chain++;
oStrand = new PDBStrand();
oStrand.setStrandName(String.valueOf(chain));
logger.debug("Added new STRAND");
} else if ("END ".equalsIgnoreCase(cCol)) {
atomNumberMap.clear();
if (isProteinStructure) {
oSet.addAtomContainer(oBP);
if (useRebondTool.isSet()) {
try {
if (!createBondsWithRebondTool(oBP)) {
logger.info("Bonds could not be created using the RebondTool when PDB file was read.");
oBP.removeAllBonds();
}
} catch (Exception exception) {
logger.info("Bonds could not be created when PDB file was read.");
logger.debug(exception);
}
}
} else {
if (useRebondTool.isSet())
createBondsWithRebondTool(molecularStructure);
oSet.addAtomContainer(molecularStructure);
}
} else if (cCol.equals("MODEL ")) {
if (isProteinStructure) {
if (oBP.getAtomCount() > 0) {
oSet.addAtomContainer(oBP);
oModel.setMoleculeSet(oSet);
oSeq.addChemModel(oModel);
oBP = new PDBPolymer();
oModel = oFile.getBuilder().newInstance(IChemModel.class);
oSet = oFile.getBuilder().newInstance(IAtomContainerSet.class);
atomNumberMap.clear();
}
} else {
if (molecularStructure.getAtomCount() > 0) {
oSet.addAtomContainer(molecularStructure);
oModel.setMoleculeSet(oSet);
oSeq.addChemModel(oModel);
molecularStructure = oFile.getBuilder().newInstance(IAtomContainer.class);
oModel = oFile.getBuilder().newInstance(IChemModel.class);
oSet = oFile.getBuilder().newInstance(IAtomContainerSet.class);
}
}
} else if ("REMARK".equalsIgnoreCase(cCol)) {
Object comment = oFile.getProperty(CDKConstants.COMMENT);
if (comment == null) {
comment = "";
}
if (lineLength > 12) {
comment = comment.toString() + cRead.substring(11).trim() + "\n";
oFile.setProperty(CDKConstants.COMMENT, comment);
} else {
logger.warn("REMARK line found without any comment!");
}
} else if ("COMPND".equalsIgnoreCase(cCol)) {
String title = cRead.substring(10).trim();
oFile.setProperty(CDKConstants.TITLE, title);
} else if (readConnect.isSet() && "CONECT".equalsIgnoreCase(cCol)) {
cRead.trim();
if (cRead.length() < 16) {
logger.debug("Skipping unexpected empty CONECT line! : ", cRead);
} else {
int lineIndex = 6;
int atomFromNumber = -1;
int atomToNumber = -1;
IAtomContainer molecule = (isProteinStructure) ? oBP : molecularStructure;
while (lineIndex + 5 <= cRead.length()) {
String part = cRead.substring(lineIndex, lineIndex + 5).trim();
if (atomFromNumber == -1) {
try {
atomFromNumber = Integer.parseInt(part);
} catch (NumberFormatException nfe) {
}
} else {
try {
atomToNumber = Integer.parseInt(part);
} catch (NumberFormatException nfe) {
atomToNumber = -1;
}
if (atomFromNumber != -1 && atomToNumber != -1) {
addBond(molecule, atomFromNumber, atomToNumber);
logger.debug("Bonded " + atomFromNumber + " with " + atomToNumber);
}
}
lineIndex += 5;
}
}
} else if ("HELIX ".equalsIgnoreCase(cCol)) {
PDBStructure structure = new PDBStructure();
structure.setStructureType(PDBStructure.HELIX);
structure.setStartChainID(cRead.charAt(19));
structure.setStartSequenceNumber(Integer.parseInt(cRead.substring(21, 25).trim()));
structure.setStartInsertionCode(cRead.charAt(25));
structure.setEndChainID(cRead.charAt(31));
structure.setEndSequenceNumber(Integer.parseInt(cRead.substring(33, 37).trim()));
structure.setEndInsertionCode(cRead.charAt(37));
oBP.addStructure(structure);
} else if ("SHEET ".equalsIgnoreCase(cCol)) {
PDBStructure structure = new PDBStructure();
structure.setStructureType(PDBStructure.SHEET);
structure.setStartChainID(cRead.charAt(21));
structure.setStartSequenceNumber(Integer.parseInt(cRead.substring(22, 26).trim()));
structure.setStartInsertionCode(cRead.charAt(26));
structure.setEndChainID(cRead.charAt(32));
structure.setEndSequenceNumber(Integer.parseInt(cRead.substring(33, 37).trim()));
structure.setEndInsertionCode(cRead.charAt(37));
oBP.addStructure(structure);
} else if ("TURN ".equalsIgnoreCase(cCol)) {
PDBStructure structure = new PDBStructure();
structure.setStructureType(PDBStructure.TURN);
structure.setStartChainID(cRead.charAt(19));
structure.setStartSequenceNumber(Integer.parseInt(cRead.substring(20, 24).trim()));
structure.setStartInsertionCode(cRead.charAt(24));
structure.setEndChainID(cRead.charAt(30));
structure.setEndSequenceNumber(Integer.parseInt(cRead.substring(31, 35).trim()));
structure.setEndInsertionCode(cRead.charAt(35));
oBP.addStructure(structure);
}
}
} while (_oInput.ready() && (cRead != null));
} catch (IOException | IllegalArgumentException | CDKException e) {
logger.error("Found a problem at line:");
logger.error(cRead);
logger.error("01234567890123456789012345678901234567890123456789012345678901234567890123456789");
logger.error(" 1 2 3 4 5 6 7 ");
logger.error(" error: " + e.getMessage());
logger.debug(e);
e.printStackTrace();
}
try {
_oInput.close();
} catch (Exception e) {
logger.debug(e);
}
oModel.setMoleculeSet(oSet);
oSeq.addChemModel(oModel);
oFile.addChemSequence(oSeq);
return oFile;
} | /storage/pdb/src/main/java/org/openscience/cdk/io/PDBReader.java |
robustness-copilot_data_472 | /**
* Calculates the topological polar surface area and expresses it as a ratio to molecule size.
*
* @param mol The {@link IAtomContainer} whose volume is to be calculated
* @return descriptor(s) retaining to polar surface area
*/
public DescriptorValue calculate(IAtomContainer mol){
try {
mol = mol.clone();
} catch (CloneNotSupportedException ex) {
}
double polar = 0, weight = 0;
try {
IChemObjectBuilder builder = mol.getBuilder();
CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.getInstance(builder);
for (IAtom atom : mol.atoms()) {
IAtomType type = matcher.findMatchingAtomType(mol, atom);
AtomTypeManipulator.configure(atom, type);
}
CDKHydrogenAdder adder = CDKHydrogenAdder.getInstance(builder);
adder.addImplicitHydrogens(mol);
TPSADescriptor tpsa = new TPSADescriptor();
DescriptorValue value = tpsa.calculate(mol);
polar = ((DoubleResult) value.getValue()).doubleValue();
for (IAtom atom : mol.atoms()) {
weight += Isotopes.getInstance().getMajorIsotope(atom.getSymbol()).getExactMass();
Integer hcount = atom.getImplicitHydrogenCount();
if (hcount != CDKConstants.UNSET)
weight += hcount * 1.00782504;
}
} catch (CDKException | IOException exception) {
return getDummyDescriptorValue(exception);
}
return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), new DoubleResult(weight == 0 ? 0 : polar / weight), getDescriptorNames());
} | /descriptor/qsarmolecular/src/main/java/org/openscience/cdk/qsar/descriptors/molecular/FractionalPSADescriptor.java |
robustness-copilot_data_473 | /**
* Get a list of all Elements which are contained
* molecular.
*
*@param formula The MolecularFormula to check
*@return The list with the IElements in this molecular formula
*/
public static List<IElement> elements(IMolecularFormula formula){
List<IElement> elementList = new ArrayList<IElement>();
List<String> stringList = new ArrayList<String>();
for (IIsotope isotope : formula.isotopes()) {
if (!stringList.contains(isotope.getSymbol())) {
elementList.add(isotope);
stringList.add(isotope.getSymbol());
}
}
return elementList;
} | /tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java |
robustness-copilot_data_474 | /**
* Adds an carrierVehicle to the CarrierCapabilites of the Carrier.
* @param carrier
* @param carrierVehicle
*/
public static void addCarrierVehicle(Carrier carrier, CarrierVehicle carrierVehicle){
carrier.getCarrierCapabilities().getCarrierVehicles().put(carrierVehicle.getId(), carrierVehicle);
} | /contribs/freight/src/main/java/org/matsim/contrib/freight/carrier/CarrierUtils.java |
robustness-copilot_data_475 | /**
* Whether this cluster contains a server with the given server name,
* including servers that are both configured and dynamic servers.
*
* @param serverName server name to be checked
* @return True if the cluster contains a server with the given server name
*/
boolean containsServer(@Nonnull String serverName){
return getServerConfigs().stream().anyMatch(c -> serverName.equals(c.getName()));
} | /operator/src/main/java/oracle/kubernetes/operator/wlsconfig/WlsClusterConfig.java |
robustness-copilot_data_476 | /**
* Creates an <code>Atom</code> and sets properties to their values from
* the ATOM or HETATM record. If the line is shorter than 80 characters, the
* information past 59 characters is treated as optional. If the line is
* shorter than 59 characters, a <code>RuntimeException</code> is thrown.
*
* @param cLine the PDB ATOM or HEATATM record.
* @return the <code>Atom</code> created from the record.
* @throws RuntimeException if the line is too short (less than 59 characters).
*/
private PDBAtom readAtom(String cLine, int lineLength) throws CDKException{
if (lineLength < 59) {
throw new RuntimeException("PDBReader error during readAtom(): line too short");
}
boolean isHetatm = cLine.startsWith("HETATM");
String atomName = cLine.substring(12, 16).trim();
String resName = cLine.substring(17, 20).trim();
String symbol = parseAtomSymbol(cLine);
if (symbol == null)
handleError("Cannot parse symbol from " + atomName);
PDBAtom oAtom = new PDBAtom(symbol, new Point3d(Double.parseDouble(cLine.substring(30, 38)), Double.parseDouble(cLine.substring(38, 46)), Double.parseDouble(cLine.substring(46, 54))));
if (useHetDictionary.isSet() && isHetatm) {
String cdkType = typeHetatm(resName, atomName);
oAtom.setAtomTypeName(cdkType);
if (cdkType != null) {
try {
cdkAtomTypeFactory.configure(oAtom);
} catch (CDKException cdke) {
logger.warn("Could not configure", resName, " ", atomName);
}
}
}
oAtom.setRecord(cLine);
oAtom.setSerial(Integer.parseInt(cLine.substring(6, 11).trim()));
oAtom.setName(atomName.trim());
oAtom.setAltLoc(cLine.substring(16, 17).trim());
oAtom.setResName(resName);
oAtom.setChainID(cLine.substring(21, 22).trim());
oAtom.setResSeq(cLine.substring(22, 26).trim());
oAtom.setICode(cLine.substring(26, 27).trim());
if (useHetDictionary.isSet() && isHetatm) {
oAtom.setID(oAtom.getResName() + "." + atomName);
} else {
oAtom.setAtomTypeName(oAtom.getResName() + "." + atomName);
}
if (lineLength >= 59) {
String frag = cLine.substring(54, Math.min(lineLength, 60)).trim();
if (frag.length() > 0) {
oAtom.setOccupancy(Double.parseDouble(frag));
}
}
if (lineLength >= 65) {
String frag = cLine.substring(60, Math.min(lineLength, 66)).trim();
if (frag.length() > 0) {
oAtom.setTempFactor(Double.parseDouble(frag));
}
}
if (lineLength >= 75) {
oAtom.setSegID(cLine.substring(72, Math.min(lineLength, 76)).trim());
}
if (lineLength >= 79) {
String frag;
if (lineLength >= 80) {
frag = cLine.substring(78, 80).trim();
} else {
frag = cLine.substring(78);
}
if (frag.length() > 0) {
if (frag.endsWith("-") || frag.endsWith("+")) {
oAtom.setCharge(Double.parseDouble(new StringBuilder(frag).reverse().toString()));
} else {
oAtom.setCharge(Double.parseDouble(frag));
}
}
}
String oxt = cLine.substring(13, 16).trim();
if (oxt.equals("OXT")) {
oAtom.setOxt(true);
} else {
oAtom.setOxt(false);
}
return oAtom;
} | /storage/pdb/src/main/java/org/openscience/cdk/io/PDBReader.java |
robustness-copilot_data_477 | /**
* This function checks whether our parent should expunge us.
*/
public boolean hasExpired(){
Date now = new Date();
return _whenIShouldExpire != null ? !now.before(_whenIShouldExpire) : false;
} | /modules/dcache-info/src/main/java/org/dcache/services/info/base/StateComposite.java |
robustness-copilot_data_478 | /**
* Ensures the node's primary type is included in the Included Node Types and NOT in the Excluded Node Types and NOT in the Excluded Node Names.
*
* @param node the candidate node
* @param options the checksum options containing the included and excluded none types
* @return true if the node represents a checksum-able node system
* @throws RepositoryException
*/
private boolean isChecksumable(Node node, ChecksumGeneratorOptions options) throws RepositoryException{
final Set<String> nodeTypeIncludes = options.getIncludedNodeTypes();
final Set<String> nodeTypeExcludes = options.getExcludedNodeTypes();
final String primaryNodeType = node.getPrimaryNodeType().getName();
return nodeTypeIncludes.contains(primaryNodeType) && !nodeTypeExcludes.contains(primaryNodeType);
} | /bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/ChecksumGeneratorImpl.java |
robustness-copilot_data_479 | /**
* Check whether otherPath points to the same location, or is a child of this path. This is
* true iff each element of this path is identical to the corresponding element in otherPath.
* <pre>
* StatePath p1 = new StatePath("foo.bar");
* StatePath p2 = new StatePath("foo.bar.baz");
*
* p1.equalsOrHasChild(p1) // true
* p2.equalsOrHasChild(p2) // true
* p1.equalsOrHasChild(p2) // true
* p2.equalsOrHasChild(p1) // false
* </pre>
*
* @param otherPath the potential child path
* @return true if otherPath is a child of this path.
*/
public boolean equalsOrHasChild(StatePath otherPath){
if (otherPath == null) {
return false;
}
if (_elements.size() > otherPath._elements.size()) {
return false;
}
for (int i = 0; i < _elements.size(); i++) {
if (_elements.get(i) != otherPath._elements.get(i)) {
return false;
}
}
return true;
} | /modules/dcache-info/src/main/java/org/dcache/services/info/base/StatePath.java |
robustness-copilot_data_480 | /**
* Helper method for constructing a new array that contains specified
* element followed by contents of the given array but never contains
* duplicates.
* If element already existed, one of two things happens: if the element
* was already the first one in array, array is returned as is; but
* if not, a new copy is created in which element has moved as the head.
*/
public static T[] insertInListNoDup(T[] array, T element){
final int len = array.length;
for (int ix = 0; ix < len; ++ix) {
if (array[ix] == element) {
if (ix == 0) {
return array;
}
T[] result = (T[]) Array.newInstance(array.getClass().getComponentType(), len);
System.arraycopy(array, 0, result, 1, ix);
result[0] = element;
++ix;
int left = len - ix;
if (left > 0) {
System.arraycopy(array, ix, result, ix, left);
}
return result;
}
}
T[] result = (T[]) Array.newInstance(array.getClass().getComponentType(), len + 1);
if (len > 0) {
System.arraycopy(array, 0, result, 1, len);
}
result[0] = element;
return result;
} | /src/main/java/com/fasterxml/jackson/databind/util/ArrayBuilders.java |
robustness-copilot_data_481 | /**
* Checks a list of new data files for duplicate names, renaming any
* duplicates to ensure that they are unique.
*
* @param version the dataset version
* @param newFiles the list of new data files to add to it
* @param fileToReplace
*/
public static void checkForDuplicateFileNamesFinal(DatasetVersion version, List<DataFile> newFiles, DataFile fileToReplace){
// Step 1: create list of existing path names from all FileMetadata in the DatasetVersion
// unique path name: directoryLabel + file separator + fileLabel
Set<String> pathNamesExisting = existingPathNamesAsSet(version, ((fileToReplace == null) ? null : fileToReplace.getFileMetadata()));
// Step 2: check each new DataFile against the list of path names, if a duplicate create a new unique file name
for (Iterator<DataFile> dfIt = newFiles.iterator(); dfIt.hasNext(); ) {
FileMetadata fm = dfIt.next().getFileMetadata();
fm.setLabel(duplicateFilenameCheck(fm, pathNamesExisting));
}
} | /src/main/java/edu/harvard/iq/dataverse/ingest/IngestUtil.java |
robustness-copilot_data_482 | /**
* Check whether the url is supported to extract or not.
*
* @param appURL app url
* @return true is the url supported, otherwise not
*/
public static boolean isExtraction(final String appURL){
for (String each : EXTRACTION_TYPES) {
if (appURL.endsWith(each)) {
return true;
}
}
return false;
} | /elasticjob-cloud/elasticjob-cloud-scheduler/src/main/java/org/apache/shardingsphere/elasticjob/cloud/scheduler/mesos/SupportedExtractionType.java |
robustness-copilot_data_483 | /**
* Add a new component to our list of children.
* <p>
*
* @param childName the name under which this item should be recorded
* @param newChild the StateComponent to be stored.
*/
private void addComponent(String childName, StateComponent newChild){
StateComponent existingChild = _children.get(childName);
if (newChild instanceof StateComposite) {
StateComposite newComposite = (StateComposite) newChild;
if (existingChild instanceof StateComposite) {
StateComposite existingComposite = (StateComposite) existingChild;
for (Map.Entry<String, StateComponent> entry : existingComposite._children.entrySet()) {
if (!newComposite._children.containsKey(entry.getKey())) {
newComposite._children.put(entry.getKey(), entry.getValue());
}
}
newComposite.updateEarliestChildExpiryDate(existingComposite.getEarliestChildExpiryDate());
newComposite.updateWhenIShouldExpireDate(existingComposite.getExpiryDate());
}
}
_children.put(childName, newChild);
LOGGER.trace("Child {} now {}", childName, newChild);
} | /modules/dcache-info/src/main/java/org/dcache/services/info/base/StateComposite.java |
robustness-copilot_data_484 | /**
* Method that actually does the work of extracting the molecular formula.
*
* @param mass molecular formula to create from the mass
* @return the filled molecular formulas as IMolecularFormulaSet
*/
public IMolecularFormulaSet generate(double mass){
if (mass <= 0.0) {
logger.error("Proposed mass is not valid: ", mass);
return null;
}
IMolecularFormula minimalMF = MolecularFormulaRangeManipulator.getMinimalFormula(mfRange, builder);
IMolecularFormula maximalMF = MolecularFormulaRangeManipulator.getMaximalFormula(mfRange, builder);
double massMim = MolecularFormulaManipulator.getTotalExactMass(minimalMF) - tolerance;
double massMap = MolecularFormulaManipulator.getTotalExactMass(maximalMF) + tolerance;
if (massMim > mass || massMap < mass) {
logger.error("Proposed mass is out of the range: ", mass);
return null;
}
IMolecularFormulaSet molecularFormulaSet = builder.newInstance(IMolecularFormulaSet.class);
int[][] matrix = this.matrix_Base;
int numberElements = mfRange.getIsotopeCount();
List<IIsotope> isotopes_TO = new ArrayList<IIsotope>();
Iterator<IIsotope> isIt = mfRange.isotopes().iterator();
while (isIt.hasNext()) isotopes_TO.add(isIt.next());
isotopes_TO = orderList(isotopes_TO);
for (int i = 0; i < matrix.length; i++) {
int[] value_In = new int[numberElements];
for (int j = 0; j < numberElements; j++) {
if (matrix[i][j] == 0)
value_In[j] = 0;
else
value_In[j] = 1;
}
int count_E = 0;
ArrayList<Integer> elem_Pos = new ArrayList<Integer>();
for (int j = 0; j < matrix[1].length; j++) if (value_In[j] != 0) {
count_E++;
elem_Pos.add(j);
}
boolean flag = true;
int possChan = 0;
String lastMFString = "";
while (flag) {
boolean flagBreak = false;
for (int j = 0; j < matrix[1].length; j++) {
int min = mfRange.getIsotopeCountMin(isotopes_TO.get(j));
if (value_In[j] == 0)
if (min != 0)
flagBreak = true;
}
if (flagBreak)
break;
int occurence = getMaxOccurence(mass, elem_Pos.get(possChan).intValue(), value_In, isotopes_TO);
if (occurence == 0)
break;
int maxx = mfRange.getIsotopeCountMax(isotopes_TO.get(elem_Pos.get(possChan).intValue()));
int minn = mfRange.getIsotopeCountMin(isotopes_TO.get(elem_Pos.get(possChan).intValue()));
if (occurence < minn | maxx < occurence) {
if (possChan < elem_Pos.size() - 1) {
if (maxx < occurence)
value_In[elem_Pos.get(possChan).intValue()] = maxx;
possChan++;
} else {
boolean foundZ = false;
for (int z = possChan - 1; z >= 0; z--) {
if (value_In[elem_Pos.get(z).intValue()] != 1) {
possChan = z;
foundZ = true;
int newValue = value_In[elem_Pos.get(possChan).intValue()] - 1;
value_In[elem_Pos.get(possChan).intValue()] = newValue;
for (int j = possChan + 1; j < elem_Pos.size(); j++) {
int p = elem_Pos.get(j).intValue();
value_In[p] = 1;
}
possChan++;
break;
}
}
if (!foundZ)
break;
}
continue;
}
value_In[elem_Pos.get(possChan).intValue()] = occurence;
double massT = calculateMassT(isotopes_TO, value_In);
double diff_new = Math.abs(mass - (massT));
if (diff_new < tolerance) {
IMolecularFormula myMF = getFormula(isotopes_TO, value_In);
String newMFString = MolecularFormulaManipulator.getString(myMF);
if (!newMFString.equals(lastMFString)) {
molecularFormulaSet.addMolecularFormula(myMF);
lastMFString = newMFString;
}
}
if (count_E == 1)
break;
if (possChan < elem_Pos.size() - 1) {
possChan++;
} else {
boolean foundZ = false;
for (int z = possChan - 1; z >= 0; z--) {
if (value_In[elem_Pos.get(z).intValue()] != 1) {
possChan = z;
foundZ = true;
int newValue = value_In[elem_Pos.get(possChan).intValue()] - 1;
value_In[elem_Pos.get(possChan).intValue()] = newValue;
for (int j = possChan + 1; j < elem_Pos.size(); j++) {
int p = elem_Pos.get(j).intValue();
value_In[p] = 1;
}
possChan++;
break;
}
}
if (!foundZ)
break;
}
}
}
return returnOrdered(mass, molecularFormulaSet);
} | /legacy/src/main/java/org/openscience/cdk/formula/MassToFormulaTool.java |
robustness-copilot_data_485 | /**
* Removes a particular strand, specified by its name.
*
* @param name name of the strand to remove
*/
public void removeStrand(String name){
if (strands.containsKey(name)) {
Strand strand = (Strand) strands.get(name);
this.remove(strand);
strands.remove(name);
}
} | /base/silent/src/main/java/org/openscience/cdk/silent/BioPolymer.java |
robustness-copilot_data_486 | /**
* Checks whether the query distance constraint matches a target distance.
*
* This method checks whether a query constraint is satisfied by an observed
* distance (represented by a {@link PharmacophoreBond} in the target molecule.
* Note that distance are compared upto 2 decimal places.
*
* @param bond The distance relationship in a target molecule
* @return true if the target distance lies within the range of the query constraint
*/
public boolean matches(IBond bond){
bond = BondRef.deref(bond);
if (bond instanceof PharmacophoreBond) {
PharmacophoreBond pbond = (PharmacophoreBond) bond;
double bondLength = round(pbond.getBondLength(), 2);
return bondLength >= lower && bondLength <= upper;
} else
return false;
} | /tool/pcore/src/main/java/org/openscience/cdk/pharmacophore/PharmacophoreQueryBond.java |
robustness-copilot_data_487 | /**
* Distribute the bonded atoms (neighbours) of an atom such that they fill the
* remaining space around an atom in a geometrically nice way.
* IMPORTANT: This method is not supposed to handle the
* case of one or no place neighbor. In the case of
* one placed neigbor, the chain placement methods
* should be used.
*
*@param atom The atom whose partners are to be placed
*@param placedNeighbours The atoms which are already placed
*@param unplacedNeighbours The partners to be placed
*@param bondLength The standared bond length for the newly placed
* Atoms
*@param sharedAtomsCenter The 2D centre of the placed Atoms
*/
public void distributePartners(IAtom atom, IAtomContainer placedNeighbours, Point2d sharedAtomsCenter, IAtomContainer unplacedNeighbours, double bondLength){
double occupiedAngle = 0;
IAtom[] sortedAtoms = null;
double startAngle = 0.0;
double addAngle = 0.0;
double radius = 0.0;
double remainingAngle = 0.0;
Vector2d sharedAtomsCenterVector = new Vector2d(sharedAtomsCenter);
Vector2d newDirection = new Vector2d(atom.getPoint2d());
Vector2d occupiedDirection = new Vector2d(sharedAtomsCenter);
occupiedDirection.sub(newDirection);
if (Math.abs(occupiedDirection.length()) < 0.001)
occupiedDirection = new Vector2d(0, 1);
logger.debug("distributePartners->occupiedDirection.lenght(): " + occupiedDirection.length());
List<IAtom> atomsToDraw = new ArrayList<IAtom>();
logger.debug("Number of shared atoms: ", placedNeighbours.getAtomCount());
if (placedNeighbours.getAtomCount() == 1) {
logger.debug("Only one neighbour...");
for (int f = 0; f < unplacedNeighbours.getAtomCount(); f++) {
atomsToDraw.add(unplacedNeighbours.getAtom(f));
}
addAngle = Math.PI * 2 / (unplacedNeighbours.getAtomCount() + placedNeighbours.getAtomCount());
IAtom placedAtom = placedNeighbours.getAtom(0);
double xDiff = placedAtom.getPoint2d().x - atom.getPoint2d().x;
double yDiff = placedAtom.getPoint2d().y - atom.getPoint2d().y;
logger.debug("distributePartners->xdiff: " + Math.toDegrees(xDiff));
logger.debug("distributePartners->ydiff: " + Math.toDegrees(yDiff));
startAngle = GeometryUtil.getAngle(xDiff, yDiff);
logger.debug("distributePartners->angle: " + Math.toDegrees(startAngle));
populatePolygonCorners(atomsToDraw, new Point2d(atom.getPoint2d()), startAngle, addAngle, bondLength);
return;
} else if (placedNeighbours.getAtomCount() == 0) {
logger.debug("First atom...");
for (int f = 0; f < unplacedNeighbours.getAtomCount(); f++) {
atomsToDraw.add(unplacedNeighbours.getAtom(f));
}
addAngle = Math.PI * 2.0 / unplacedNeighbours.getAtomCount();
startAngle = 0.0;
populatePolygonCorners(atomsToDraw, new Point2d(atom.getPoint2d()), startAngle, addAngle, bondLength);
return;
}
if (doAngleSnap(atom, placedNeighbours)) {
int numTerminal = 0;
for (IAtom unplaced : unplacedNeighbours.atoms()) if (molecule.getConnectedBondsCount(unplaced) == 1)
numTerminal++;
if (numTerminal == unplacedNeighbours.getAtomCount()) {
final Vector2d a = newVector(placedNeighbours.getAtom(0).getPoint2d(), atom.getPoint2d());
final Vector2d b = newVector(placedNeighbours.getAtom(1).getPoint2d(), atom.getPoint2d());
final double d1 = GeometryUtil.getAngle(a.x, a.y);
final double d2 = GeometryUtil.getAngle(b.x, b.y);
double sweep = a.angle(b);
if (sweep < Math.PI) {
sweep = 2 * Math.PI - sweep;
}
startAngle = d2;
if (d1 > d2 && d1 - d2 < Math.PI || d2 - d1 >= Math.PI) {
startAngle = d1;
}
sweep /= (1 + unplacedNeighbours.getAtomCount());
populatePolygonCorners(StreamSupport.stream(unplacedNeighbours.atoms().spliterator(), false).collect(Collectors.toList()), atom.getPoint2d(), startAngle, sweep, bondLength);
markPlaced(unplacedNeighbours);
return;
} else {
atom.removeProperty(MacroCycleLayout.MACROCYCLE_ATOM_HINT);
}
}
sharedAtomsCenterVector.sub(newDirection);
newDirection = sharedAtomsCenterVector;
newDirection.normalize();
newDirection.scale(bondLength);
newDirection.negate();
logger.debug("distributePartners->newDirection.lenght(): " + newDirection.length());
Point2d distanceMeasure = new Point2d(atom.getPoint2d());
distanceMeasure.add(newDirection);
sortedAtoms = AtomContainerManipulator.getAtomArray(placedNeighbours);
GeometryUtil.sortBy2DDistance(sortedAtoms, distanceMeasure);
Vector2d closestPoint1 = new Vector2d(sortedAtoms[0].getPoint2d());
Vector2d closestPoint2 = new Vector2d(sortedAtoms[1].getPoint2d());
closestPoint1.sub(new Vector2d(atom.getPoint2d()));
closestPoint2.sub(new Vector2d(atom.getPoint2d()));
occupiedAngle = closestPoint1.angle(occupiedDirection);
occupiedAngle += closestPoint2.angle(occupiedDirection);
double angle1 = GeometryUtil.getAngle(sortedAtoms[0].getPoint2d().x - atom.getPoint2d().x, sortedAtoms[0].getPoint2d().y - atom.getPoint2d().y);
double angle2 = GeometryUtil.getAngle(sortedAtoms[1].getPoint2d().x - atom.getPoint2d().x, sortedAtoms[1].getPoint2d().y - atom.getPoint2d().y);
double angle3 = GeometryUtil.getAngle(distanceMeasure.x - atom.getPoint2d().x, distanceMeasure.y - atom.getPoint2d().y);
if (debug) {
try {
logger.debug("distributePartners->sortedAtoms[0]: ", (molecule.indexOf(sortedAtoms[0]) + 1));
logger.debug("distributePartners->sortedAtoms[1]: ", (molecule.indexOf(sortedAtoms[1]) + 1));
logger.debug("distributePartners->angle1: ", Math.toDegrees(angle1));
logger.debug("distributePartners->angle2: ", Math.toDegrees(angle2));
} catch (Exception exc) {
logger.debug(exc);
}
}
IAtom startAtom = null;
if (angle1 > angle3) {
if (angle1 - angle3 < Math.PI) {
startAtom = sortedAtoms[1];
} else {
startAtom = sortedAtoms[0];
}
} else {
if (angle3 - angle1 < Math.PI) {
startAtom = sortedAtoms[0];
} else {
startAtom = sortedAtoms[1];
}
}
remainingAngle = (2 * Math.PI) - occupiedAngle;
addAngle = remainingAngle / (unplacedNeighbours.getAtomCount() + 1);
if (debug) {
try {
logger.debug("distributePartners->startAtom: " + (molecule.indexOf(startAtom) + 1));
logger.debug("distributePartners->remainingAngle: " + Math.toDegrees(remainingAngle));
logger.debug("distributePartners->addAngle: " + Math.toDegrees(addAngle));
logger.debug("distributePartners-> partners.getAtomCount(): " + unplacedNeighbours.getAtomCount());
} catch (Exception exc) {
logger.debug(exc);
}
}
for (int f = 0; f < unplacedNeighbours.getAtomCount(); f++) {
atomsToDraw.add(unplacedNeighbours.getAtom(f));
}
radius = bondLength;
startAngle = GeometryUtil.getAngle(startAtom.getPoint2d().x - atom.getPoint2d().x, startAtom.getPoint2d().y - atom.getPoint2d().y);
logger.debug("Before check: distributePartners->startAngle: " + startAngle);
logger.debug("After check: distributePartners->startAngle: " + startAngle);
populatePolygonCorners(atomsToDraw, new Point2d(atom.getPoint2d()), startAngle, addAngle, radius);
} | /tool/sdg/src/main/java/org/openscience/cdk/layout/AtomPlacer.java |
robustness-copilot_data_488 | /**
* Returns true if the value in the field is required to be DNS-1123 legal.
*
* @param fieldName Name of the field to be checked
* @return true if the value needs to be DNS1123 legal, false otherwise
*/
public static boolean isDns1123Required(String fieldName){
if (fieldName != null) {
for (String dns1123Field : getDns1123Fields()) {
if (dns1123Field.equalsIgnoreCase(fieldName)) {
return true;
}
}
}
return false;
} | /operator/src/main/java/oracle/kubernetes/operator/helpers/LegalNames.java |
robustness-copilot_data_489 | /**
* Removes all trailing zero decimals from the given String, assuming all decimals are zero and
* any zero decimals actually exist.
*
* <p>A {@code null} input String returns {@code null}.
*
* @param str the String to handle, may be null
* @return string without trailing zero decimals
*/
public static String removeZeroDecimal(final String str){
if (Strings.isNullOrEmpty(str)) {
return str;
}
return ZERO_DECIMAL_PATTERN.matcher(str).replaceFirst(EMPTY);
} | /core/src/main/java/tech/tablesaw/util/StringUtils.java |
robustness-copilot_data_490 | /**
* Returns the topology equivalent of the domain configuration, as a map. It may be converted to
* YAML or JSON via an object mapper.
*
* @return a map containing the topology
*/
public Map<String, Object> toTopology(){
Map<String, Object> topology = new HashMap<>();
topology.put("domainValid", "true");
topology.put("domain", createDomainTopology());
return topology;
} | /operator/src/main/java/oracle/kubernetes/operator/wlsconfig/WlsDomainConfig.java |
robustness-copilot_data_491 | /**
* Generate an {@link OpenAPI} model from Jooby class. This method parses class byte code and
* generates an open api model from it. Compilation must be done with debug information and
* parameters name available.
*
* Optionally, the <code>conf/openapi.yaml</code> is used as template and get merged into the
* final model.
*
* @param classname Application class name.
* @return Model.
*/
public OpenAPI generate(@Nonnull String classname){
ClassLoader classLoader = Optional.ofNullable(this.classLoader).orElseGet(getClass()::getClassLoader);
ClassSource source = new ClassSource(classLoader);
RouteParser routes = new RouteParser(metaInf);
ParserContext ctx = new ParserContext(source, TypeFactory.fromJavaName(classname), debug);
List<OperationExt> operations = routes.parse(ctx);
String contextPath = ContextPathParser.parse(ctx);
OpenAPIExt openapi = new OpenAPIExt();
openapi.setSource(Optional.ofNullable(ctx.getMainClass()).orElse(classname));
OpenAPIParser.parse(ctx, openapi);
OpenAPIExt.fromTemplate(basedir, classLoader, templateName).ifPresent(template -> merge(openapi, template));
defaults(classname, contextPath, openapi);
ctx.schemas().forEach(schema -> openapi.schema(schema.getName(), schema));
Map<String, Tag> globalTags = new LinkedHashMap<>();
Paths paths = new Paths();
for (OperationExt operation : operations) {
String pattern = operation.getPattern();
if (!includes(pattern) || excludes(pattern)) {
log.debug("skipping {}", pattern);
continue;
}
Map<String, String> regexMap = new HashMap<>();
Router.pathKeys(pattern, (key, value) -> Optional.ofNullable(value).ifPresent(v -> regexMap.put(key, v)));
if (regexMap.size() > 0) {
for (Map.Entry<String, String> e : regexMap.entrySet()) {
String name = e.getKey();
String regex = e.getValue();
operation.getParameter(name).ifPresent(parameter -> parameter.getSchema().setPattern(regex));
if (regex.equals("\\.*")) {
if (name.equals("*")) {
pattern = pattern.substring(0, pattern.length() - 1) + "{*}";
} else {
pattern = pattern.replace("*" + name, "{" + name + "}");
}
} else {
pattern = pattern.replace(name + ":" + regex, name);
}
}
}
PathItem pathItem = paths.computeIfAbsent(pattern, k -> new PathItem());
pathItem.operation(PathItem.HttpMethod.valueOf(operation.getMethod()), operation);
Optional.ofNullable(operation.getPathSummary()).ifPresent(pathItem::setSummary);
Optional.ofNullable(operation.getPathDescription()).ifPresent(pathItem::setDescription);
operation.getGlobalTags().forEach(tag -> globalTags.put(tag.getName(), tag));
}
globalTags.values().forEach(tag -> {
if (tag.getDescription() != null || tag.getExtensions() != null) {
openapi.addTagsItem(tag);
}
});
openapi.setOperations(operations);
openapi.setPaths(paths);
return openapi;
} | /modules/jooby-openapi/src/main/java/io/jooby/openapi/OpenAPIGenerator.java |
robustness-copilot_data_492 | /**
* Computes the score of a document with respect to a query given a scoring function and an analyzer.
*
* @param reader index reader
* @param docid docid of the document to score
* @param q query
* @param similarity scoring function
* @param analyzer analyzer to use
* @return the score of the document with respect to the query
* @throws IOException if error encountered during query
*/
public static float computeQueryDocumentScoreWithSimilarityAndAnalyzer(IndexReader reader, String docid, String q, Similarity similarity, Analyzer analyzer) throws IOException{
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(similarity);
Query query = new BagOfWordsQueryGenerator().buildQuery(IndexArgs.CONTENTS, analyzer, q);
Query filterQuery = new ConstantScoreQuery(new TermQuery(new Term(IndexArgs.ID, docid)));
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.add(filterQuery, BooleanClause.Occur.MUST);
builder.add(query, BooleanClause.Occur.MUST);
Query finalQuery = builder.build();
TopDocs rs = searcher.search(finalQuery, 1);
return rs.scoreDocs.length == 0 ? 0 : rs.scoreDocs[0].score - 1;
} | /src/main/java/io/anserini/index/IndexReaderUtils.java |
robustness-copilot_data_493 | /**
* Refines the compatibility removing any mappings which have now become
* invalid (since the last mapping). The matrix is refined from the row
* after the current {@code row} - all previous rows are fixed. If when
* refined we find a query vertex has no more candidates left in the target
* we can never reach a feasible matching and refinement is aborted (false
* is returned).
*
* @param row refine from here
* @return match is still feasible
*/
private boolean refine(int row){
int marking = -(row + 1);
boolean changed;
do {
changed = false;
for (int n = row + 1; n < matrix.nRows; n++) {
for (int m = 0; m < matrix.mCols; m++) {
if (matrix.get(n, m) && !verify(n, m)) {
matrix.mark(n, m, marking);
changed = true;
if (!hasCandidate(n))
return false;
}
}
}
} while (changed);
return true;
} | /base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/UllmannState.java |
robustness-copilot_data_494 | /**
* Search and place branches of a chain or ring.
*
*@param chain AtomContainer if atoms in an aliphatic chain or ring system
*/
private void searchAndPlaceBranches(IAtomContainer molecule, IAtomContainer chain, AtomPlacer3D ap3d, AtomTetrahedralLigandPlacer3D atlp3d, AtomPlacer atomPlacer) throws CDKException{
List atoms = null;
IAtomContainer branchAtoms = molecule.getBuilder().newInstance(IAtomContainer.class);
IAtomContainer connectedAtoms = molecule.getBuilder().newInstance(IAtomContainer.class);
for (int i = 0; i < chain.getAtomCount(); i++) {
atoms = molecule.getConnectedAtomsList(chain.getAtom(i));
for (int j = 0; j < atoms.size(); j++) {
IAtom atom = (IAtom) atoms.get(j);
if (!(atom.getSymbol()).equals("H") & !(atom.getFlag(CDKConstants.ISPLACED)) & !(atom.getFlag(CDKConstants.ISINRING))) {
connectedAtoms.add(ap3d.getPlacedHeavyAtoms(molecule, chain.getAtom(i)));
try {
setBranchAtom(molecule, atom, chain.getAtom(i), connectedAtoms, ap3d, atlp3d);
} catch (CDKException ex2) {
logger.error("SearchAndPlaceBranchERROR: Cannot find enough neighbour atoms due to" + ex2.toString());
throw new CDKException("SearchAndPlaceBranchERROR: Cannot find enough neighbour atoms: " + ex2.getMessage(), ex2);
}
branchAtoms.addAtom(atom);
connectedAtoms.removeAllElements();
}
}
}
placeLinearChains3D(molecule, branchAtoms, ap3d, atlp3d, atomPlacer);
} | /tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/ModelBuilder3D.java |
robustness-copilot_data_495 | /**
* Default implementation, just look for "local" IPs. If the database returns a null URL we return false since we don't know it's safe to run the update.
*
* @throws liquibase.exception.DatabaseException
*
*/
public boolean isSafeToRunUpdate() throws DatabaseException{
DatabaseConnection connection = getConnection();
if (connection == null) {
return true;
}
String url = connection.getURL();
if (url == null) {
return false;
}
return (url.contains("localhost")) || (url.contains("127.0.0.1"));
} | /liquibase-core/src/main/java/liquibase/database/AbstractJdbcDatabase.java |
robustness-copilot_data_496 | /**
* Returns a lexicographically sorted map of the [PROPERTY PATH] : [CHECKSUM OF PROPERTIES].
* @param aggregateNodePath the absolute path of the node being aggregated into a checksum
* @param node the node to collect and checksum the properties for
* @param options the checksum generator options
* @return the map of the properties and their checksums
* @throws RepositoryException
*/
protected String generatePropertyChecksums(final String aggregateNodePath, final Node node, final ChecksumGeneratorOptions options) throws RepositoryException, IOException{
SortedMap<String, String> propertyChecksums = new TreeMap<>();
PropertyIterator properties = node.getProperties();
while (properties.hasNext()) {
final Property property = properties.nextProperty();
if (options.getExcludedProperties().contains(property.getName())) {
log.debug("Excluding property: {}", node.getPath() + "/@" + property.getName());
continue;
}
final List<String> checksums = new ArrayList<String>();
final List<Value> values = getPropertyValues(property);
for (final Value value : values) {
if (value.getType() == PropertyType.BINARY) {
checksums.add(getBinaryChecksum(value));
} else {
checksums.add(getStringChecksum(value));
}
}
if (!options.getSortedProperties().contains(property.getName())) {
Collections.sort(checksums);
}
if (log.isDebugEnabled()) {
log.debug("Property: {} ~> {}", getChecksumKey(aggregateNodePath, property.getPath()), StringUtils.join(checksums, ","));
}
propertyChecksums.put(getChecksumKey(aggregateNodePath, property.getPath()), StringUtils.join(checksums, ","));
}
return aggregateChecksums(propertyChecksums);
} | /bundle/src/main/java/com/adobe/acs/commons/analysis/jcrchecksum/impl/ChecksumGeneratorImpl.java |
robustness-copilot_data_497 | /**
* A convenience method for testing the value returned by {@link #getRequiredForDatabase()} against a given database.
* Returns true if the {@link Database#getShortName()} method is contained in the required databases or the
* required database list contains the string "all"
*/
public boolean isRequiredFor(Database database){
return getRequiredForDatabase().contains(ALL) || getRequiredForDatabase().contains(database.getShortName());
} | /liquibase-core/src/main/java/liquibase/change/ChangeParameterMetaData.java |
robustness-copilot_data_498 | /**
* Change the base of the group to the new base <code>newBase</code>.
*
* @param newBase the new base for the group
*/
public void changeBase(Permutation newBase){
PermutationGroup h = new PermutationGroup(newBase);
int firstDiffIndex = base.firstIndexOfDifference(newBase);
for (int j = firstDiffIndex; j < size; j++) {
for (int a = 0; a < size; a++) {
Permutation g = permutations[j][a];
if (g != null) {
h.enter(g);
}
}
}
for (int j = 0; j < firstDiffIndex; j++) {
for (int a = 0; a < size; a++) {
Permutation g = permutations[j][a];
if (g != null) {
int hj = h.base.get(j);
int x = g.get(hj);
h.permutations[j][x] = new Permutation(g);
}
}
}
this.base = new Permutation(h.base);
this.permutations = h.permutations.clone();
} | /tool/group/src/main/java/org/openscience/cdk/group/PermutationGroup.java |
robustness-copilot_data_499 | /**
* Util for converting a String[] into a List of compiled Patterns. Empty/blank strings will be skipped.
* @param values the Strings to convert to patterns.
* @return a List of Patterns
*/
public static List<Pattern> toPatterns(String[] values){
List<Pattern> patterns = new ArrayList<Pattern>();
if (values == null) {
return patterns;
}
for (String value : values) {
if (StringUtils.isNotBlank(value)) {
patterns.add(Pattern.compile(value));
}
}
return patterns;
} | /bundle/src/main/java/com/adobe/acs/commons/util/ParameterUtil.java |
robustness-copilot_data_500 | /**
* Looks at structural containment: whether {@code ra} is part of the
* group's structure. It mostly the same as {@link #contains(edu.harvard.iq.dataverse.engine.command.DataverseRequest)},
* except for logical containment. So if an ExplicitGroup contains {@link AuthenticatedUsers} but not
* a specific {@link AuthenticatedUser} {@code u}, {@code structuralContains(u)}
* would return {@code false} while {@code contains( request(u, ...) )} would return true;
*
* @param ra
* @return {@code true} iff the role assignee is structurally a part of the group.
*/
public boolean structuralContains(RoleAssignee ra){
if (ra instanceof AuthenticatedUser) {
if (containedAuthenticatedUsers.contains((AuthenticatedUser) ra)) {
return true;
}
} else if (ra instanceof ExplicitGroup) {
if (containedExplicitGroups.contains((ExplicitGroup) ra)) {
return true;
}
} else {
if (containedRoleAssignees.contains(ra.getIdentifier())) {
return true;
}
}
for (ExplicitGroup eg : containedExplicitGroups) {
if (eg.structuralContains(ra)) {
return true;
}
}
return false;
} | /src/main/java/edu/harvard/iq/dataverse/authorization/groups/impl/explicit/ExplicitGroup.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.