repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java
HashCodeBuilder.reflectionHashCode
@GwtIncompatible("incompatible method") public static int reflectionHashCode(final Object object, final Collection<String> excludeFields) { """ <p> Uses reflection to build a valid hash code from the fields of {@code object}. </p> <p> This constructor uses two hard coded choices for the constants needed to build a hash code. </p> <p> It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly. </p> <p> Transient members will be not be used, as they are likely derived fields, and not part of the value of the <code>Object</code>. </p> <p> Static fields will not be tested. Superclass fields will be included. If no fields are found to include in the hash code, the result of this method will be constant. </p> @param object the Object to create a <code>hashCode</code> for @param excludeFields Collection of String field names to exclude from use in calculation of hash code @return int hash code @throws IllegalArgumentException if the object is <code>null</code> @see HashCodeExclude """ return reflectionHashCode(object, ReflectionToStringBuilder.toNoNullStringArray(excludeFields)); }
java
@GwtIncompatible("incompatible method") public static int reflectionHashCode(final Object object, final Collection<String> excludeFields) { return reflectionHashCode(object, ReflectionToStringBuilder.toNoNullStringArray(excludeFields)); }
[ "@", "GwtIncompatible", "(", "\"incompatible method\"", ")", "public", "static", "int", "reflectionHashCode", "(", "final", "Object", "object", ",", "final", "Collection", "<", "String", ">", "excludeFields", ")", "{", "return", "reflectionHashCode", "(", "object", ",", "ReflectionToStringBuilder", ".", "toNoNullStringArray", "(", "excludeFields", ")", ")", ";", "}" ]
<p> Uses reflection to build a valid hash code from the fields of {@code object}. </p> <p> This constructor uses two hard coded choices for the constants needed to build a hash code. </p> <p> It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly. </p> <p> Transient members will be not be used, as they are likely derived fields, and not part of the value of the <code>Object</code>. </p> <p> Static fields will not be tested. Superclass fields will be included. If no fields are found to include in the hash code, the result of this method will be constant. </p> @param object the Object to create a <code>hashCode</code> for @param excludeFields Collection of String field names to exclude from use in calculation of hash code @return int hash code @throws IllegalArgumentException if the object is <code>null</code> @see HashCodeExclude
[ "<p", ">", "Uses", "reflection", "to", "build", "a", "valid", "hash", "code", "from", "the", "fields", "of", "{", "@code", "object", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/builder/HashCodeBuilder.java#L453-L456
forge/javaee-descriptors
impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/jobXML10/JobXMLDescriptorImpl.java
JobXMLDescriptorImpl.addNamespace
public JobXMLDescriptor addNamespace(String name, String value) { """ Adds a new namespace @return the current instance of <code>JobXMLDescriptor</code> """ model.attribute(name, value); return this; }
java
public JobXMLDescriptor addNamespace(String name, String value) { model.attribute(name, value); return this; }
[ "public", "JobXMLDescriptor", "addNamespace", "(", "String", "name", ",", "String", "value", ")", "{", "model", ".", "attribute", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds a new namespace @return the current instance of <code>JobXMLDescriptor</code>
[ "Adds", "a", "new", "namespace" ]
train
https://github.com/forge/javaee-descriptors/blob/cb914330a1a0b04bfc1d0f199bd9cde3bbf0b3ed/impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/jobXML10/JobXMLDescriptorImpl.java#L88-L92
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/WriterTableProcessor.java
WriterTableProcessor.readKeysFromSegment
@SneakyThrows(IOException.class) private KeyUpdateCollection readKeysFromSegment(DirectSegmentAccess segment, long firstOffset, long lastOffset, TimeoutTimer timer) { """ Reads all the Keys from the given Segment between the given offsets and indexes them by key. @param segment The InputStream to process. @param firstOffset The first offset in the Segment to start reading Keys at. @param lastOffset The last offset in the Segment to read Keys until. @param timer Timer for the operation. @return A {@link KeyUpdateCollection}s containing the indexed keys. """ KeyUpdateCollection keyUpdates = new KeyUpdateCollection(); try (InputStream input = readFromInMemorySegment(segment, firstOffset, lastOffset, timer)) { long segmentOffset = firstOffset; while (segmentOffset < lastOffset) { segmentOffset += indexSingleKey(input, segmentOffset, keyUpdates); } } return keyUpdates; }
java
@SneakyThrows(IOException.class) private KeyUpdateCollection readKeysFromSegment(DirectSegmentAccess segment, long firstOffset, long lastOffset, TimeoutTimer timer) { KeyUpdateCollection keyUpdates = new KeyUpdateCollection(); try (InputStream input = readFromInMemorySegment(segment, firstOffset, lastOffset, timer)) { long segmentOffset = firstOffset; while (segmentOffset < lastOffset) { segmentOffset += indexSingleKey(input, segmentOffset, keyUpdates); } } return keyUpdates; }
[ "@", "SneakyThrows", "(", "IOException", ".", "class", ")", "private", "KeyUpdateCollection", "readKeysFromSegment", "(", "DirectSegmentAccess", "segment", ",", "long", "firstOffset", ",", "long", "lastOffset", ",", "TimeoutTimer", "timer", ")", "{", "KeyUpdateCollection", "keyUpdates", "=", "new", "KeyUpdateCollection", "(", ")", ";", "try", "(", "InputStream", "input", "=", "readFromInMemorySegment", "(", "segment", ",", "firstOffset", ",", "lastOffset", ",", "timer", ")", ")", "{", "long", "segmentOffset", "=", "firstOffset", ";", "while", "(", "segmentOffset", "<", "lastOffset", ")", "{", "segmentOffset", "+=", "indexSingleKey", "(", "input", ",", "segmentOffset", ",", "keyUpdates", ")", ";", "}", "}", "return", "keyUpdates", ";", "}" ]
Reads all the Keys from the given Segment between the given offsets and indexes them by key. @param segment The InputStream to process. @param firstOffset The first offset in the Segment to start reading Keys at. @param lastOffset The last offset in the Segment to read Keys until. @param timer Timer for the operation. @return A {@link KeyUpdateCollection}s containing the indexed keys.
[ "Reads", "all", "the", "Keys", "from", "the", "given", "Segment", "between", "the", "given", "offsets", "and", "indexes", "them", "by", "key", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/WriterTableProcessor.java#L343-L353
lucee/Lucee
core/src/main/java/lucee/runtime/net/mail/MailClient.java
MailClient.getMails
public Query getMails(String[] messageNumbers, String[] uids, boolean all) throws MessagingException, IOException { """ return all messages from inbox @param messageNumbers all messages with this ids @param uIds all messages with this uids @param withBody also return body @return all messages from inbox @throws MessagingException @throws IOException """ Query qry = new QueryImpl(all ? _fldnew : _flddo, 0, "query"); Folder folder = _store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); try { getMessages(qry, folder, uids, messageNumbers, startrow, maxrows, all); } finally { folder.close(false); } return qry; }
java
public Query getMails(String[] messageNumbers, String[] uids, boolean all) throws MessagingException, IOException { Query qry = new QueryImpl(all ? _fldnew : _flddo, 0, "query"); Folder folder = _store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); try { getMessages(qry, folder, uids, messageNumbers, startrow, maxrows, all); } finally { folder.close(false); } return qry; }
[ "public", "Query", "getMails", "(", "String", "[", "]", "messageNumbers", ",", "String", "[", "]", "uids", ",", "boolean", "all", ")", "throws", "MessagingException", ",", "IOException", "{", "Query", "qry", "=", "new", "QueryImpl", "(", "all", "?", "_fldnew", ":", "_flddo", ",", "0", ",", "\"query\"", ")", ";", "Folder", "folder", "=", "_store", ".", "getFolder", "(", "\"INBOX\"", ")", ";", "folder", ".", "open", "(", "Folder", ".", "READ_ONLY", ")", ";", "try", "{", "getMessages", "(", "qry", ",", "folder", ",", "uids", ",", "messageNumbers", ",", "startrow", ",", "maxrows", ",", "all", ")", ";", "}", "finally", "{", "folder", ".", "close", "(", "false", ")", ";", "}", "return", "qry", ";", "}" ]
return all messages from inbox @param messageNumbers all messages with this ids @param uIds all messages with this uids @param withBody also return body @return all messages from inbox @throws MessagingException @throws IOException
[ "return", "all", "messages", "from", "inbox" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/net/mail/MailClient.java#L309-L320
JodaOrg/joda-time
src/main/java/org/joda/time/format/PeriodFormatter.java
PeriodFormatter.parseInto
public int parseInto(ReadWritablePeriod period, String text, int position) { """ Parses a period from the given text, at the given position, saving the result into the fields of the given ReadWritablePeriod. If the parse succeeds, the return value is the new text position. Note that the parse may succeed without fully reading the text. <p> The parse type of the formatter is not used by this method. <p> If it fails, the return value is negative, but the period may still be modified. To determine the position where the parse failed, apply the one's complement operator (~) on the return value. @param period a period that will be modified @param text text to parse @param position position to start parsing from @return new position, if negative, parse failed. Apply complement operator (~) to get position of failure @throws IllegalArgumentException if any field is out of range """ checkParser(); checkPeriod(period); return getParser().parseInto(period, text, position, iLocale); }
java
public int parseInto(ReadWritablePeriod period, String text, int position) { checkParser(); checkPeriod(period); return getParser().parseInto(period, text, position, iLocale); }
[ "public", "int", "parseInto", "(", "ReadWritablePeriod", "period", ",", "String", "text", ",", "int", "position", ")", "{", "checkParser", "(", ")", ";", "checkPeriod", "(", "period", ")", ";", "return", "getParser", "(", ")", ".", "parseInto", "(", "period", ",", "text", ",", "position", ",", "iLocale", ")", ";", "}" ]
Parses a period from the given text, at the given position, saving the result into the fields of the given ReadWritablePeriod. If the parse succeeds, the return value is the new text position. Note that the parse may succeed without fully reading the text. <p> The parse type of the formatter is not used by this method. <p> If it fails, the return value is negative, but the period may still be modified. To determine the position where the parse failed, apply the one's complement operator (~) on the return value. @param period a period that will be modified @param text text to parse @param position position to start parsing from @return new position, if negative, parse failed. Apply complement operator (~) to get position of failure @throws IllegalArgumentException if any field is out of range
[ "Parses", "a", "period", "from", "the", "given", "text", "at", "the", "given", "position", "saving", "the", "result", "into", "the", "fields", "of", "the", "given", "ReadWritablePeriod", ".", "If", "the", "parse", "succeeds", "the", "return", "value", "is", "the", "new", "text", "position", ".", "Note", "that", "the", "parse", "may", "succeed", "without", "fully", "reading", "the", "text", ".", "<p", ">", "The", "parse", "type", "of", "the", "formatter", "is", "not", "used", "by", "this", "method", ".", "<p", ">", "If", "it", "fails", "the", "return", "value", "is", "negative", "but", "the", "period", "may", "still", "be", "modified", ".", "To", "determine", "the", "position", "where", "the", "parse", "failed", "apply", "the", "one", "s", "complement", "operator", "(", "~", ")", "on", "the", "return", "value", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/PeriodFormatter.java#L291-L296
heroku/heroku.jar
heroku-api/src/main/java/com/heroku/api/HerokuAPI.java
HerokuAPI.restartDyno
public void restartDyno(String appName, String dynoId) { """ Restarts a single dyno @param appName See {@link #listApps} for a list of apps that can be used. @param dynoId the unique identifier of the dyno to restart """ connection.execute(new DynoRestart(appName, dynoId), apiKey); }
java
public void restartDyno(String appName, String dynoId) { connection.execute(new DynoRestart(appName, dynoId), apiKey); }
[ "public", "void", "restartDyno", "(", "String", "appName", ",", "String", "dynoId", ")", "{", "connection", ".", "execute", "(", "new", "DynoRestart", "(", "appName", ",", "dynoId", ")", ",", "apiKey", ")", ";", "}" ]
Restarts a single dyno @param appName See {@link #listApps} for a list of apps that can be used. @param dynoId the unique identifier of the dyno to restart
[ "Restarts", "a", "single", "dyno" ]
train
https://github.com/heroku/heroku.jar/blob/d9e52991293159498c10c498c6f91fcdd637378e/heroku-api/src/main/java/com/heroku/api/HerokuAPI.java#L470-L472
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/MinimizeEnergyPrune.java
MinimizeEnergyPrune.energyRemoveCorner
protected double energyRemoveCorner( int removed , GrowQueue_I32 corners ) { """ Returns the total energy after removing a corner @param removed index of the corner that is being removed @param corners list of corner indexes """ double total = 0; int cornerA = CircularIndex.addOffset(removed, -1 , corners.size()); int cornerB = CircularIndex.addOffset(removed, 1 , corners.size()); total += computeSegmentEnergy(corners, cornerA, cornerB); if( cornerA > cornerB ) { for (int i = cornerB; i < cornerA; i++) total += energySegment[i]; } else { for (int i = 0; i < cornerA; i++) { total += energySegment[i]; } for (int i = cornerB; i < corners.size(); i++) { total += energySegment[i]; } } return total; }
java
protected double energyRemoveCorner( int removed , GrowQueue_I32 corners ) { double total = 0; int cornerA = CircularIndex.addOffset(removed, -1 , corners.size()); int cornerB = CircularIndex.addOffset(removed, 1 , corners.size()); total += computeSegmentEnergy(corners, cornerA, cornerB); if( cornerA > cornerB ) { for (int i = cornerB; i < cornerA; i++) total += energySegment[i]; } else { for (int i = 0; i < cornerA; i++) { total += energySegment[i]; } for (int i = cornerB; i < corners.size(); i++) { total += energySegment[i]; } } return total; }
[ "protected", "double", "energyRemoveCorner", "(", "int", "removed", ",", "GrowQueue_I32", "corners", ")", "{", "double", "total", "=", "0", ";", "int", "cornerA", "=", "CircularIndex", ".", "addOffset", "(", "removed", ",", "-", "1", ",", "corners", ".", "size", "(", ")", ")", ";", "int", "cornerB", "=", "CircularIndex", ".", "addOffset", "(", "removed", ",", "1", ",", "corners", ".", "size", "(", ")", ")", ";", "total", "+=", "computeSegmentEnergy", "(", "corners", ",", "cornerA", ",", "cornerB", ")", ";", "if", "(", "cornerA", ">", "cornerB", ")", "{", "for", "(", "int", "i", "=", "cornerB", ";", "i", "<", "cornerA", ";", "i", "++", ")", "total", "+=", "energySegment", "[", "i", "]", ";", "}", "else", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "cornerA", ";", "i", "++", ")", "{", "total", "+=", "energySegment", "[", "i", "]", ";", "}", "for", "(", "int", "i", "=", "cornerB", ";", "i", "<", "corners", ".", "size", "(", ")", ";", "i", "++", ")", "{", "total", "+=", "energySegment", "[", "i", "]", ";", "}", "}", "return", "total", ";", "}" ]
Returns the total energy after removing a corner @param removed index of the corner that is being removed @param corners list of corner indexes
[ "Returns", "the", "total", "energy", "after", "removing", "a", "corner" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/MinimizeEnergyPrune.java#L184-L205
primefaces/primefaces
src/main/java/org/primefaces/model/timeline/TimelineModel.java
TimelineModel.addAll
public void addAll(Collection<TimelineEvent> events, TimelineUpdater timelineUpdater) { """ Adds all given events to the model with UI update. @param events collection of events to be added @param timelineUpdater TimelineUpdater instance to add the events in UI """ if (events != null && !events.isEmpty()) { for (TimelineEvent event : events) { add(event, timelineUpdater); } } }
java
public void addAll(Collection<TimelineEvent> events, TimelineUpdater timelineUpdater) { if (events != null && !events.isEmpty()) { for (TimelineEvent event : events) { add(event, timelineUpdater); } } }
[ "public", "void", "addAll", "(", "Collection", "<", "TimelineEvent", ">", "events", ",", "TimelineUpdater", "timelineUpdater", ")", "{", "if", "(", "events", "!=", "null", "&&", "!", "events", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "TimelineEvent", "event", ":", "events", ")", "{", "add", "(", "event", ",", "timelineUpdater", ")", ";", "}", "}", "}" ]
Adds all given events to the model with UI update. @param events collection of events to be added @param timelineUpdater TimelineUpdater instance to add the events in UI
[ "Adds", "all", "given", "events", "to", "the", "model", "with", "UI", "update", "." ]
train
https://github.com/primefaces/primefaces/blob/b8cdd5ed395d09826e40e3302d6b14901d3ef4e7/src/main/java/org/primefaces/model/timeline/TimelineModel.java#L133-L139
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParseUtil.java
BpmnParseUtil.parseCamundaOutputParameters
public static void parseCamundaOutputParameters(Element inputOutputElement, IoMapping ioMapping) { """ Parses all output parameters of an input output element and adds them to the {@link IoMapping}. @param inputOutputElement the input output element to process @param ioMapping the input output mapping to add input parameters to @throws BpmnParseException if a output parameter element is malformed """ List<Element> outputParameters = inputOutputElement.elementsNS(BpmnParse.CAMUNDA_BPMN_EXTENSIONS_NS, "outputParameter"); for (Element outputParameterElement : outputParameters) { parseOutputParameterElement(outputParameterElement, ioMapping); } }
java
public static void parseCamundaOutputParameters(Element inputOutputElement, IoMapping ioMapping) { List<Element> outputParameters = inputOutputElement.elementsNS(BpmnParse.CAMUNDA_BPMN_EXTENSIONS_NS, "outputParameter"); for (Element outputParameterElement : outputParameters) { parseOutputParameterElement(outputParameterElement, ioMapping); } }
[ "public", "static", "void", "parseCamundaOutputParameters", "(", "Element", "inputOutputElement", ",", "IoMapping", "ioMapping", ")", "{", "List", "<", "Element", ">", "outputParameters", "=", "inputOutputElement", ".", "elementsNS", "(", "BpmnParse", ".", "CAMUNDA_BPMN_EXTENSIONS_NS", ",", "\"outputParameter\"", ")", ";", "for", "(", "Element", "outputParameterElement", ":", "outputParameters", ")", "{", "parseOutputParameterElement", "(", "outputParameterElement", ",", "ioMapping", ")", ";", "}", "}" ]
Parses all output parameters of an input output element and adds them to the {@link IoMapping}. @param inputOutputElement the input output element to process @param ioMapping the input output mapping to add input parameters to @throws BpmnParseException if a output parameter element is malformed
[ "Parses", "all", "output", "parameters", "of", "an", "input", "output", "element", "and", "adds", "them", "to", "the", "{", "@link", "IoMapping", "}", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/parser/BpmnParseUtil.java#L103-L108
iig-uni-freiburg/SEWOL
src/de/uni/freiburg/iig/telematik/sewol/log/DULogEntry.java
DULogEntry.setDataUsageFor
public boolean setDataUsageFor(DataAttribute attribute, Set<DataUsage> dataUsage) throws ParameterException, LockingException { """ Sets the data usage for a given attribute. @param attribute The attribute (data element) for which the usage is specified. @param dataUsage The usage of the data element specified by the given attribute. @return <code>true</code> if the data usage for the given attribute was modified;<br> <code>false</code> otherwise. @throws ParameterException if the given attribute is <code>null</code> or data usage is invalid (<code>null</code> or empty). @throws LockingException if the corresponding field is locked <br> and the given data usage is not identical to the current one. """ Validate.notNull(attribute); Validate.notNull(dataUsage); Validate.notEmpty(dataUsage); if (isFieldLocked(EntryField.DATA)) { if (!(this.dataUsage.containsKey(attribute) && this.dataUsage.get(attribute).equals(dataUsage))) { throw new LockingException(EntryField.DATA); } return false; } else { this.dataUsage.put(attribute, dataUsage); return true; } }
java
public boolean setDataUsageFor(DataAttribute attribute, Set<DataUsage> dataUsage) throws ParameterException, LockingException { Validate.notNull(attribute); Validate.notNull(dataUsage); Validate.notEmpty(dataUsage); if (isFieldLocked(EntryField.DATA)) { if (!(this.dataUsage.containsKey(attribute) && this.dataUsage.get(attribute).equals(dataUsage))) { throw new LockingException(EntryField.DATA); } return false; } else { this.dataUsage.put(attribute, dataUsage); return true; } }
[ "public", "boolean", "setDataUsageFor", "(", "DataAttribute", "attribute", ",", "Set", "<", "DataUsage", ">", "dataUsage", ")", "throws", "ParameterException", ",", "LockingException", "{", "Validate", ".", "notNull", "(", "attribute", ")", ";", "Validate", ".", "notNull", "(", "dataUsage", ")", ";", "Validate", ".", "notEmpty", "(", "dataUsage", ")", ";", "if", "(", "isFieldLocked", "(", "EntryField", ".", "DATA", ")", ")", "{", "if", "(", "!", "(", "this", ".", "dataUsage", ".", "containsKey", "(", "attribute", ")", "&&", "this", ".", "dataUsage", ".", "get", "(", "attribute", ")", ".", "equals", "(", "dataUsage", ")", ")", ")", "{", "throw", "new", "LockingException", "(", "EntryField", ".", "DATA", ")", ";", "}", "return", "false", ";", "}", "else", "{", "this", ".", "dataUsage", ".", "put", "(", "attribute", ",", "dataUsage", ")", ";", "return", "true", ";", "}", "}" ]
Sets the data usage for a given attribute. @param attribute The attribute (data element) for which the usage is specified. @param dataUsage The usage of the data element specified by the given attribute. @return <code>true</code> if the data usage for the given attribute was modified;<br> <code>false</code> otherwise. @throws ParameterException if the given attribute is <code>null</code> or data usage is invalid (<code>null</code> or empty). @throws LockingException if the corresponding field is locked <br> and the given data usage is not identical to the current one.
[ "Sets", "the", "data", "usage", "for", "a", "given", "attribute", "." ]
train
https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/src/de/uni/freiburg/iig/telematik/sewol/log/DULogEntry.java#L126-L140
lessthanoptimal/BoofCV
main/boofcv-types/src/main/java/boofcv/struct/convolve/Kernel2D_S32.java
Kernel2D_S32.wrap
public static Kernel2D_S32 wrap(int data[], int width, int offset) { """ Creates a kernel whose elements are the specified data array and has the specified width. @param data The array who will be the kernel's data. Reference is saved. @param width The kernel's width. @param offset Kernel origin's offset from element 0. @return A new kernel. """ if (width % 2 == 0 && width <= 0 && width * width > data.length) throw new IllegalArgumentException("invalid width"); Kernel2D_S32 ret = new Kernel2D_S32(); ret.data = data; ret.width = width; ret.offset = offset; return ret; }
java
public static Kernel2D_S32 wrap(int data[], int width, int offset) { if (width % 2 == 0 && width <= 0 && width * width > data.length) throw new IllegalArgumentException("invalid width"); Kernel2D_S32 ret = new Kernel2D_S32(); ret.data = data; ret.width = width; ret.offset = offset; return ret; }
[ "public", "static", "Kernel2D_S32", "wrap", "(", "int", "data", "[", "]", ",", "int", "width", ",", "int", "offset", ")", "{", "if", "(", "width", "%", "2", "==", "0", "&&", "width", "<=", "0", "&&", "width", "*", "width", ">", "data", ".", "length", ")", "throw", "new", "IllegalArgumentException", "(", "\"invalid width\"", ")", ";", "Kernel2D_S32", "ret", "=", "new", "Kernel2D_S32", "(", ")", ";", "ret", ".", "data", "=", "data", ";", "ret", ".", "width", "=", "width", ";", "ret", ".", "offset", "=", "offset", ";", "return", "ret", ";", "}" ]
Creates a kernel whose elements are the specified data array and has the specified width. @param data The array who will be the kernel's data. Reference is saved. @param width The kernel's width. @param offset Kernel origin's offset from element 0. @return A new kernel.
[ "Creates", "a", "kernel", "whose", "elements", "are", "the", "specified", "data", "array", "and", "has", "the", "specified", "width", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-types/src/main/java/boofcv/struct/convolve/Kernel2D_S32.java#L87-L97
jenkinsci/jenkins
core/src/main/java/hudson/Util.java
Util.isDescendant
public static boolean isDescendant(File forParent, File potentialChild) throws IOException { """ A check if a file path is a descendant of a parent path @param forParent the parent the child should be a descendant of @param potentialChild the path to check @return true if so @throws IOException for invalid paths @since 2.80 @see InvalidPathException """ Path child = fileToPath(potentialChild.getAbsoluteFile()).normalize(); Path parent = fileToPath(forParent.getAbsoluteFile()).normalize(); return child.startsWith(parent); }
java
public static boolean isDescendant(File forParent, File potentialChild) throws IOException { Path child = fileToPath(potentialChild.getAbsoluteFile()).normalize(); Path parent = fileToPath(forParent.getAbsoluteFile()).normalize(); return child.startsWith(parent); }
[ "public", "static", "boolean", "isDescendant", "(", "File", "forParent", ",", "File", "potentialChild", ")", "throws", "IOException", "{", "Path", "child", "=", "fileToPath", "(", "potentialChild", ".", "getAbsoluteFile", "(", ")", ")", ".", "normalize", "(", ")", ";", "Path", "parent", "=", "fileToPath", "(", "forParent", ".", "getAbsoluteFile", "(", ")", ")", ".", "normalize", "(", ")", ";", "return", "child", ".", "startsWith", "(", "parent", ")", ";", "}" ]
A check if a file path is a descendant of a parent path @param forParent the parent the child should be a descendant of @param potentialChild the path to check @return true if so @throws IOException for invalid paths @since 2.80 @see InvalidPathException
[ "A", "check", "if", "a", "file", "path", "is", "a", "descendant", "of", "a", "parent", "path" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/Util.java#L375-L379
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java
ExamplesUtil.generateStringExample
public static String generateStringExample(String format, List<String> enumValues) { """ Generates examples for string properties or parameters with given format @param format the format of the string property @param enumValues the enum values @return example """ if (enumValues == null || enumValues.isEmpty()) { if (format == null) { return "string"; } else { switch (format) { case "byte": return "Ynl0ZQ=="; case "date": return "1970-01-01"; case "date-time": return "1970-01-01T00:00:00Z"; case "email": return "[email protected]"; case "password": return "secret"; case "uuid": return "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"; default: return "string"; } } } else { return enumValues.get(0); } }
java
public static String generateStringExample(String format, List<String> enumValues) { if (enumValues == null || enumValues.isEmpty()) { if (format == null) { return "string"; } else { switch (format) { case "byte": return "Ynl0ZQ=="; case "date": return "1970-01-01"; case "date-time": return "1970-01-01T00:00:00Z"; case "email": return "[email protected]"; case "password": return "secret"; case "uuid": return "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"; default: return "string"; } } } else { return enumValues.get(0); } }
[ "public", "static", "String", "generateStringExample", "(", "String", "format", ",", "List", "<", "String", ">", "enumValues", ")", "{", "if", "(", "enumValues", "==", "null", "||", "enumValues", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "format", "==", "null", ")", "{", "return", "\"string\"", ";", "}", "else", "{", "switch", "(", "format", ")", "{", "case", "\"byte\"", ":", "return", "\"Ynl0ZQ==\"", ";", "case", "\"date\"", ":", "return", "\"1970-01-01\"", ";", "case", "\"date-time\"", ":", "return", "\"1970-01-01T00:00:00Z\"", ";", "case", "\"email\"", ":", "return", "\"[email protected]\"", ";", "case", "\"password\"", ":", "return", "\"secret\"", ";", "case", "\"uuid\"", ":", "return", "\"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"", ";", "default", ":", "return", "\"string\"", ";", "}", "}", "}", "else", "{", "return", "enumValues", ".", "get", "(", "0", ")", ";", "}", "}" ]
Generates examples for string properties or parameters with given format @param format the format of the string property @param enumValues the enum values @return example
[ "Generates", "examples", "for", "string", "properties", "or", "parameters", "with", "given", "format" ]
train
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/utils/ExamplesUtil.java#L373-L398
Syncleus/aparapi
src/main/java/com/aparapi/internal/model/ClassModel.java
ClassModel.getMethodModel
public MethodModel getMethodModel(String _name, String _signature) throws AparapiException { """ Create a MethodModel for a given method name and signature. @param _name @param _signature @return @throws AparapiException """ if (CacheEnabler.areCachesEnabled()) return methodModelCache.computeIfAbsent(MethodKey.of(_name, _signature)); else { final ClassModelMethod method = getMethod(_name, _signature); return new MethodModel(method); } }
java
public MethodModel getMethodModel(String _name, String _signature) throws AparapiException { if (CacheEnabler.areCachesEnabled()) return methodModelCache.computeIfAbsent(MethodKey.of(_name, _signature)); else { final ClassModelMethod method = getMethod(_name, _signature); return new MethodModel(method); } }
[ "public", "MethodModel", "getMethodModel", "(", "String", "_name", ",", "String", "_signature", ")", "throws", "AparapiException", "{", "if", "(", "CacheEnabler", ".", "areCachesEnabled", "(", ")", ")", "return", "methodModelCache", ".", "computeIfAbsent", "(", "MethodKey", ".", "of", "(", "_name", ",", "_signature", ")", ")", ";", "else", "{", "final", "ClassModelMethod", "method", "=", "getMethod", "(", "_name", ",", "_signature", ")", ";", "return", "new", "MethodModel", "(", "method", ")", ";", "}", "}" ]
Create a MethodModel for a given method name and signature. @param _name @param _signature @return @throws AparapiException
[ "Create", "a", "MethodModel", "for", "a", "given", "method", "name", "and", "signature", "." ]
train
https://github.com/Syncleus/aparapi/blob/6d5892c8e69854b3968c541023de37cf4762bd24/src/main/java/com/aparapi/internal/model/ClassModel.java#L2993-L3000
quattor/pan
panc/src/main/java/org/quattor/pan/dml/data/AbstractElement.java
AbstractElement.rput
public void rput(Term[] terms, int index, Element value) throws InvalidTermException { """ Add the given child to this resource, creating intermediate resources as necessary. If this Element is not a resource, then this will throw an InvalidTermException. The default implementation of this method throws such an exception. This resource must be a writable resource, otherwise an exception will be thrown. @throws org.quattor.pan.exceptions.InvalidTermException thrown if an trying to dereference a list with a key or a hash with an index """ throw new EvaluationException(MessageUtils.format(MSG_CANNOT_ADD_CHILD, this.getTypeAsString())); }
java
public void rput(Term[] terms, int index, Element value) throws InvalidTermException { throw new EvaluationException(MessageUtils.format(MSG_CANNOT_ADD_CHILD, this.getTypeAsString())); }
[ "public", "void", "rput", "(", "Term", "[", "]", "terms", ",", "int", "index", ",", "Element", "value", ")", "throws", "InvalidTermException", "{", "throw", "new", "EvaluationException", "(", "MessageUtils", ".", "format", "(", "MSG_CANNOT_ADD_CHILD", ",", "this", ".", "getTypeAsString", "(", ")", ")", ")", ";", "}" ]
Add the given child to this resource, creating intermediate resources as necessary. If this Element is not a resource, then this will throw an InvalidTermException. The default implementation of this method throws such an exception. This resource must be a writable resource, otherwise an exception will be thrown. @throws org.quattor.pan.exceptions.InvalidTermException thrown if an trying to dereference a list with a key or a hash with an index
[ "Add", "the", "given", "child", "to", "this", "resource", "creating", "intermediate", "resources", "as", "necessary", ".", "If", "this", "Element", "is", "not", "a", "resource", "then", "this", "will", "throw", "an", "InvalidTermException", ".", "The", "default", "implementation", "of", "this", "method", "throws", "such", "an", "exception", ".", "This", "resource", "must", "be", "a", "writable", "resource", "otherwise", "an", "exception", "will", "be", "thrown", "." ]
train
https://github.com/quattor/pan/blob/009934a603dd0c08d3fa4bb7d9389c380a916f54/panc/src/main/java/org/quattor/pan/dml/data/AbstractElement.java#L257-L261
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/TmdbTV.java
TmdbTV.getTVAlternativeTitles
public ResultList<AlternativeTitle> getTVAlternativeTitles(int tvID) throws MovieDbException { """ Get the alternative titles for a specific show ID. @param tvID @return @throws com.omertron.themoviedbapi.MovieDbException """ TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); URL url = new ApiUrl(apiKey, MethodBase.TV).subMethod(MethodSub.ALT_TITLES).buildUrl(parameters); WrapperGenericList<AlternativeTitle> wrapper = processWrapper(getTypeReference(AlternativeTitle.class), url, "alternative titles"); return wrapper.getResultsList(); }
java
public ResultList<AlternativeTitle> getTVAlternativeTitles(int tvID) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); URL url = new ApiUrl(apiKey, MethodBase.TV).subMethod(MethodSub.ALT_TITLES).buildUrl(parameters); WrapperGenericList<AlternativeTitle> wrapper = processWrapper(getTypeReference(AlternativeTitle.class), url, "alternative titles"); return wrapper.getResultsList(); }
[ "public", "ResultList", "<", "AlternativeTitle", ">", "getTVAlternativeTitles", "(", "int", "tvID", ")", "throws", "MovieDbException", "{", "TmdbParameters", "parameters", "=", "new", "TmdbParameters", "(", ")", ";", "parameters", ".", "add", "(", "Param", ".", "ID", ",", "tvID", ")", ";", "URL", "url", "=", "new", "ApiUrl", "(", "apiKey", ",", "MethodBase", ".", "TV", ")", ".", "subMethod", "(", "MethodSub", ".", "ALT_TITLES", ")", ".", "buildUrl", "(", "parameters", ")", ";", "WrapperGenericList", "<", "AlternativeTitle", ">", "wrapper", "=", "processWrapper", "(", "getTypeReference", "(", "AlternativeTitle", ".", "class", ")", ",", "url", ",", "\"alternative titles\"", ")", ";", "return", "wrapper", ".", "getResultsList", "(", ")", ";", "}" ]
Get the alternative titles for a specific show ID. @param tvID @return @throws com.omertron.themoviedbapi.MovieDbException
[ "Get", "the", "alternative", "titles", "for", "a", "specific", "show", "ID", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbTV.java#L130-L137
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/core/model/Properties.java
Properties.putMapEntry
public <K, V> void putMapEntry(PropertyMapKey<K, V> property, K key, V value) { """ Insert the value to the map to which the specified property key is mapped. If this properties contains no mapping for the property key, the value insert to a new map witch is associate the the specified property key. @param <K> the type of keys maintained by the map @param <V> the type of mapped values @param property the property key whose associated list is to be added @param value the value to be appended to list """ Map<K, V> map = get(property); if (!property.allowsOverwrite() && map.containsKey(key)) { throw new ProcessEngineException("Cannot overwrite property key " + key + ". Key already exists"); } map.put(key, value); if (!contains(property)) { set(property, map); } }
java
public <K, V> void putMapEntry(PropertyMapKey<K, V> property, K key, V value) { Map<K, V> map = get(property); if (!property.allowsOverwrite() && map.containsKey(key)) { throw new ProcessEngineException("Cannot overwrite property key " + key + ". Key already exists"); } map.put(key, value); if (!contains(property)) { set(property, map); } }
[ "public", "<", "K", ",", "V", ">", "void", "putMapEntry", "(", "PropertyMapKey", "<", "K", ",", "V", ">", "property", ",", "K", "key", ",", "V", "value", ")", "{", "Map", "<", "K", ",", "V", ">", "map", "=", "get", "(", "property", ")", ";", "if", "(", "!", "property", ".", "allowsOverwrite", "(", ")", "&&", "map", ".", "containsKey", "(", "key", ")", ")", "{", "throw", "new", "ProcessEngineException", "(", "\"Cannot overwrite property key \"", "+", "key", "+", "\". Key already exists\"", ")", ";", "}", "map", ".", "put", "(", "key", ",", "value", ")", ";", "if", "(", "!", "contains", "(", "property", ")", ")", "{", "set", "(", "property", ",", "map", ")", ";", "}", "}" ]
Insert the value to the map to which the specified property key is mapped. If this properties contains no mapping for the property key, the value insert to a new map witch is associate the the specified property key. @param <K> the type of keys maintained by the map @param <V> the type of mapped values @param property the property key whose associated list is to be added @param value the value to be appended to list
[ "Insert", "the", "value", "to", "the", "map", "to", "which", "the", "specified", "property", "key", "is", "mapped", ".", "If", "this", "properties", "contains", "no", "mapping", "for", "the", "property", "key", "the", "value", "insert", "to", "a", "new", "map", "witch", "is", "associate", "the", "the", "specified", "property", "key", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/core/model/Properties.java#L183-L195
iipc/openwayback
wayback-core/src/main/java/org/archive/wayback/util/bdb/BDBMap.java
BDBMap.get
public String get(String keyStr) { """ retrieve the value assoicated with keyStr from persistant storage @param keyStr @return String value associated with key, or null if no key is found or an error occurs """ String result = null; try { DatabaseEntry key = new DatabaseEntry(keyStr.getBytes("UTF-8")); DatabaseEntry data = new DatabaseEntry(); if (db.get(null, key, data, LockMode.DEFAULT) == OperationStatus.SUCCESS) { byte[] bytes = data.getData(); result = new String(bytes, "UTF-8"); } } catch (DatabaseException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
java
public String get(String keyStr) { String result = null; try { DatabaseEntry key = new DatabaseEntry(keyStr.getBytes("UTF-8")); DatabaseEntry data = new DatabaseEntry(); if (db.get(null, key, data, LockMode.DEFAULT) == OperationStatus.SUCCESS) { byte[] bytes = data.getData(); result = new String(bytes, "UTF-8"); } } catch (DatabaseException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
[ "public", "String", "get", "(", "String", "keyStr", ")", "{", "String", "result", "=", "null", ";", "try", "{", "DatabaseEntry", "key", "=", "new", "DatabaseEntry", "(", "keyStr", ".", "getBytes", "(", "\"UTF-8\"", ")", ")", ";", "DatabaseEntry", "data", "=", "new", "DatabaseEntry", "(", ")", ";", "if", "(", "db", ".", "get", "(", "null", ",", "key", ",", "data", ",", "LockMode", ".", "DEFAULT", ")", "==", "OperationStatus", ".", "SUCCESS", ")", "{", "byte", "[", "]", "bytes", "=", "data", ".", "getData", "(", ")", ";", "result", "=", "new", "String", "(", "bytes", ",", "\"UTF-8\"", ")", ";", "}", "}", "catch", "(", "DatabaseException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "result", ";", "}" ]
retrieve the value assoicated with keyStr from persistant storage @param keyStr @return String value associated with key, or null if no key is found or an error occurs
[ "retrieve", "the", "value", "assoicated", "with", "keyStr", "from", "persistant", "storage" ]
train
https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/util/bdb/BDBMap.java#L109-L126
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/servo/impl/MaestroServoProvider.java
MaestroServoProvider.getServoDriver
public synchronized ServoDriver getServoDriver(Pin servoPin) throws IOException { """ Returns new instance of {@link MaestroServoDriver}. @param servoPin servo pin. @return instance of {@link MaestroServoDriver}. """ List<Pin> servoPins = getDefinedServoPins(); int index = servoPins.indexOf(servoPin); if (index < 0) { throw new IOException("Servo driver cannot drive pin " + servoPin); } MaestroServoDriver driver = servoDrivers.get(servoPin); if (driver == null) { driver = new MaestroServoDriver(this, servoPin); servoDrivers.put(servoPin, driver); } return driver; }
java
public synchronized ServoDriver getServoDriver(Pin servoPin) throws IOException { List<Pin> servoPins = getDefinedServoPins(); int index = servoPins.indexOf(servoPin); if (index < 0) { throw new IOException("Servo driver cannot drive pin " + servoPin); } MaestroServoDriver driver = servoDrivers.get(servoPin); if (driver == null) { driver = new MaestroServoDriver(this, servoPin); servoDrivers.put(servoPin, driver); } return driver; }
[ "public", "synchronized", "ServoDriver", "getServoDriver", "(", "Pin", "servoPin", ")", "throws", "IOException", "{", "List", "<", "Pin", ">", "servoPins", "=", "getDefinedServoPins", "(", ")", ";", "int", "index", "=", "servoPins", ".", "indexOf", "(", "servoPin", ")", ";", "if", "(", "index", "<", "0", ")", "{", "throw", "new", "IOException", "(", "\"Servo driver cannot drive pin \"", "+", "servoPin", ")", ";", "}", "MaestroServoDriver", "driver", "=", "servoDrivers", ".", "get", "(", "servoPin", ")", ";", "if", "(", "driver", "==", "null", ")", "{", "driver", "=", "new", "MaestroServoDriver", "(", "this", ",", "servoPin", ")", ";", "servoDrivers", ".", "put", "(", "servoPin", ",", "driver", ")", ";", "}", "return", "driver", ";", "}" ]
Returns new instance of {@link MaestroServoDriver}. @param servoPin servo pin. @return instance of {@link MaestroServoDriver}.
[ "Returns", "new", "instance", "of", "{", "@link", "MaestroServoDriver", "}", "." ]
train
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/servo/impl/MaestroServoProvider.java#L147-L161
yanzhenjie/AndServer
api/src/main/java/com/yanzhenjie/andserver/util/StringUtils.java
StringUtils.startsWithIgnoreCase
public static boolean startsWithIgnoreCase(String str, String prefix) { """ Test if the given {@code String} starts with the specified prefix, ignoring upper/lower case. @param str the {@code String} to check. @param prefix the prefix to look for. """ return (str != null && prefix != null && str.length() >= prefix.length() && str.regionMatches(true, 0, prefix, 0, prefix.length())); }
java
public static boolean startsWithIgnoreCase(String str, String prefix) { return (str != null && prefix != null && str.length() >= prefix.length() && str.regionMatches(true, 0, prefix, 0, prefix.length())); }
[ "public", "static", "boolean", "startsWithIgnoreCase", "(", "String", "str", ",", "String", "prefix", ")", "{", "return", "(", "str", "!=", "null", "&&", "prefix", "!=", "null", "&&", "str", ".", "length", "(", ")", ">=", "prefix", ".", "length", "(", ")", "&&", "str", ".", "regionMatches", "(", "true", ",", "0", ",", "prefix", ",", "0", ",", "prefix", ".", "length", "(", ")", ")", ")", ";", "}" ]
Test if the given {@code String} starts with the specified prefix, ignoring upper/lower case. @param str the {@code String} to check. @param prefix the prefix to look for.
[ "Test", "if", "the", "given", "{", "@code", "String", "}", "starts", "with", "the", "specified", "prefix", "ignoring", "upper", "/", "lower", "case", "." ]
train
https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/api/src/main/java/com/yanzhenjie/andserver/util/StringUtils.java#L296-L299
DataArt/CalculationEngine
calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DataSetConverters.java
DataSetConverters.toXlsxFile
static OutputStream toXlsxFile(final IDataSet dataSet, final InputStream formatting) { """ Converts {@link IDataSet} to {@link Workbook}, then writes this Workbook to new {@link ByteArrayOutputStream}. Middle-state {@link Workbook} is created from @param formatting. """ ByteArrayOutputStream xlsx = new ByteArrayOutputStream(); try { toWorkbook(dataSet, ConverterUtils.newWorkbook(formatting)).write(xlsx); } catch (IOException e) { throw new CalculationEngineException(e); } return xlsx; }
java
static OutputStream toXlsxFile(final IDataSet dataSet, final InputStream formatting) { ByteArrayOutputStream xlsx = new ByteArrayOutputStream(); try { toWorkbook(dataSet, ConverterUtils.newWorkbook(formatting)).write(xlsx); } catch (IOException e) { throw new CalculationEngineException(e); } return xlsx; }
[ "static", "OutputStream", "toXlsxFile", "(", "final", "IDataSet", "dataSet", ",", "final", "InputStream", "formatting", ")", "{", "ByteArrayOutputStream", "xlsx", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "try", "{", "toWorkbook", "(", "dataSet", ",", "ConverterUtils", ".", "newWorkbook", "(", "formatting", ")", ")", ".", "write", "(", "xlsx", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "CalculationEngineException", "(", "e", ")", ";", "}", "return", "xlsx", ";", "}" ]
Converts {@link IDataSet} to {@link Workbook}, then writes this Workbook to new {@link ByteArrayOutputStream}. Middle-state {@link Workbook} is created from @param formatting.
[ "Converts", "{" ]
train
https://github.com/DataArt/CalculationEngine/blob/34ce1d9c1f9b57a502906b274311d28580b134e5/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DataSetConverters.java#L115-L122
mapsforge/mapsforge
mapsforge-map-reader/src/main/java/org/mapsforge/map/reader/MapFile.java
MapFile.readLabels
@Override public MapReadResult readLabels(Tile upperLeft, Tile lowerRight) { """ Reads data for an area defined by the tile in the upper left and the tile in the lower right corner. Precondition: upperLeft.tileX <= lowerRight.tileX && upperLeft.tileY <= lowerRight.tileY @param upperLeft tile that defines the upper left corner of the requested area. @param lowerRight tile that defines the lower right corner of the requested area. @return map data for the tile. """ return readMapData(upperLeft, lowerRight, Selector.LABELS); }
java
@Override public MapReadResult readLabels(Tile upperLeft, Tile lowerRight) { return readMapData(upperLeft, lowerRight, Selector.LABELS); }
[ "@", "Override", "public", "MapReadResult", "readLabels", "(", "Tile", "upperLeft", ",", "Tile", "lowerRight", ")", "{", "return", "readMapData", "(", "upperLeft", ",", "lowerRight", ",", "Selector", ".", "LABELS", ")", ";", "}" ]
Reads data for an area defined by the tile in the upper left and the tile in the lower right corner. Precondition: upperLeft.tileX <= lowerRight.tileX && upperLeft.tileY <= lowerRight.tileY @param upperLeft tile that defines the upper left corner of the requested area. @param lowerRight tile that defines the lower right corner of the requested area. @return map data for the tile.
[ "Reads", "data", "for", "an", "area", "defined", "by", "the", "tile", "in", "the", "upper", "left", "and", "the", "tile", "in", "the", "lower", "right", "corner", ".", "Precondition", ":", "upperLeft", ".", "tileX", "<", "=", "lowerRight", ".", "tileX", "&&", "upperLeft", ".", "tileY", "<", "=", "lowerRight", ".", "tileY" ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-reader/src/main/java/org/mapsforge/map/reader/MapFile.java#L851-L854
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMaster.java
JobMaster.tryRestoreExecutionGraphFromSavepoint
private void tryRestoreExecutionGraphFromSavepoint(ExecutionGraph executionGraphToRestore, SavepointRestoreSettings savepointRestoreSettings) throws Exception { """ Tries to restore the given {@link ExecutionGraph} from the provided {@link SavepointRestoreSettings}. @param executionGraphToRestore {@link ExecutionGraph} which is supposed to be restored @param savepointRestoreSettings {@link SavepointRestoreSettings} containing information about the savepoint to restore from @throws Exception if the {@link ExecutionGraph} could not be restored """ if (savepointRestoreSettings.restoreSavepoint()) { final CheckpointCoordinator checkpointCoordinator = executionGraphToRestore.getCheckpointCoordinator(); if (checkpointCoordinator != null) { checkpointCoordinator.restoreSavepoint( savepointRestoreSettings.getRestorePath(), savepointRestoreSettings.allowNonRestoredState(), executionGraphToRestore.getAllVertices(), userCodeLoader); } } }
java
private void tryRestoreExecutionGraphFromSavepoint(ExecutionGraph executionGraphToRestore, SavepointRestoreSettings savepointRestoreSettings) throws Exception { if (savepointRestoreSettings.restoreSavepoint()) { final CheckpointCoordinator checkpointCoordinator = executionGraphToRestore.getCheckpointCoordinator(); if (checkpointCoordinator != null) { checkpointCoordinator.restoreSavepoint( savepointRestoreSettings.getRestorePath(), savepointRestoreSettings.allowNonRestoredState(), executionGraphToRestore.getAllVertices(), userCodeLoader); } } }
[ "private", "void", "tryRestoreExecutionGraphFromSavepoint", "(", "ExecutionGraph", "executionGraphToRestore", ",", "SavepointRestoreSettings", "savepointRestoreSettings", ")", "throws", "Exception", "{", "if", "(", "savepointRestoreSettings", ".", "restoreSavepoint", "(", ")", ")", "{", "final", "CheckpointCoordinator", "checkpointCoordinator", "=", "executionGraphToRestore", ".", "getCheckpointCoordinator", "(", ")", ";", "if", "(", "checkpointCoordinator", "!=", "null", ")", "{", "checkpointCoordinator", ".", "restoreSavepoint", "(", "savepointRestoreSettings", ".", "getRestorePath", "(", ")", ",", "savepointRestoreSettings", ".", "allowNonRestoredState", "(", ")", ",", "executionGraphToRestore", ".", "getAllVertices", "(", ")", ",", "userCodeLoader", ")", ";", "}", "}", "}" ]
Tries to restore the given {@link ExecutionGraph} from the provided {@link SavepointRestoreSettings}. @param executionGraphToRestore {@link ExecutionGraph} which is supposed to be restored @param savepointRestoreSettings {@link SavepointRestoreSettings} containing information about the savepoint to restore from @throws Exception if the {@link ExecutionGraph} could not be restored
[ "Tries", "to", "restore", "the", "given", "{", "@link", "ExecutionGraph", "}", "from", "the", "provided", "{", "@link", "SavepointRestoreSettings", "}", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/JobMaster.java#L1126-L1137
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/CapabilityRegistry.java
CapabilityRegistry.createShadowCopy
CapabilityRegistry createShadowCopy() { """ Creates updateable version of capability registry that on publish pushes all changes to main registry this is used to create context local registry that only on completion commits changes to main registry @return writable registry """ CapabilityRegistry result = new CapabilityRegistry(forServer, this); readLock.lock(); try { try { result.writeLock.lock(); copy(this, result); } finally { result.writeLock.unlock(); } } finally { readLock.unlock(); } return result; }
java
CapabilityRegistry createShadowCopy() { CapabilityRegistry result = new CapabilityRegistry(forServer, this); readLock.lock(); try { try { result.writeLock.lock(); copy(this, result); } finally { result.writeLock.unlock(); } } finally { readLock.unlock(); } return result; }
[ "CapabilityRegistry", "createShadowCopy", "(", ")", "{", "CapabilityRegistry", "result", "=", "new", "CapabilityRegistry", "(", "forServer", ",", "this", ")", ";", "readLock", ".", "lock", "(", ")", ";", "try", "{", "try", "{", "result", ".", "writeLock", ".", "lock", "(", ")", ";", "copy", "(", "this", ",", "result", ")", ";", "}", "finally", "{", "result", ".", "writeLock", ".", "unlock", "(", ")", ";", "}", "}", "finally", "{", "readLock", ".", "unlock", "(", ")", ";", "}", "return", "result", ";", "}" ]
Creates updateable version of capability registry that on publish pushes all changes to main registry this is used to create context local registry that only on completion commits changes to main registry @return writable registry
[ "Creates", "updateable", "version", "of", "capability", "registry", "that", "on", "publish", "pushes", "all", "changes", "to", "main", "registry", "this", "is", "used", "to", "create", "context", "local", "registry", "that", "only", "on", "completion", "commits", "changes", "to", "main", "registry" ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/CapabilityRegistry.java#L103-L117
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java
ReUtil.findAll
public static List<String> findAll(String regex, CharSequence content, int group) { """ 取得内容中匹配的所有结果 @param regex 正则 @param content 被查找的内容 @param group 正则的分组 @return 结果列表 @since 3.0.6 """ return findAll(regex, content, group, new ArrayList<String>()); }
java
public static List<String> findAll(String regex, CharSequence content, int group) { return findAll(regex, content, group, new ArrayList<String>()); }
[ "public", "static", "List", "<", "String", ">", "findAll", "(", "String", "regex", ",", "CharSequence", "content", ",", "int", "group", ")", "{", "return", "findAll", "(", "regex", ",", "content", ",", "group", ",", "new", "ArrayList", "<", "String", ">", "(", ")", ")", ";", "}" ]
取得内容中匹配的所有结果 @param regex 正则 @param content 被查找的内容 @param group 正则的分组 @return 结果列表 @since 3.0.6
[ "取得内容中匹配的所有结果" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java#L388-L390
jenkinsci/jenkins
core/src/main/java/hudson/os/SU.java
SU.start
public static VirtualChannel start(final TaskListener listener, final String rootUsername, final String rootPassword) throws IOException, InterruptedException { """ Returns a {@link VirtualChannel} that's connected to the privilege-escalated environment. @param listener What this method is doing (such as what process it's invoking) will be sent here. @return Never null. This may represent a channel to a separate JVM, or just {@link LocalChannel}. Close this channel and the SU environment will be shut down. """ if(File.pathSeparatorChar==';') // on Windows return newLocalChannel(); // TODO: perhaps use RunAs to run as an Administrator? String os = Util.fixNull(System.getProperty("os.name")); if(os.equals("Linux")) return new UnixSu() { protected String sudoExe() { return "sudo"; } protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { args.prepend(sudoExe(),"-S"); listener.getLogger().println("$ "+Util.join(args.toList()," ")); ProcessBuilder pb = new ProcessBuilder(args.toCommandArray()); Process p = pb.start(); // TODO: use -p to detect prompt // TODO: detect if the password didn't work PrintStream ps = new PrintStream(p.getOutputStream()); ps.println(rootPassword); ps.println(rootPassword); ps.println(rootPassword); return p; } }.start(listener,rootPassword); if(os.equals("SunOS")) return new UnixSu() { protected String sudoExe() { return "/usr/bin/pfexec"; } protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { listener.getLogger().println("Running with embedded_su"); ProcessBuilder pb = new ProcessBuilder(args.prepend(sudoExe()).toCommandArray()); return EmbeddedSu.startWithSu(rootUsername, rootPassword, pb); } // in solaris, pfexec never asks for a password, so username==null means // we won't be using password. this helps disambiguate empty password }.start(listener,rootUsername==null?null:rootPassword); // TODO: Mac? // unsupported platform, take a chance return newLocalChannel(); }
java
public static VirtualChannel start(final TaskListener listener, final String rootUsername, final String rootPassword) throws IOException, InterruptedException { if(File.pathSeparatorChar==';') // on Windows return newLocalChannel(); // TODO: perhaps use RunAs to run as an Administrator? String os = Util.fixNull(System.getProperty("os.name")); if(os.equals("Linux")) return new UnixSu() { protected String sudoExe() { return "sudo"; } protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { args.prepend(sudoExe(),"-S"); listener.getLogger().println("$ "+Util.join(args.toList()," ")); ProcessBuilder pb = new ProcessBuilder(args.toCommandArray()); Process p = pb.start(); // TODO: use -p to detect prompt // TODO: detect if the password didn't work PrintStream ps = new PrintStream(p.getOutputStream()); ps.println(rootPassword); ps.println(rootPassword); ps.println(rootPassword); return p; } }.start(listener,rootPassword); if(os.equals("SunOS")) return new UnixSu() { protected String sudoExe() { return "/usr/bin/pfexec"; } protected Process sudoWithPass(ArgumentListBuilder args) throws IOException { listener.getLogger().println("Running with embedded_su"); ProcessBuilder pb = new ProcessBuilder(args.prepend(sudoExe()).toCommandArray()); return EmbeddedSu.startWithSu(rootUsername, rootPassword, pb); } // in solaris, pfexec never asks for a password, so username==null means // we won't be using password. this helps disambiguate empty password }.start(listener,rootUsername==null?null:rootPassword); // TODO: Mac? // unsupported platform, take a chance return newLocalChannel(); }
[ "public", "static", "VirtualChannel", "start", "(", "final", "TaskListener", "listener", ",", "final", "String", "rootUsername", ",", "final", "String", "rootPassword", ")", "throws", "IOException", ",", "InterruptedException", "{", "if", "(", "File", ".", "pathSeparatorChar", "==", "'", "'", ")", "// on Windows", "return", "newLocalChannel", "(", ")", ";", "// TODO: perhaps use RunAs to run as an Administrator?", "String", "os", "=", "Util", ".", "fixNull", "(", "System", ".", "getProperty", "(", "\"os.name\"", ")", ")", ";", "if", "(", "os", ".", "equals", "(", "\"Linux\"", ")", ")", "return", "new", "UnixSu", "(", ")", "{", "protected", "String", "sudoExe", "(", ")", "{", "return", "\"sudo\"", ";", "}", "protected", "Process", "sudoWithPass", "(", "ArgumentListBuilder", "args", ")", "throws", "IOException", "{", "args", ".", "prepend", "(", "sudoExe", "(", ")", ",", "\"-S\"", ")", ";", "listener", ".", "getLogger", "(", ")", ".", "println", "(", "\"$ \"", "+", "Util", ".", "join", "(", "args", ".", "toList", "(", ")", ",", "\" \"", ")", ")", ";", "ProcessBuilder", "pb", "=", "new", "ProcessBuilder", "(", "args", ".", "toCommandArray", "(", ")", ")", ";", "Process", "p", "=", "pb", ".", "start", "(", ")", ";", "// TODO: use -p to detect prompt", "// TODO: detect if the password didn't work", "PrintStream", "ps", "=", "new", "PrintStream", "(", "p", ".", "getOutputStream", "(", ")", ")", ";", "ps", ".", "println", "(", "rootPassword", ")", ";", "ps", ".", "println", "(", "rootPassword", ")", ";", "ps", ".", "println", "(", "rootPassword", ")", ";", "return", "p", ";", "}", "}", ".", "start", "(", "listener", ",", "rootPassword", ")", ";", "if", "(", "os", ".", "equals", "(", "\"SunOS\"", ")", ")", "return", "new", "UnixSu", "(", ")", "{", "protected", "String", "sudoExe", "(", ")", "{", "return", "\"/usr/bin/pfexec\"", ";", "}", "protected", "Process", "sudoWithPass", "(", "ArgumentListBuilder", "args", ")", "throws", "IOException", "{", "listener", ".", "getLogger", "(", ")", ".", "println", "(", "\"Running with embedded_su\"", ")", ";", "ProcessBuilder", "pb", "=", "new", "ProcessBuilder", "(", "args", ".", "prepend", "(", "sudoExe", "(", ")", ")", ".", "toCommandArray", "(", ")", ")", ";", "return", "EmbeddedSu", ".", "startWithSu", "(", "rootUsername", ",", "rootPassword", ",", "pb", ")", ";", "}", "// in solaris, pfexec never asks for a password, so username==null means", "// we won't be using password. this helps disambiguate empty password", "}", ".", "start", "(", "listener", ",", "rootUsername", "==", "null", "?", "null", ":", "rootPassword", ")", ";", "// TODO: Mac?", "// unsupported platform, take a chance", "return", "newLocalChannel", "(", ")", ";", "}" ]
Returns a {@link VirtualChannel} that's connected to the privilege-escalated environment. @param listener What this method is doing (such as what process it's invoking) will be sent here. @return Never null. This may represent a channel to a separate JVM, or just {@link LocalChannel}. Close this channel and the SU environment will be shut down.
[ "Returns", "a", "{", "@link", "VirtualChannel", "}", "that", "s", "connected", "to", "the", "privilege", "-", "escalated", "environment", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/os/SU.java#L73-L118
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/earth/ST_GeometryShadow.java
ST_GeometryShadow.shadowLine
private static Geometry shadowLine(LineString lineString, double[] shadowOffset, GeometryFactory factory, boolean doUnion) { """ Compute the shadow for a linestring @param lineString the input linestring @param shadowOffset computed according the sun position and the height of the geometry @return """ Coordinate[] coords = lineString.getCoordinates(); Collection<Polygon> shadows = new ArrayList<Polygon>(); createShadowPolygons(shadows, coords, shadowOffset, factory); if (!doUnion) { return factory.buildGeometry(shadows); } else { if (!shadows.isEmpty()) { CascadedPolygonUnion union = new CascadedPolygonUnion(shadows); Geometry result = union.union(); result.apply(new UpdateZCoordinateSequenceFilter(0, 1)); return result; } return null; } }
java
private static Geometry shadowLine(LineString lineString, double[] shadowOffset, GeometryFactory factory, boolean doUnion) { Coordinate[] coords = lineString.getCoordinates(); Collection<Polygon> shadows = new ArrayList<Polygon>(); createShadowPolygons(shadows, coords, shadowOffset, factory); if (!doUnion) { return factory.buildGeometry(shadows); } else { if (!shadows.isEmpty()) { CascadedPolygonUnion union = new CascadedPolygonUnion(shadows); Geometry result = union.union(); result.apply(new UpdateZCoordinateSequenceFilter(0, 1)); return result; } return null; } }
[ "private", "static", "Geometry", "shadowLine", "(", "LineString", "lineString", ",", "double", "[", "]", "shadowOffset", ",", "GeometryFactory", "factory", ",", "boolean", "doUnion", ")", "{", "Coordinate", "[", "]", "coords", "=", "lineString", ".", "getCoordinates", "(", ")", ";", "Collection", "<", "Polygon", ">", "shadows", "=", "new", "ArrayList", "<", "Polygon", ">", "(", ")", ";", "createShadowPolygons", "(", "shadows", ",", "coords", ",", "shadowOffset", ",", "factory", ")", ";", "if", "(", "!", "doUnion", ")", "{", "return", "factory", ".", "buildGeometry", "(", "shadows", ")", ";", "}", "else", "{", "if", "(", "!", "shadows", ".", "isEmpty", "(", ")", ")", "{", "CascadedPolygonUnion", "union", "=", "new", "CascadedPolygonUnion", "(", "shadows", ")", ";", "Geometry", "result", "=", "union", ".", "union", "(", ")", ";", "result", ".", "apply", "(", "new", "UpdateZCoordinateSequenceFilter", "(", "0", ",", "1", ")", ")", ";", "return", "result", ";", "}", "return", "null", ";", "}", "}" ]
Compute the shadow for a linestring @param lineString the input linestring @param shadowOffset computed according the sun position and the height of the geometry @return
[ "Compute", "the", "shadow", "for", "a", "linestring" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/earth/ST_GeometryShadow.java#L133-L148
Waikato/jclasslocator
src/main/java/nz/ac/waikato/cms/locator/ClassPathTraversal.java
ClassPathTraversal.traverseDir
protected void traverseDir(File dir, TraversalState state) { """ Fills the class cache with classes in the specified directory. @param dir the directory to search @param state the traversal state """ if (isLoggingEnabled()) getLogger().log(Level.INFO, "Analyzing directory: " + dir); traverseDir(null, dir, state); }
java
protected void traverseDir(File dir, TraversalState state) { if (isLoggingEnabled()) getLogger().log(Level.INFO, "Analyzing directory: " + dir); traverseDir(null, dir, state); }
[ "protected", "void", "traverseDir", "(", "File", "dir", ",", "TraversalState", "state", ")", "{", "if", "(", "isLoggingEnabled", "(", ")", ")", "getLogger", "(", ")", ".", "log", "(", "Level", ".", "INFO", ",", "\"Analyzing directory: \"", "+", "dir", ")", ";", "traverseDir", "(", "null", ",", "dir", ",", "state", ")", ";", "}" ]
Fills the class cache with classes in the specified directory. @param dir the directory to search @param state the traversal state
[ "Fills", "the", "class", "cache", "with", "classes", "in", "the", "specified", "directory", "." ]
train
https://github.com/Waikato/jclasslocator/blob/c899072fff607a56ee7f8c2d01fbeb15157ad144/src/main/java/nz/ac/waikato/cms/locator/ClassPathTraversal.java#L192-L196
Stratio/bdt
src/main/java/com/stratio/qa/specs/MiscSpec.java
MiscSpec.saveElementEnvironment
@Given("^I save element (in position \'(.+?)\' in )?\'(.+?)\' in environment variable \'(.+?)\'$") public void saveElementEnvironment(String foo, String position, String element, String envVar) throws Exception { """ Save value for future use. <p> If element is a jsonpath expression (i.e. $.fragments[0].id), it will be applied over the last httpResponse. <p> If element is a jsonpath expression preceded by some other string (i.e. ["a","b",,"c"].$.[0]), it will be applied over this string. This will help to save the result of a jsonpath expression evaluated over previous stored variable. @param position position from a search result @param element key in the json response to be saved @param envVar thread environment variable where to store the value @throws IllegalAccessException exception @throws IllegalArgumentException exception @throws SecurityException exception @throws NoSuchFieldException exception @throws ClassNotFoundException exception @throws InstantiationException exception @throws InvocationTargetException exception @throws NoSuchMethodException exception """ Pattern pattern = Pattern.compile("^((.*)(\\.)+)(\\$.*)$"); Matcher matcher = pattern.matcher(element); String json; String parsedElement; if (matcher.find()) { json = matcher.group(2); parsedElement = matcher.group(4); } else { json = commonspec.getResponse().getResponse(); parsedElement = element; } String value = commonspec.getJSONPathString(json, parsedElement, position); ThreadProperty.set(envVar, value.replaceAll("\n", "")); }
java
@Given("^I save element (in position \'(.+?)\' in )?\'(.+?)\' in environment variable \'(.+?)\'$") public void saveElementEnvironment(String foo, String position, String element, String envVar) throws Exception { Pattern pattern = Pattern.compile("^((.*)(\\.)+)(\\$.*)$"); Matcher matcher = pattern.matcher(element); String json; String parsedElement; if (matcher.find()) { json = matcher.group(2); parsedElement = matcher.group(4); } else { json = commonspec.getResponse().getResponse(); parsedElement = element; } String value = commonspec.getJSONPathString(json, parsedElement, position); ThreadProperty.set(envVar, value.replaceAll("\n", "")); }
[ "@", "Given", "(", "\"^I save element (in position \\'(.+?)\\' in )?\\'(.+?)\\' in environment variable \\'(.+?)\\'$\"", ")", "public", "void", "saveElementEnvironment", "(", "String", "foo", ",", "String", "position", ",", "String", "element", ",", "String", "envVar", ")", "throws", "Exception", "{", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "\"^((.*)(\\\\.)+)(\\\\$.*)$\"", ")", ";", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "element", ")", ";", "String", "json", ";", "String", "parsedElement", ";", "if", "(", "matcher", ".", "find", "(", ")", ")", "{", "json", "=", "matcher", ".", "group", "(", "2", ")", ";", "parsedElement", "=", "matcher", ".", "group", "(", "4", ")", ";", "}", "else", "{", "json", "=", "commonspec", ".", "getResponse", "(", ")", ".", "getResponse", "(", ")", ";", "parsedElement", "=", "element", ";", "}", "String", "value", "=", "commonspec", ".", "getJSONPathString", "(", "json", ",", "parsedElement", ",", "position", ")", ";", "ThreadProperty", ".", "set", "(", "envVar", ",", "value", ".", "replaceAll", "(", "\"\\n\"", ",", "\"\"", ")", ")", ";", "}" ]
Save value for future use. <p> If element is a jsonpath expression (i.e. $.fragments[0].id), it will be applied over the last httpResponse. <p> If element is a jsonpath expression preceded by some other string (i.e. ["a","b",,"c"].$.[0]), it will be applied over this string. This will help to save the result of a jsonpath expression evaluated over previous stored variable. @param position position from a search result @param element key in the json response to be saved @param envVar thread environment variable where to store the value @throws IllegalAccessException exception @throws IllegalArgumentException exception @throws SecurityException exception @throws NoSuchFieldException exception @throws ClassNotFoundException exception @throws InstantiationException exception @throws InvocationTargetException exception @throws NoSuchMethodException exception
[ "Save", "value", "for", "future", "use", ".", "<p", ">", "If", "element", "is", "a", "jsonpath", "expression", "(", "i", ".", "e", ".", "$", ".", "fragments", "[", "0", "]", ".", "id", ")", "it", "will", "be", "applied", "over", "the", "last", "httpResponse", ".", "<p", ">", "If", "element", "is", "a", "jsonpath", "expression", "preceded", "by", "some", "other", "string", "(", "i", ".", "e", ".", "[", "a", "b", "c", "]", ".", "$", ".", "[", "0", "]", ")", "it", "will", "be", "applied", "over", "this", "string", ".", "This", "will", "help", "to", "save", "the", "result", "of", "a", "jsonpath", "expression", "evaluated", "over", "previous", "stored", "variable", "." ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/MiscSpec.java#L77-L96
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java
RTMPProtocolEncoder.calculateHeaderSize
private int calculateHeaderSize(final Header header, final Header lastHeader) { """ Calculate number of bytes necessary to encode the header. @param header RTMP message header @param lastHeader Previous header @return Calculated size """ final byte headerType = getHeaderType(header, lastHeader); int channelIdAdd = 0; int channelId = header.getChannelId(); if (channelId > 320) { channelIdAdd = 2; } else if (channelId > 63) { channelIdAdd = 1; } return RTMPUtils.getHeaderLength(headerType) + channelIdAdd; }
java
private int calculateHeaderSize(final Header header, final Header lastHeader) { final byte headerType = getHeaderType(header, lastHeader); int channelIdAdd = 0; int channelId = header.getChannelId(); if (channelId > 320) { channelIdAdd = 2; } else if (channelId > 63) { channelIdAdd = 1; } return RTMPUtils.getHeaderLength(headerType) + channelIdAdd; }
[ "private", "int", "calculateHeaderSize", "(", "final", "Header", "header", ",", "final", "Header", "lastHeader", ")", "{", "final", "byte", "headerType", "=", "getHeaderType", "(", "header", ",", "lastHeader", ")", ";", "int", "channelIdAdd", "=", "0", ";", "int", "channelId", "=", "header", ".", "getChannelId", "(", ")", ";", "if", "(", "channelId", ">", "320", ")", "{", "channelIdAdd", "=", "2", ";", "}", "else", "if", "(", "channelId", ">", "63", ")", "{", "channelIdAdd", "=", "1", ";", "}", "return", "RTMPUtils", ".", "getHeaderLength", "(", "headerType", ")", "+", "channelIdAdd", ";", "}" ]
Calculate number of bytes necessary to encode the header. @param header RTMP message header @param lastHeader Previous header @return Calculated size
[ "Calculate", "number", "of", "bytes", "necessary", "to", "encode", "the", "header", "." ]
train
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMPProtocolEncoder.java#L381-L391
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java
PerspectiveOps.pinholeToMatrix
public static DMatrixRMaj pinholeToMatrix(CameraPinhole param , DMatrixRMaj K ) { """ Given the intrinsic parameters create a calibration matrix @param param Intrinsic parameters structure that is to be converted into a matrix @param K Storage for calibration matrix, must be 3x3. If null then a new matrix is declared @return Calibration matrix 3x3 """ return ImplPerspectiveOps_F64.pinholeToMatrix(param, K); }
java
public static DMatrixRMaj pinholeToMatrix(CameraPinhole param , DMatrixRMaj K ) { return ImplPerspectiveOps_F64.pinholeToMatrix(param, K); }
[ "public", "static", "DMatrixRMaj", "pinholeToMatrix", "(", "CameraPinhole", "param", ",", "DMatrixRMaj", "K", ")", "{", "return", "ImplPerspectiveOps_F64", ".", "pinholeToMatrix", "(", "param", ",", "K", ")", ";", "}" ]
Given the intrinsic parameters create a calibration matrix @param param Intrinsic parameters structure that is to be converted into a matrix @param K Storage for calibration matrix, must be 3x3. If null then a new matrix is declared @return Calibration matrix 3x3
[ "Given", "the", "intrinsic", "parameters", "create", "a", "calibration", "matrix" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java#L259-L262
windup/windup
rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/MavenStructureRenderer.java
MavenStructureRenderer.renderFreemarkerTemplate
private static void renderFreemarkerTemplate(Path templatePath, Map vars, Path outputPath) throws IOException, TemplateException { """ Renders the given FreeMarker template to given directory, using given variables. """ if(templatePath == null) throw new WindupException("templatePath is null"); freemarker.template.Configuration freemarkerConfig = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_26); DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); objectWrapperBuilder.setUseAdaptersForContainers(true); objectWrapperBuilder.setIterableSupport(true); freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build()); freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader()); Template template = freemarkerConfig.getTemplate(templatePath.toString().replace('\\', '/')); try (FileWriter fw = new FileWriter(outputPath.toFile())) { template.process(vars, fw); } }
java
private static void renderFreemarkerTemplate(Path templatePath, Map vars, Path outputPath) throws IOException, TemplateException { if(templatePath == null) throw new WindupException("templatePath is null"); freemarker.template.Configuration freemarkerConfig = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_26); DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); objectWrapperBuilder.setUseAdaptersForContainers(true); objectWrapperBuilder.setIterableSupport(true); freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build()); freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader()); Template template = freemarkerConfig.getTemplate(templatePath.toString().replace('\\', '/')); try (FileWriter fw = new FileWriter(outputPath.toFile())) { template.process(vars, fw); } }
[ "private", "static", "void", "renderFreemarkerTemplate", "(", "Path", "templatePath", ",", "Map", "vars", ",", "Path", "outputPath", ")", "throws", "IOException", ",", "TemplateException", "{", "if", "(", "templatePath", "==", "null", ")", "throw", "new", "WindupException", "(", "\"templatePath is null\"", ")", ";", "freemarker", ".", "template", ".", "Configuration", "freemarkerConfig", "=", "new", "freemarker", ".", "template", ".", "Configuration", "(", "freemarker", ".", "template", ".", "Configuration", ".", "VERSION_2_3_26", ")", ";", "DefaultObjectWrapperBuilder", "objectWrapperBuilder", "=", "new", "DefaultObjectWrapperBuilder", "(", "freemarker", ".", "template", ".", "Configuration", ".", "DEFAULT_INCOMPATIBLE_IMPROVEMENTS", ")", ";", "objectWrapperBuilder", ".", "setUseAdaptersForContainers", "(", "true", ")", ";", "objectWrapperBuilder", ".", "setIterableSupport", "(", "true", ")", ";", "freemarkerConfig", ".", "setObjectWrapper", "(", "objectWrapperBuilder", ".", "build", "(", ")", ")", ";", "freemarkerConfig", ".", "setTemplateLoader", "(", "new", "FurnaceFreeMarkerTemplateLoader", "(", ")", ")", ";", "Template", "template", "=", "freemarkerConfig", ".", "getTemplate", "(", "templatePath", ".", "toString", "(", ")", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ")", ";", "try", "(", "FileWriter", "fw", "=", "new", "FileWriter", "(", "outputPath", ".", "toFile", "(", ")", ")", ")", "{", "template", ".", "process", "(", "vars", ",", "fw", ")", ";", "}", "}" ]
Renders the given FreeMarker template to given directory, using given variables.
[ "Renders", "the", "given", "FreeMarker", "template", "to", "given", "directory", "using", "given", "variables", "." ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/rules-java/api/src/main/java/org/jboss/windup/rules/apps/mavenize/MavenStructureRenderer.java#L120-L137
AKSW/RDFUnit
rdfunit-validate/src/main/java/org/aksw/rdfunit/validate/ws/AbstractRDFUnitWebService.java
AbstractRDFUnitWebService.printMessage
protected void printMessage(HttpServletResponse httpServletResponse, String message) throws IOException { """ Help function that writes a string to the output surrounded with {@code <pre> </pre>} @param httpServletResponse a {@link javax.servlet.http.HttpServletResponse} object. @param message the message we want to write @throws java.io.IOException if any. """ // Set response content type httpServletResponse.setContentType("text/html"); // Actual logic goes here. PrintWriter out = httpServletResponse.getWriter(); out.println("<pre>" + message + "</pre>"); //out.close(); }
java
protected void printMessage(HttpServletResponse httpServletResponse, String message) throws IOException { // Set response content type httpServletResponse.setContentType("text/html"); // Actual logic goes here. PrintWriter out = httpServletResponse.getWriter(); out.println("<pre>" + message + "</pre>"); //out.close(); }
[ "protected", "void", "printMessage", "(", "HttpServletResponse", "httpServletResponse", ",", "String", "message", ")", "throws", "IOException", "{", "// Set response content type", "httpServletResponse", ".", "setContentType", "(", "\"text/html\"", ")", ";", "// Actual logic goes here.", "PrintWriter", "out", "=", "httpServletResponse", ".", "getWriter", "(", ")", ";", "out", ".", "println", "(", "\"<pre>\"", "+", "message", "+", "\"</pre>\"", ")", ";", "//out.close();", "}" ]
Help function that writes a string to the output surrounded with {@code <pre> </pre>} @param httpServletResponse a {@link javax.servlet.http.HttpServletResponse} object. @param message the message we want to write @throws java.io.IOException if any.
[ "Help", "function", "that", "writes", "a", "string", "to", "the", "output", "surrounded", "with", "{", "@code", "<pre", ">", "<", "/", "pre", ">", "}" ]
train
https://github.com/AKSW/RDFUnit/blob/083f18ebda4ad790b1fbb4cfe1c9dd1762d51384/rdfunit-validate/src/main/java/org/aksw/rdfunit/validate/ws/AbstractRDFUnitWebService.java#L138-L145
haraldk/TwelveMonkeys
servlet/src/main/java/com/twelvemonkeys/servlet/BrowserHelperFilter.java
BrowserHelperFilter.setAcceptMappingsFile
@InitParam(name = "accept-mappings-file") public void setAcceptMappingsFile(String pPropertiesFile) throws ServletConfigException { """ Sets the accept-mappings for this filter @param pPropertiesFile name of accept-mappings properties files @throws ServletConfigException if the accept-mappings properties file cannot be read. """ // NOTE: Format is: // <agent-name>=<reg-exp> // <agent-name>.accept=<http-accept-header> Properties mappings = new Properties(); try { log("Reading Accept-mappings properties file: " + pPropertiesFile); mappings.load(getServletContext().getResourceAsStream(pPropertiesFile)); //System.out.println("--> Loaded file: " + pPropertiesFile); } catch (IOException e) { throw new ServletConfigException("Could not read Accept-mappings properties file: " + pPropertiesFile, e); } parseMappings(mappings); }
java
@InitParam(name = "accept-mappings-file") public void setAcceptMappingsFile(String pPropertiesFile) throws ServletConfigException { // NOTE: Format is: // <agent-name>=<reg-exp> // <agent-name>.accept=<http-accept-header> Properties mappings = new Properties(); try { log("Reading Accept-mappings properties file: " + pPropertiesFile); mappings.load(getServletContext().getResourceAsStream(pPropertiesFile)); //System.out.println("--> Loaded file: " + pPropertiesFile); } catch (IOException e) { throw new ServletConfigException("Could not read Accept-mappings properties file: " + pPropertiesFile, e); } parseMappings(mappings); }
[ "@", "InitParam", "(", "name", "=", "\"accept-mappings-file\"", ")", "public", "void", "setAcceptMappingsFile", "(", "String", "pPropertiesFile", ")", "throws", "ServletConfigException", "{", "// NOTE: Format is:", "// <agent-name>=<reg-exp>", "// <agent-name>.accept=<http-accept-header>", "Properties", "mappings", "=", "new", "Properties", "(", ")", ";", "try", "{", "log", "(", "\"Reading Accept-mappings properties file: \"", "+", "pPropertiesFile", ")", ";", "mappings", ".", "load", "(", "getServletContext", "(", ")", ".", "getResourceAsStream", "(", "pPropertiesFile", ")", ")", ";", "//System.out.println(\"--> Loaded file: \" + pPropertiesFile);", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "ServletConfigException", "(", "\"Could not read Accept-mappings properties file: \"", "+", "pPropertiesFile", ",", "e", ")", ";", "}", "parseMappings", "(", "mappings", ")", ";", "}" ]
Sets the accept-mappings for this filter @param pPropertiesFile name of accept-mappings properties files @throws ServletConfigException if the accept-mappings properties file cannot be read.
[ "Sets", "the", "accept", "-", "mappings", "for", "this", "filter" ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/BrowserHelperFilter.java#L68-L87
apache/incubator-gobblin
gobblin-modules/gobblin-http/src/main/java/org/apache/gobblin/http/ApacheHttpRequestBuilder.java
ApacheHttpRequestBuilder.addPayload
protected int addPayload(RequestBuilder builder, String payload) { """ Add payload to request. By default, payload is sent as application/json """ if (payload == null || payload.length() == 0) { return 0; } builder.setHeader(HttpHeaders.CONTENT_TYPE, contentType.getMimeType()); builder.setEntity(new StringEntity(payload, contentType)); return payload.length(); }
java
protected int addPayload(RequestBuilder builder, String payload) { if (payload == null || payload.length() == 0) { return 0; } builder.setHeader(HttpHeaders.CONTENT_TYPE, contentType.getMimeType()); builder.setEntity(new StringEntity(payload, contentType)); return payload.length(); }
[ "protected", "int", "addPayload", "(", "RequestBuilder", "builder", ",", "String", "payload", ")", "{", "if", "(", "payload", "==", "null", "||", "payload", ".", "length", "(", ")", "==", "0", ")", "{", "return", "0", ";", "}", "builder", ".", "setHeader", "(", "HttpHeaders", ".", "CONTENT_TYPE", ",", "contentType", ".", "getMimeType", "(", ")", ")", ";", "builder", ".", "setEntity", "(", "new", "StringEntity", "(", "payload", ",", "contentType", ")", ")", ";", "return", "payload", ".", "length", "(", ")", ";", "}" ]
Add payload to request. By default, payload is sent as application/json
[ "Add", "payload", "to", "request", ".", "By", "default", "payload", "is", "sent", "as", "application", "/", "json" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-http/src/main/java/org/apache/gobblin/http/ApacheHttpRequestBuilder.java#L107-L116
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.readResource
public I_CmsHistoryResource readResource(CmsRequestContext context, CmsResource resource, int version) throws CmsException { """ Reads the historical resource entry for the given resource with the given version number.<p> @param context the current request context @param resource the resource to be read the version for @param version the version number to retrieve @return the resource that was read @throws CmsException if the resource could not be read for any reason @see CmsObject#readFile(CmsResource) @see CmsObject#restoreResourceVersion(CmsUUID, int) @see CmsObject#readResource(CmsUUID, int) """ CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsHistoryResource result = null; try { result = m_driverManager.readResource(dbc, resource, version); } catch (CmsException e) { dbc.report( null, Messages.get().container( Messages.ERR_READING_RESOURCE_VERSION_2, dbc.removeSiteRoot(resource.getRootPath()), new Integer(version)), e); } finally { dbc.clear(); } return result; }
java
public I_CmsHistoryResource readResource(CmsRequestContext context, CmsResource resource, int version) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsHistoryResource result = null; try { result = m_driverManager.readResource(dbc, resource, version); } catch (CmsException e) { dbc.report( null, Messages.get().container( Messages.ERR_READING_RESOURCE_VERSION_2, dbc.removeSiteRoot(resource.getRootPath()), new Integer(version)), e); } finally { dbc.clear(); } return result; }
[ "public", "I_CmsHistoryResource", "readResource", "(", "CmsRequestContext", "context", ",", "CmsResource", "resource", ",", "int", "version", ")", "throws", "CmsException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "(", "context", ")", ";", "I_CmsHistoryResource", "result", "=", "null", ";", "try", "{", "result", "=", "m_driverManager", ".", "readResource", "(", "dbc", ",", "resource", ",", "version", ")", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "dbc", ".", "report", "(", "null", ",", "Messages", ".", "get", "(", ")", ".", "container", "(", "Messages", ".", "ERR_READING_RESOURCE_VERSION_2", ",", "dbc", ".", "removeSiteRoot", "(", "resource", ".", "getRootPath", "(", ")", ")", ",", "new", "Integer", "(", "version", ")", ")", ",", "e", ")", ";", "}", "finally", "{", "dbc", ".", "clear", "(", ")", ";", "}", "return", "result", ";", "}" ]
Reads the historical resource entry for the given resource with the given version number.<p> @param context the current request context @param resource the resource to be read the version for @param version the version number to retrieve @return the resource that was read @throws CmsException if the resource could not be read for any reason @see CmsObject#readFile(CmsResource) @see CmsObject#restoreResourceVersion(CmsUUID, int) @see CmsObject#readResource(CmsUUID, int)
[ "Reads", "the", "historical", "resource", "entry", "for", "the", "given", "resource", "with", "the", "given", "version", "number", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L4966-L4985
couchbase/CouchbaseMock
src/main/java/com/couchbase/mock/CouchbaseMock.java
CouchbaseMock.createDefaultConfig
private static BucketConfiguration createDefaultConfig(String hostname, int numNodes, int bucketStartPort, int numVBuckets, int numReplicas) { """ Initializes the default configuration from the command line parameters. This is present in order to allow the super constructor to be the first statement """ BucketConfiguration defaultConfig = new BucketConfiguration(); defaultConfig.type = BucketType.COUCHBASE; defaultConfig.hostname = hostname; defaultConfig.numNodes = numNodes; if (numReplicas > -1) { defaultConfig.numReplicas = numReplicas; } defaultConfig.bucketStartPort = bucketStartPort; defaultConfig.numVBuckets = numVBuckets; return defaultConfig; }
java
private static BucketConfiguration createDefaultConfig(String hostname, int numNodes, int bucketStartPort, int numVBuckets, int numReplicas) { BucketConfiguration defaultConfig = new BucketConfiguration(); defaultConfig.type = BucketType.COUCHBASE; defaultConfig.hostname = hostname; defaultConfig.numNodes = numNodes; if (numReplicas > -1) { defaultConfig.numReplicas = numReplicas; } defaultConfig.bucketStartPort = bucketStartPort; defaultConfig.numVBuckets = numVBuckets; return defaultConfig; }
[ "private", "static", "BucketConfiguration", "createDefaultConfig", "(", "String", "hostname", ",", "int", "numNodes", ",", "int", "bucketStartPort", ",", "int", "numVBuckets", ",", "int", "numReplicas", ")", "{", "BucketConfiguration", "defaultConfig", "=", "new", "BucketConfiguration", "(", ")", ";", "defaultConfig", ".", "type", "=", "BucketType", ".", "COUCHBASE", ";", "defaultConfig", ".", "hostname", "=", "hostname", ";", "defaultConfig", ".", "numNodes", "=", "numNodes", ";", "if", "(", "numReplicas", ">", "-", "1", ")", "{", "defaultConfig", ".", "numReplicas", "=", "numReplicas", ";", "}", "defaultConfig", ".", "bucketStartPort", "=", "bucketStartPort", ";", "defaultConfig", ".", "numVBuckets", "=", "numVBuckets", ";", "return", "defaultConfig", ";", "}" ]
Initializes the default configuration from the command line parameters. This is present in order to allow the super constructor to be the first statement
[ "Initializes", "the", "default", "configuration", "from", "the", "command", "line", "parameters", ".", "This", "is", "present", "in", "order", "to", "allow", "the", "super", "constructor", "to", "be", "the", "first", "statement" ]
train
https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/CouchbaseMock.java#L215-L227
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_sshkey_GET
public ArrayList<OvhSshKey> project_serviceName_sshkey_GET(String serviceName, String region) throws IOException { """ Get SSH keys REST: GET /cloud/project/{serviceName}/sshkey @param region [required] Region @param serviceName [required] Project name """ String qPath = "/cloud/project/{serviceName}/sshkey"; StringBuilder sb = path(qPath, serviceName); query(sb, "region", region); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t17); }
java
public ArrayList<OvhSshKey> project_serviceName_sshkey_GET(String serviceName, String region) throws IOException { String qPath = "/cloud/project/{serviceName}/sshkey"; StringBuilder sb = path(qPath, serviceName); query(sb, "region", region); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t17); }
[ "public", "ArrayList", "<", "OvhSshKey", ">", "project_serviceName_sshkey_GET", "(", "String", "serviceName", ",", "String", "region", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/sshkey\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "query", "(", "sb", ",", "\"region\"", ",", "region", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t17", ")", ";", "}" ]
Get SSH keys REST: GET /cloud/project/{serviceName}/sshkey @param region [required] Region @param serviceName [required] Project name
[ "Get", "SSH", "keys" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L1540-L1546
ixa-ehu/ixa-pipe-ml
src/main/java/eus/ixa/ixa/pipe/ml/parse/ParserEventStream.java
ParserEventStream.firstChild
protected boolean firstChild(final Parse child, final Parse parent) { """ Returns true if the specified child is the first child of the specified parent. @param child The child parse. @param parent The parent parse. @return true if the specified child is the first child of the specified parent; false otherwise. """ return ShiftReduceParser.collapsePunctuation(parent.getChildren(), this.punctSet)[0] == child; }
java
protected boolean firstChild(final Parse child, final Parse parent) { return ShiftReduceParser.collapsePunctuation(parent.getChildren(), this.punctSet)[0] == child; }
[ "protected", "boolean", "firstChild", "(", "final", "Parse", "child", ",", "final", "Parse", "parent", ")", "{", "return", "ShiftReduceParser", ".", "collapsePunctuation", "(", "parent", ".", "getChildren", "(", ")", ",", "this", ".", "punctSet", ")", "[", "0", "]", "==", "child", ";", "}" ]
Returns true if the specified child is the first child of the specified parent. @param child The child parse. @param parent The parent parse. @return true if the specified child is the first child of the specified parent; false otherwise.
[ "Returns", "true", "if", "the", "specified", "child", "is", "the", "first", "child", "of", "the", "specified", "parent", "." ]
train
https://github.com/ixa-ehu/ixa-pipe-ml/blob/c817fa1e40e96ed15fc79d22c3a7c25f1a40d172/src/main/java/eus/ixa/ixa/pipe/ml/parse/ParserEventStream.java#L186-L189
gallandarakhneorg/afc
advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItineraryHalt.java
BusItineraryHalt.getPosition1D
@Pure public Point1d getPosition1D() { """ Replies the position of the bus halt on the road. The replied position may differ from the position of the associated bus stop because the position on the road is a projection of the stop's position on the road. @return the 1.5D position or <code>null</code> if the halt is not associated to a road segment. """ if (this.bufferPosition1D == null) { final RoadSegment segment = getRoadSegment(); if (segment != null && !Double.isNaN(this.curvilineDistance)) { final RoadNetwork network = segment.getRoadNetwork(); assert network != null; double lateral = segment.getRoadBorderDistance(); if (lateral < 0.) { lateral -= DISTANCE_BETWEEN_HALT_AND_ROAD_BORDER; } else { lateral += DISTANCE_BETWEEN_HALT_AND_ROAD_BORDER; } final boolean isSegmentDirection = getRoadSegmentDirection().isSegmentDirection(); if (!isSegmentDirection) { lateral = -lateral; } this.bufferPosition1D = new Point1d(segment, this.curvilineDistance, lateral); } } return this.bufferPosition1D; }
java
@Pure public Point1d getPosition1D() { if (this.bufferPosition1D == null) { final RoadSegment segment = getRoadSegment(); if (segment != null && !Double.isNaN(this.curvilineDistance)) { final RoadNetwork network = segment.getRoadNetwork(); assert network != null; double lateral = segment.getRoadBorderDistance(); if (lateral < 0.) { lateral -= DISTANCE_BETWEEN_HALT_AND_ROAD_BORDER; } else { lateral += DISTANCE_BETWEEN_HALT_AND_ROAD_BORDER; } final boolean isSegmentDirection = getRoadSegmentDirection().isSegmentDirection(); if (!isSegmentDirection) { lateral = -lateral; } this.bufferPosition1D = new Point1d(segment, this.curvilineDistance, lateral); } } return this.bufferPosition1D; }
[ "@", "Pure", "public", "Point1d", "getPosition1D", "(", ")", "{", "if", "(", "this", ".", "bufferPosition1D", "==", "null", ")", "{", "final", "RoadSegment", "segment", "=", "getRoadSegment", "(", ")", ";", "if", "(", "segment", "!=", "null", "&&", "!", "Double", ".", "isNaN", "(", "this", ".", "curvilineDistance", ")", ")", "{", "final", "RoadNetwork", "network", "=", "segment", ".", "getRoadNetwork", "(", ")", ";", "assert", "network", "!=", "null", ";", "double", "lateral", "=", "segment", ".", "getRoadBorderDistance", "(", ")", ";", "if", "(", "lateral", "<", "0.", ")", "{", "lateral", "-=", "DISTANCE_BETWEEN_HALT_AND_ROAD_BORDER", ";", "}", "else", "{", "lateral", "+=", "DISTANCE_BETWEEN_HALT_AND_ROAD_BORDER", ";", "}", "final", "boolean", "isSegmentDirection", "=", "getRoadSegmentDirection", "(", ")", ".", "isSegmentDirection", "(", ")", ";", "if", "(", "!", "isSegmentDirection", ")", "{", "lateral", "=", "-", "lateral", ";", "}", "this", ".", "bufferPosition1D", "=", "new", "Point1d", "(", "segment", ",", "this", ".", "curvilineDistance", ",", "lateral", ")", ";", "}", "}", "return", "this", ".", "bufferPosition1D", ";", "}" ]
Replies the position of the bus halt on the road. The replied position may differ from the position of the associated bus stop because the position on the road is a projection of the stop's position on the road. @return the 1.5D position or <code>null</code> if the halt is not associated to a road segment.
[ "Replies", "the", "position", "of", "the", "bus", "halt", "on", "the", "road", ".", "The", "replied", "position", "may", "differ", "from", "the", "position", "of", "the", "associated", "bus", "stop", "because", "the", "position", "on", "the", "road", "is", "a", "projection", "of", "the", "stop", "s", "position", "on", "the", "road", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/gisbus/src/main/java/org/arakhne/afc/gis/bus/network/BusItineraryHalt.java#L387-L411
samskivert/samskivert
src/main/java/com/samskivert/velocity/Application.java
Application.handleException
protected String handleException (HttpServletRequest req, Logic logic, Exception error) { """ If a generic exception propagates up from {@link Logic#invoke} and is not otherwise converted into a friendly or redirect exception, the application will be required to provide a generic error message to be inserted into the context and should take this opportunity to log the exception. <p><em>Note:</em> the string returned by this method will be translated using the application's message manager before being inserted into the Velocity context. """ log.warning(logic + " failed on: " + RequestUtils.reconstructURL(req), error); return ExceptionMap.getMessage(error); }
java
protected String handleException (HttpServletRequest req, Logic logic, Exception error) { log.warning(logic + " failed on: " + RequestUtils.reconstructURL(req), error); return ExceptionMap.getMessage(error); }
[ "protected", "String", "handleException", "(", "HttpServletRequest", "req", ",", "Logic", "logic", ",", "Exception", "error", ")", "{", "log", ".", "warning", "(", "logic", "+", "\" failed on: \"", "+", "RequestUtils", ".", "reconstructURL", "(", "req", ")", ",", "error", ")", ";", "return", "ExceptionMap", ".", "getMessage", "(", "error", ")", ";", "}" ]
If a generic exception propagates up from {@link Logic#invoke} and is not otherwise converted into a friendly or redirect exception, the application will be required to provide a generic error message to be inserted into the context and should take this opportunity to log the exception. <p><em>Note:</em> the string returned by this method will be translated using the application's message manager before being inserted into the Velocity context.
[ "If", "a", "generic", "exception", "propagates", "up", "from", "{", "@link", "Logic#invoke", "}", "and", "is", "not", "otherwise", "converted", "into", "a", "friendly", "or", "redirect", "exception", "the", "application", "will", "be", "required", "to", "provide", "a", "generic", "error", "message", "to", "be", "inserted", "into", "the", "context", "and", "should", "take", "this", "opportunity", "to", "log", "the", "exception", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/velocity/Application.java#L200-L204
finmath/finmath-lib
src/main/java/net/finmath/marketdata/products/Cap.java
Cap.getImpliedVolatility
public double getImpliedVolatility(double evaluationTime, AnalyticModel model, VolatilitySurface.QuotingConvention quotingConvention) { """ Returns the value of this cap in terms of an implied volatility (of a flat caplet surface). @param evaluationTime The evaluation time as double. Cash flows prior and including this time are not considered. @param model The model under which the product is valued. @param quotingConvention The quoting convention requested for the return value. @return The value of the product using the given model in terms of a implied volatility. """ double lowerBound = Double.MAX_VALUE; double upperBound = -Double.MAX_VALUE; for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) { double fixingDate = schedule.getFixing(periodIndex); double periodLength = schedule.getPeriodLength(periodIndex); if(periodLength == 0) { continue; } double effektiveStrike = strike; if(isStrikeMoneyness) { effektiveStrike += getATMForward(model, true); } VolatilitySurface volatilitySurface = model.getVolatilitySurface(volatiltiySufaceName); double volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, quotingConvention); lowerBound = Math.min(volatility, lowerBound); upperBound = Math.max(volatility, upperBound); } double value = getValueAsPrice(evaluationTime, model); int maxIterations = 100; double maxAccuracy = 0.0; GoldenSectionSearch solver = new GoldenSectionSearch(lowerBound, upperBound); while(solver.getAccuracy() > maxAccuracy && !solver.isDone() && solver.getNumberOfIterations() < maxIterations) { double volatility = solver.getNextPoint(); double[] maturities = { 1.0 }; double[] strikes = { 0.0 }; double[] volatilities = { volatility }; VolatilitySurface flatSurface = new CapletVolatilities(model.getVolatilitySurface(volatiltiySufaceName).getName(), model.getVolatilitySurface(volatiltiySufaceName).getReferenceDate(), model.getForwardCurve(forwardCurveName), maturities, strikes, volatilities, quotingConvention, model.getDiscountCurve(discountCurveName)); AnalyticModel flatModel = model.clone(); flatModel = flatModel.addVolatilitySurfaces(flatSurface); double flatModelValue = this.getValueAsPrice(evaluationTime, flatModel); double error = value-flatModelValue; solver.setValue(error*error); } return solver.getBestPoint(); }
java
public double getImpliedVolatility(double evaluationTime, AnalyticModel model, VolatilitySurface.QuotingConvention quotingConvention) { double lowerBound = Double.MAX_VALUE; double upperBound = -Double.MAX_VALUE; for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) { double fixingDate = schedule.getFixing(periodIndex); double periodLength = schedule.getPeriodLength(periodIndex); if(periodLength == 0) { continue; } double effektiveStrike = strike; if(isStrikeMoneyness) { effektiveStrike += getATMForward(model, true); } VolatilitySurface volatilitySurface = model.getVolatilitySurface(volatiltiySufaceName); double volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, quotingConvention); lowerBound = Math.min(volatility, lowerBound); upperBound = Math.max(volatility, upperBound); } double value = getValueAsPrice(evaluationTime, model); int maxIterations = 100; double maxAccuracy = 0.0; GoldenSectionSearch solver = new GoldenSectionSearch(lowerBound, upperBound); while(solver.getAccuracy() > maxAccuracy && !solver.isDone() && solver.getNumberOfIterations() < maxIterations) { double volatility = solver.getNextPoint(); double[] maturities = { 1.0 }; double[] strikes = { 0.0 }; double[] volatilities = { volatility }; VolatilitySurface flatSurface = new CapletVolatilities(model.getVolatilitySurface(volatiltiySufaceName).getName(), model.getVolatilitySurface(volatiltiySufaceName).getReferenceDate(), model.getForwardCurve(forwardCurveName), maturities, strikes, volatilities, quotingConvention, model.getDiscountCurve(discountCurveName)); AnalyticModel flatModel = model.clone(); flatModel = flatModel.addVolatilitySurfaces(flatSurface); double flatModelValue = this.getValueAsPrice(evaluationTime, flatModel); double error = value-flatModelValue; solver.setValue(error*error); } return solver.getBestPoint(); }
[ "public", "double", "getImpliedVolatility", "(", "double", "evaluationTime", ",", "AnalyticModel", "model", ",", "VolatilitySurface", ".", "QuotingConvention", "quotingConvention", ")", "{", "double", "lowerBound", "=", "Double", ".", "MAX_VALUE", ";", "double", "upperBound", "=", "-", "Double", ".", "MAX_VALUE", ";", "for", "(", "int", "periodIndex", "=", "0", ";", "periodIndex", "<", "schedule", ".", "getNumberOfPeriods", "(", ")", ";", "periodIndex", "++", ")", "{", "double", "fixingDate", "=", "schedule", ".", "getFixing", "(", "periodIndex", ")", ";", "double", "periodLength", "=", "schedule", ".", "getPeriodLength", "(", "periodIndex", ")", ";", "if", "(", "periodLength", "==", "0", ")", "{", "continue", ";", "}", "double", "effektiveStrike", "=", "strike", ";", "if", "(", "isStrikeMoneyness", ")", "{", "effektiveStrike", "+=", "getATMForward", "(", "model", ",", "true", ")", ";", "}", "VolatilitySurface", "volatilitySurface", "=", "model", ".", "getVolatilitySurface", "(", "volatiltiySufaceName", ")", ";", "double", "volatility", "=", "volatilitySurface", ".", "getValue", "(", "model", ",", "fixingDate", ",", "effektiveStrike", ",", "quotingConvention", ")", ";", "lowerBound", "=", "Math", ".", "min", "(", "volatility", ",", "lowerBound", ")", ";", "upperBound", "=", "Math", ".", "max", "(", "volatility", ",", "upperBound", ")", ";", "}", "double", "value", "=", "getValueAsPrice", "(", "evaluationTime", ",", "model", ")", ";", "int", "maxIterations", "=", "100", ";", "double", "maxAccuracy", "=", "0.0", ";", "GoldenSectionSearch", "solver", "=", "new", "GoldenSectionSearch", "(", "lowerBound", ",", "upperBound", ")", ";", "while", "(", "solver", ".", "getAccuracy", "(", ")", ">", "maxAccuracy", "&&", "!", "solver", ".", "isDone", "(", ")", "&&", "solver", ".", "getNumberOfIterations", "(", ")", "<", "maxIterations", ")", "{", "double", "volatility", "=", "solver", ".", "getNextPoint", "(", ")", ";", "double", "[", "]", "maturities", "=", "{", "1.0", "}", ";", "double", "[", "]", "strikes", "=", "{", "0.0", "}", ";", "double", "[", "]", "volatilities", "=", "{", "volatility", "}", ";", "VolatilitySurface", "flatSurface", "=", "new", "CapletVolatilities", "(", "model", ".", "getVolatilitySurface", "(", "volatiltiySufaceName", ")", ".", "getName", "(", ")", ",", "model", ".", "getVolatilitySurface", "(", "volatiltiySufaceName", ")", ".", "getReferenceDate", "(", ")", ",", "model", ".", "getForwardCurve", "(", "forwardCurveName", ")", ",", "maturities", ",", "strikes", ",", "volatilities", ",", "quotingConvention", ",", "model", ".", "getDiscountCurve", "(", "discountCurveName", ")", ")", ";", "AnalyticModel", "flatModel", "=", "model", ".", "clone", "(", ")", ";", "flatModel", "=", "flatModel", ".", "addVolatilitySurfaces", "(", "flatSurface", ")", ";", "double", "flatModelValue", "=", "this", ".", "getValueAsPrice", "(", "evaluationTime", ",", "flatModel", ")", ";", "double", "error", "=", "value", "-", "flatModelValue", ";", "solver", ".", "setValue", "(", "error", "*", "error", ")", ";", "}", "return", "solver", ".", "getBestPoint", "(", ")", ";", "}" ]
Returns the value of this cap in terms of an implied volatility (of a flat caplet surface). @param evaluationTime The evaluation time as double. Cash flows prior and including this time are not considered. @param model The model under which the product is valued. @param quotingConvention The quoting convention requested for the return value. @return The value of the product using the given model in terms of a implied volatility.
[ "Returns", "the", "value", "of", "this", "cap", "in", "terms", "of", "an", "implied", "volatility", "(", "of", "a", "flat", "caplet", "surface", ")", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/products/Cap.java#L232-L272
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPlot.java
SVGPlot.saveAsJPEG
public void saveAsJPEG(File file, int width, int height, float quality) throws IOException, TranscoderException { """ Transcode file to JPEG. @param file Output filename @param width Width @param height Height @param quality JPEG quality setting, between 0.0 and 1.0 @throws IOException On write errors @throws TranscoderException On input/parsing errors. """ JPEGTranscoder t = new JPEGTranscoder(); t.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, new Float(width)); t.addTranscodingHint(JPEGTranscoder.KEY_HEIGHT, new Float(height)); t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(quality)); transcode(file, t); }
java
public void saveAsJPEG(File file, int width, int height, float quality) throws IOException, TranscoderException { JPEGTranscoder t = new JPEGTranscoder(); t.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, new Float(width)); t.addTranscodingHint(JPEGTranscoder.KEY_HEIGHT, new Float(height)); t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(quality)); transcode(file, t); }
[ "public", "void", "saveAsJPEG", "(", "File", "file", ",", "int", "width", ",", "int", "height", ",", "float", "quality", ")", "throws", "IOException", ",", "TranscoderException", "{", "JPEGTranscoder", "t", "=", "new", "JPEGTranscoder", "(", ")", ";", "t", ".", "addTranscodingHint", "(", "JPEGTranscoder", ".", "KEY_WIDTH", ",", "new", "Float", "(", "width", ")", ")", ";", "t", ".", "addTranscodingHint", "(", "JPEGTranscoder", ".", "KEY_HEIGHT", ",", "new", "Float", "(", "height", ")", ")", ";", "t", ".", "addTranscodingHint", "(", "JPEGTranscoder", ".", "KEY_QUALITY", ",", "new", "Float", "(", "quality", ")", ")", ";", "transcode", "(", "file", ",", "t", ")", ";", "}" ]
Transcode file to JPEG. @param file Output filename @param width Width @param height Height @param quality JPEG quality setting, between 0.0 and 1.0 @throws IOException On write errors @throws TranscoderException On input/parsing errors.
[ "Transcode", "file", "to", "JPEG", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPlot.java#L533-L539
joniles/mpxj
src/main/java/net/sf/mpxj/turboproject/PEPUtility.java
PEPUtility.getString
public static final String getString(byte[] data, int offset) { """ Retrieve a string value. @param data byte array @param offset offset into byte array @return string value """ return getString(data, offset, data.length - offset); }
java
public static final String getString(byte[] data, int offset) { return getString(data, offset, data.length - offset); }
[ "public", "static", "final", "String", "getString", "(", "byte", "[", "]", "data", ",", "int", "offset", ")", "{", "return", "getString", "(", "data", ",", "offset", ",", "data", ".", "length", "-", "offset", ")", ";", "}" ]
Retrieve a string value. @param data byte array @param offset offset into byte array @return string value
[ "Retrieve", "a", "string", "value", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/turboproject/PEPUtility.java#L80-L83
sshtools/j2ssh-maverick
j2ssh-maverick/src/main/java/com/sshtools/ssh2/Ssh2Session.java
Ssh2Session.setEnvironmentVariable
public boolean setEnvironmentVariable(String name, String value) throws SshException { """ The SSH2 session supports the setting of environments variables however in our experiance no server to date allows unconditional setting of variables. This method should be called before the command is started. """ ByteArrayWriter request = new ByteArrayWriter(); try { request.writeString(name); request.writeString(value); return sendRequest("env", true, request.toByteArray()); } catch (IOException ex) { throw new SshException(ex, SshException.INTERNAL_ERROR); } finally { try { request.close(); } catch (IOException e) { } } }
java
public boolean setEnvironmentVariable(String name, String value) throws SshException { ByteArrayWriter request = new ByteArrayWriter(); try { request.writeString(name); request.writeString(value); return sendRequest("env", true, request.toByteArray()); } catch (IOException ex) { throw new SshException(ex, SshException.INTERNAL_ERROR); } finally { try { request.close(); } catch (IOException e) { } } }
[ "public", "boolean", "setEnvironmentVariable", "(", "String", "name", ",", "String", "value", ")", "throws", "SshException", "{", "ByteArrayWriter", "request", "=", "new", "ByteArrayWriter", "(", ")", ";", "try", "{", "request", ".", "writeString", "(", "name", ")", ";", "request", ".", "writeString", "(", "value", ")", ";", "return", "sendRequest", "(", "\"env\"", ",", "true", ",", "request", ".", "toByteArray", "(", ")", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "SshException", "(", "ex", ",", "SshException", ".", "INTERNAL_ERROR", ")", ";", "}", "finally", "{", "try", "{", "request", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "}", "}", "}" ]
The SSH2 session supports the setting of environments variables however in our experiance no server to date allows unconditional setting of variables. This method should be called before the command is started.
[ "The", "SSH2", "session", "supports", "the", "setting", "of", "environments", "variables", "however", "in", "our", "experiance", "no", "server", "to", "date", "allows", "unconditional", "setting", "of", "variables", ".", "This", "method", "should", "be", "called", "before", "the", "command", "is", "started", "." ]
train
https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/ssh2/Ssh2Session.java#L301-L317
grpc/grpc-java
alts/src/main/java/io/grpc/alts/internal/NettyTsiHandshaker.java
NettyTsiHandshaker.createFrameProtector
TsiFrameProtector createFrameProtector(int maxFrameSize, ByteBufAllocator alloc) { """ Creates a frame protector from a completed handshake. No other methods may be called after the frame protector is created. @param maxFrameSize the requested max frame size, the callee is free to ignore. @return a new {@link io.grpc.alts.internal.TsiFrameProtector}. """ unwrapper = null; return internalHandshaker.createFrameProtector(maxFrameSize, alloc); }
java
TsiFrameProtector createFrameProtector(int maxFrameSize, ByteBufAllocator alloc) { unwrapper = null; return internalHandshaker.createFrameProtector(maxFrameSize, alloc); }
[ "TsiFrameProtector", "createFrameProtector", "(", "int", "maxFrameSize", ",", "ByteBufAllocator", "alloc", ")", "{", "unwrapper", "=", "null", ";", "return", "internalHandshaker", ".", "createFrameProtector", "(", "maxFrameSize", ",", "alloc", ")", ";", "}" ]
Creates a frame protector from a completed handshake. No other methods may be called after the frame protector is created. @param maxFrameSize the requested max frame size, the callee is free to ignore. @return a new {@link io.grpc.alts.internal.TsiFrameProtector}.
[ "Creates", "a", "frame", "protector", "from", "a", "completed", "handshake", ".", "No", "other", "methods", "may", "be", "called", "after", "the", "frame", "protector", "is", "created", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/alts/src/main/java/io/grpc/alts/internal/NettyTsiHandshaker.java#L137-L140
trellis-ldp/trellis
components/constraint-rules/src/main/java/org/trellisldp/constraint/LdpConstraints.java
LdpConstraints.propertyFilter
private static boolean propertyFilter(final Triple t, final IRI ixnModel) { """ Ensure that any LDP properties are appropriate for the interaction model """ return typeMap.getOrDefault(ixnModel, LdpConstraints::basicConstraints).test(t); }
java
private static boolean propertyFilter(final Triple t, final IRI ixnModel) { return typeMap.getOrDefault(ixnModel, LdpConstraints::basicConstraints).test(t); }
[ "private", "static", "boolean", "propertyFilter", "(", "final", "Triple", "t", ",", "final", "IRI", "ixnModel", ")", "{", "return", "typeMap", ".", "getOrDefault", "(", "ixnModel", ",", "LdpConstraints", "::", "basicConstraints", ")", ".", "test", "(", "t", ")", ";", "}" ]
Ensure that any LDP properties are appropriate for the interaction model
[ "Ensure", "that", "any", "LDP", "properties", "are", "appropriate", "for", "the", "interaction", "model" ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/components/constraint-rules/src/main/java/org/trellisldp/constraint/LdpConstraints.java#L121-L123
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/output/AbstractOutputWriter.java
AbstractOutputWriter.getBooleanSetting
protected boolean getBooleanSetting(String name, boolean defaultValue) { """ Convert value of this setting to a Java <b>boolean</b> (via {@link Boolean#parseBoolean(String)}). If the property is not found, the <code>defaultValue</code> is returned. @param name name of the property @param defaultValue default value if the property is not defined. @return int value of the property or <code>defaultValue</code> if the property is not defined. """ if (settings.containsKey(name)) { String value = settings.get(name).toString(); return Boolean.parseBoolean(value); } else { return defaultValue; } }
java
protected boolean getBooleanSetting(String name, boolean defaultValue) { if (settings.containsKey(name)) { String value = settings.get(name).toString(); return Boolean.parseBoolean(value); } else { return defaultValue; } }
[ "protected", "boolean", "getBooleanSetting", "(", "String", "name", ",", "boolean", "defaultValue", ")", "{", "if", "(", "settings", ".", "containsKey", "(", "name", ")", ")", "{", "String", "value", "=", "settings", ".", "get", "(", "name", ")", ".", "toString", "(", ")", ";", "return", "Boolean", ".", "parseBoolean", "(", "value", ")", ";", "}", "else", "{", "return", "defaultValue", ";", "}", "}" ]
Convert value of this setting to a Java <b>boolean</b> (via {@link Boolean#parseBoolean(String)}). If the property is not found, the <code>defaultValue</code> is returned. @param name name of the property @param defaultValue default value if the property is not defined. @return int value of the property or <code>defaultValue</code> if the property is not defined.
[ "Convert", "value", "of", "this", "setting", "to", "a", "Java", "<b", ">", "boolean<", "/", "b", ">", "(", "via", "{", "@link", "Boolean#parseBoolean", "(", "String", ")", "}", ")", "." ]
train
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/output/AbstractOutputWriter.java#L154-L163
betfair/cougar
cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/AbstractHttpCommandProcessor.java
AbstractHttpCommandProcessor.writeIdentity
public void writeIdentity(List<IdentityToken> tokens, IdentityTokenIOAdapter ioAdapter) { """ Rewrites the caller's credentials back into the HTTP response. The main use case for this is rewriting SSO tokens, which may change and the client needs to know the new value. @param tokens - the identity tokens to marshall @param ioAdapter - the adapter to detail with the transport specific IO requirements """ if (ioAdapter != null && ioAdapter.isRewriteSupported()) { ioAdapter.rewriteIdentityTokens(tokens); } }
java
public void writeIdentity(List<IdentityToken> tokens, IdentityTokenIOAdapter ioAdapter) { if (ioAdapter != null && ioAdapter.isRewriteSupported()) { ioAdapter.rewriteIdentityTokens(tokens); } }
[ "public", "void", "writeIdentity", "(", "List", "<", "IdentityToken", ">", "tokens", ",", "IdentityTokenIOAdapter", "ioAdapter", ")", "{", "if", "(", "ioAdapter", "!=", "null", "&&", "ioAdapter", ".", "isRewriteSupported", "(", ")", ")", "{", "ioAdapter", ".", "rewriteIdentityTokens", "(", "tokens", ")", ";", "}", "}" ]
Rewrites the caller's credentials back into the HTTP response. The main use case for this is rewriting SSO tokens, which may change and the client needs to know the new value. @param tokens - the identity tokens to marshall @param ioAdapter - the adapter to detail with the transport specific IO requirements
[ "Rewrites", "the", "caller", "s", "credentials", "back", "into", "the", "HTTP", "response", ".", "The", "main", "use", "case", "for", "this", "is", "rewriting", "SSO", "tokens", "which", "may", "change", "and", "the", "client", "needs", "to", "know", "the", "new", "value", "." ]
train
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jetty-transport/src/main/java/com/betfair/cougar/transport/impl/protocol/http/AbstractHttpCommandProcessor.java#L270-L274
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java
ByteUtils.bytesToString
public static final String bytesToString( byte[] data, int[] offset ) { """ Return the <code>String</code> represented by the bytes in <code>data</code> staring at offset <code>offset[0]</code>. This method relies on the user using the corresponding <code>stringToBytes</code> method to encode the <code>String</code>, so that it may properly retrieve the <code>String</code> length. @param data the array from which to read @param offset A single element array whose first element is the index in data from which to begin reading on function entry, and which on function exit has been incremented by the number of bytes read. @return the value of the <code>String</code> decoded """ offset[0] = 0; int length = bytesToInt(data, offset); String st = null; if ((length < 0) || (length > data.length)) { st = new String(data); } else { st = new String(data, offset[0], length); } offset[0] += length; return st; }
java
public static final String bytesToString( byte[] data, int[] offset ) { offset[0] = 0; int length = bytesToInt(data, offset); String st = null; if ((length < 0) || (length > data.length)) { st = new String(data); } else { st = new String(data, offset[0], length); } offset[0] += length; return st; }
[ "public", "static", "final", "String", "bytesToString", "(", "byte", "[", "]", "data", ",", "int", "[", "]", "offset", ")", "{", "offset", "[", "0", "]", "=", "0", ";", "int", "length", "=", "bytesToInt", "(", "data", ",", "offset", ")", ";", "String", "st", "=", "null", ";", "if", "(", "(", "length", "<", "0", ")", "||", "(", "length", ">", "data", ".", "length", ")", ")", "{", "st", "=", "new", "String", "(", "data", ")", ";", "}", "else", "{", "st", "=", "new", "String", "(", "data", ",", "offset", "[", "0", "]", ",", "length", ")", ";", "}", "offset", "[", "0", "]", "+=", "length", ";", "return", "st", ";", "}" ]
Return the <code>String</code> represented by the bytes in <code>data</code> staring at offset <code>offset[0]</code>. This method relies on the user using the corresponding <code>stringToBytes</code> method to encode the <code>String</code>, so that it may properly retrieve the <code>String</code> length. @param data the array from which to read @param offset A single element array whose first element is the index in data from which to begin reading on function entry, and which on function exit has been incremented by the number of bytes read. @return the value of the <code>String</code> decoded
[ "Return", "the", "<code", ">", "String<", "/", "code", ">", "represented", "by", "the", "bytes", "in", "<code", ">", "data<", "/", "code", ">", "staring", "at", "offset", "<code", ">", "offset", "[", "0", "]", "<", "/", "code", ">", ".", "This", "method", "relies", "on", "the", "user", "using", "the", "corresponding", "<code", ">", "stringToBytes<", "/", "code", ">", "method", "to", "encode", "the", "<code", ">", "String<", "/", "code", ">", "so", "that", "it", "may", "properly", "retrieve", "the", "<code", ">", "String<", "/", "code", ">", "length", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/io/dxfdwg/libs/dwg/utils/ByteUtils.java#L256-L271
nextreports/nextreports-engine
src/ro/nextreports/engine/util/ReportUtil.java
ReportUtil.isValidSqlWithMessage
public static String isValidSqlWithMessage(Connection con, String sql, List<QueryParameter> parameters) { """ Test if sql with parameters is valid @param con database connection @param sql sql @return return message error if sql is not valid, null otherwise """ try { QueryUtil qu = new QueryUtil(con, DialectUtil.getDialect(con)); Map<String, QueryParameter> params = new HashMap<String, QueryParameter>(); for (QueryParameter qp : parameters) { params.put(qp.getName(), qp); } qu.getColumnNames(sql, params); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); return ex.getMessage(); } return null; }
java
public static String isValidSqlWithMessage(Connection con, String sql, List<QueryParameter> parameters) { try { QueryUtil qu = new QueryUtil(con, DialectUtil.getDialect(con)); Map<String, QueryParameter> params = new HashMap<String, QueryParameter>(); for (QueryParameter qp : parameters) { params.put(qp.getName(), qp); } qu.getColumnNames(sql, params); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); return ex.getMessage(); } return null; }
[ "public", "static", "String", "isValidSqlWithMessage", "(", "Connection", "con", ",", "String", "sql", ",", "List", "<", "QueryParameter", ">", "parameters", ")", "{", "try", "{", "QueryUtil", "qu", "=", "new", "QueryUtil", "(", "con", ",", "DialectUtil", ".", "getDialect", "(", "con", ")", ")", ";", "Map", "<", "String", ",", "QueryParameter", ">", "params", "=", "new", "HashMap", "<", "String", ",", "QueryParameter", ">", "(", ")", ";", "for", "(", "QueryParameter", "qp", ":", "parameters", ")", "{", "params", ".", "put", "(", "qp", ".", "getName", "(", ")", ",", "qp", ")", ";", "}", "qu", ".", "getColumnNames", "(", "sql", ",", "params", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "error", "(", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "return", "ex", ".", "getMessage", "(", ")", ";", "}", "return", "null", ";", "}" ]
Test if sql with parameters is valid @param con database connection @param sql sql @return return message error if sql is not valid, null otherwise
[ "Test", "if", "sql", "with", "parameters", "is", "valid" ]
train
https://github.com/nextreports/nextreports-engine/blob/a847575a9298b5fce63b88961190c5b83ddccc44/src/ro/nextreports/engine/util/ReportUtil.java#L761-L774
Azure/azure-sdk-for-java
network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/LoadBalancerLoadBalancingRulesInner.java
LoadBalancerLoadBalancingRulesInner.listAsync
public Observable<Page<LoadBalancingRuleInner>> listAsync(final String resourceGroupName, final String loadBalancerName) { """ Gets all the load balancing rules in a load balancer. @param resourceGroupName The name of the resource group. @param loadBalancerName The name of the load balancer. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;LoadBalancingRuleInner&gt; object """ return listWithServiceResponseAsync(resourceGroupName, loadBalancerName) .map(new Func1<ServiceResponse<Page<LoadBalancingRuleInner>>, Page<LoadBalancingRuleInner>>() { @Override public Page<LoadBalancingRuleInner> call(ServiceResponse<Page<LoadBalancingRuleInner>> response) { return response.body(); } }); }
java
public Observable<Page<LoadBalancingRuleInner>> listAsync(final String resourceGroupName, final String loadBalancerName) { return listWithServiceResponseAsync(resourceGroupName, loadBalancerName) .map(new Func1<ServiceResponse<Page<LoadBalancingRuleInner>>, Page<LoadBalancingRuleInner>>() { @Override public Page<LoadBalancingRuleInner> call(ServiceResponse<Page<LoadBalancingRuleInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "LoadBalancingRuleInner", ">", ">", "listAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "loadBalancerName", ")", "{", "return", "listWithServiceResponseAsync", "(", "resourceGroupName", ",", "loadBalancerName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "LoadBalancingRuleInner", ">", ">", ",", "Page", "<", "LoadBalancingRuleInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "LoadBalancingRuleInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "LoadBalancingRuleInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets all the load balancing rules in a load balancer. @param resourceGroupName The name of the resource group. @param loadBalancerName The name of the load balancer. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;LoadBalancingRuleInner&gt; object
[ "Gets", "all", "the", "load", "balancing", "rules", "in", "a", "load", "balancer", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/LoadBalancerLoadBalancingRulesInner.java#L123-L131
SonarSource/sonarqube
sonar-core/src/main/java/org/sonar/core/platform/PluginLoader.java
PluginLoader.instantiatePluginClasses
@VisibleForTesting Map<String, Plugin> instantiatePluginClasses(Map<PluginClassLoaderDef, ClassLoader> classloaders) { """ Instantiates collection of {@link org.sonar.api.Plugin} according to given metadata and classloaders @return the instances grouped by plugin key @throws IllegalStateException if at least one plugin can't be correctly loaded """ // instantiate plugins Map<String, Plugin> instancesByPluginKey = new HashMap<>(); for (Map.Entry<PluginClassLoaderDef, ClassLoader> entry : classloaders.entrySet()) { PluginClassLoaderDef def = entry.getKey(); ClassLoader classLoader = entry.getValue(); // the same classloader can be used by multiple plugins for (Map.Entry<String, String> mainClassEntry : def.getMainClassesByPluginKey().entrySet()) { String pluginKey = mainClassEntry.getKey(); String mainClass = mainClassEntry.getValue(); try { instancesByPluginKey.put(pluginKey, (Plugin) classLoader.loadClass(mainClass).newInstance()); } catch (UnsupportedClassVersionError e) { throw new IllegalStateException(String.format("The plugin [%s] does not support Java %s", pluginKey, SystemUtils.JAVA_VERSION_TRIMMED), e); } catch (Throwable e) { throw new IllegalStateException(String.format( "Fail to instantiate class [%s] of plugin [%s]", mainClass, pluginKey), e); } } } return instancesByPluginKey; }
java
@VisibleForTesting Map<String, Plugin> instantiatePluginClasses(Map<PluginClassLoaderDef, ClassLoader> classloaders) { // instantiate plugins Map<String, Plugin> instancesByPluginKey = new HashMap<>(); for (Map.Entry<PluginClassLoaderDef, ClassLoader> entry : classloaders.entrySet()) { PluginClassLoaderDef def = entry.getKey(); ClassLoader classLoader = entry.getValue(); // the same classloader can be used by multiple plugins for (Map.Entry<String, String> mainClassEntry : def.getMainClassesByPluginKey().entrySet()) { String pluginKey = mainClassEntry.getKey(); String mainClass = mainClassEntry.getValue(); try { instancesByPluginKey.put(pluginKey, (Plugin) classLoader.loadClass(mainClass).newInstance()); } catch (UnsupportedClassVersionError e) { throw new IllegalStateException(String.format("The plugin [%s] does not support Java %s", pluginKey, SystemUtils.JAVA_VERSION_TRIMMED), e); } catch (Throwable e) { throw new IllegalStateException(String.format( "Fail to instantiate class [%s] of plugin [%s]", mainClass, pluginKey), e); } } } return instancesByPluginKey; }
[ "@", "VisibleForTesting", "Map", "<", "String", ",", "Plugin", ">", "instantiatePluginClasses", "(", "Map", "<", "PluginClassLoaderDef", ",", "ClassLoader", ">", "classloaders", ")", "{", "// instantiate plugins", "Map", "<", "String", ",", "Plugin", ">", "instancesByPluginKey", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "PluginClassLoaderDef", ",", "ClassLoader", ">", "entry", ":", "classloaders", ".", "entrySet", "(", ")", ")", "{", "PluginClassLoaderDef", "def", "=", "entry", ".", "getKey", "(", ")", ";", "ClassLoader", "classLoader", "=", "entry", ".", "getValue", "(", ")", ";", "// the same classloader can be used by multiple plugins", "for", "(", "Map", ".", "Entry", "<", "String", ",", "String", ">", "mainClassEntry", ":", "def", ".", "getMainClassesByPluginKey", "(", ")", ".", "entrySet", "(", ")", ")", "{", "String", "pluginKey", "=", "mainClassEntry", ".", "getKey", "(", ")", ";", "String", "mainClass", "=", "mainClassEntry", ".", "getValue", "(", ")", ";", "try", "{", "instancesByPluginKey", ".", "put", "(", "pluginKey", ",", "(", "Plugin", ")", "classLoader", ".", "loadClass", "(", "mainClass", ")", ".", "newInstance", "(", ")", ")", ";", "}", "catch", "(", "UnsupportedClassVersionError", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "String", ".", "format", "(", "\"The plugin [%s] does not support Java %s\"", ",", "pluginKey", ",", "SystemUtils", ".", "JAVA_VERSION_TRIMMED", ")", ",", "e", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "String", ".", "format", "(", "\"Fail to instantiate class [%s] of plugin [%s]\"", ",", "mainClass", ",", "pluginKey", ")", ",", "e", ")", ";", "}", "}", "}", "return", "instancesByPluginKey", ";", "}" ]
Instantiates collection of {@link org.sonar.api.Plugin} according to given metadata and classloaders @return the instances grouped by plugin key @throws IllegalStateException if at least one plugin can't be correctly loaded
[ "Instantiates", "collection", "of", "{", "@link", "org", ".", "sonar", ".", "api", ".", "Plugin", "}", "according", "to", "given", "metadata", "and", "classloaders" ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-core/src/main/java/org/sonar/core/platform/PluginLoader.java#L115-L139
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalReader.java
JournalReader.getInstance
public static JournalReader getInstance(Map<String, String> parameters, String role, JournalRecoveryLog recoveryLog, ServerInterface server) throws ModuleInitializationException { """ Create an instance of the proper JournalReader child class, as determined by the server parameters. """ try { Object journalReader = JournalHelper .createInstanceAccordingToParameter(PARAMETER_JOURNAL_READER_CLASSNAME, new Class[] { Map.class, String.class, JournalRecoveryLog.class, ServerInterface.class}, new Object[] { parameters, role, recoveryLog, server}, parameters); logger.info("JournalReader is " + journalReader.toString()); return (JournalReader) journalReader; } catch (JournalException e) { String msg = "Can't create JournalReader"; logger.error(msg, e); throw new ModuleInitializationException(msg, role, e); } }
java
public static JournalReader getInstance(Map<String, String> parameters, String role, JournalRecoveryLog recoveryLog, ServerInterface server) throws ModuleInitializationException { try { Object journalReader = JournalHelper .createInstanceAccordingToParameter(PARAMETER_JOURNAL_READER_CLASSNAME, new Class[] { Map.class, String.class, JournalRecoveryLog.class, ServerInterface.class}, new Object[] { parameters, role, recoveryLog, server}, parameters); logger.info("JournalReader is " + journalReader.toString()); return (JournalReader) journalReader; } catch (JournalException e) { String msg = "Can't create JournalReader"; logger.error(msg, e); throw new ModuleInitializationException(msg, role, e); } }
[ "public", "static", "JournalReader", "getInstance", "(", "Map", "<", "String", ",", "String", ">", "parameters", ",", "String", "role", ",", "JournalRecoveryLog", "recoveryLog", ",", "ServerInterface", "server", ")", "throws", "ModuleInitializationException", "{", "try", "{", "Object", "journalReader", "=", "JournalHelper", ".", "createInstanceAccordingToParameter", "(", "PARAMETER_JOURNAL_READER_CLASSNAME", ",", "new", "Class", "[", "]", "{", "Map", ".", "class", ",", "String", ".", "class", ",", "JournalRecoveryLog", ".", "class", ",", "ServerInterface", ".", "class", "}", ",", "new", "Object", "[", "]", "{", "parameters", ",", "role", ",", "recoveryLog", ",", "server", "}", ",", "parameters", ")", ";", "logger", ".", "info", "(", "\"JournalReader is \"", "+", "journalReader", ".", "toString", "(", ")", ")", ";", "return", "(", "JournalReader", ")", "journalReader", ";", "}", "catch", "(", "JournalException", "e", ")", "{", "String", "msg", "=", "\"Can't create JournalReader\"", ";", "logger", ".", "error", "(", "msg", ",", "e", ")", ";", "throw", "new", "ModuleInitializationException", "(", "msg", ",", "role", ",", "e", ")", ";", "}", "}" ]
Create an instance of the proper JournalReader child class, as determined by the server parameters.
[ "Create", "an", "instance", "of", "the", "proper", "JournalReader", "child", "class", "as", "determined", "by", "the", "server", "parameters", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/JournalReader.java#L66-L94
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/JoinableResourceBundleImpl.java
JoinableResourceBundleImpl.setVariants
@Override public void setVariants(Map<String, VariantSet> variantSets) { """ Set the list of variants for variant resources @param variantSets """ if (variantSets != null) { this.variants = new TreeMap<>(variantSets); variantKeys = VariantUtils.getAllVariantKeys(this.variants); } }
java
@Override public void setVariants(Map<String, VariantSet> variantSets) { if (variantSets != null) { this.variants = new TreeMap<>(variantSets); variantKeys = VariantUtils.getAllVariantKeys(this.variants); } }
[ "@", "Override", "public", "void", "setVariants", "(", "Map", "<", "String", ",", "VariantSet", ">", "variantSets", ")", "{", "if", "(", "variantSets", "!=", "null", ")", "{", "this", ".", "variants", "=", "new", "TreeMap", "<>", "(", "variantSets", ")", ";", "variantKeys", "=", "VariantUtils", ".", "getAllVariantKeys", "(", "this", ".", "variants", ")", ";", "}", "}" ]
Set the list of variants for variant resources @param variantSets
[ "Set", "the", "list", "of", "variants", "for", "variant", "resources" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/JoinableResourceBundleImpl.java#L318-L325
prestodb/presto
presto-spi/src/main/java/com/facebook/presto/spi/type/UnscaledDecimal128Arithmetic.java
UnscaledDecimal128Arithmetic.scaleUpFiveDestructive
private static void scaleUpFiveDestructive(Slice decimal, int fiveScale) { """ Scale up the value for 5**fiveScale (decimal := decimal * 5**fiveScale). """ while (fiveScale > 0) { int powerFive = Math.min(fiveScale, MAX_POWER_OF_FIVE_INT); fiveScale -= powerFive; int multiplier = POWERS_OF_FIVES_INT[powerFive]; multiplyDestructive(decimal, multiplier); } }
java
private static void scaleUpFiveDestructive(Slice decimal, int fiveScale) { while (fiveScale > 0) { int powerFive = Math.min(fiveScale, MAX_POWER_OF_FIVE_INT); fiveScale -= powerFive; int multiplier = POWERS_OF_FIVES_INT[powerFive]; multiplyDestructive(decimal, multiplier); } }
[ "private", "static", "void", "scaleUpFiveDestructive", "(", "Slice", "decimal", ",", "int", "fiveScale", ")", "{", "while", "(", "fiveScale", ">", "0", ")", "{", "int", "powerFive", "=", "Math", ".", "min", "(", "fiveScale", ",", "MAX_POWER_OF_FIVE_INT", ")", ";", "fiveScale", "-=", "powerFive", ";", "int", "multiplier", "=", "POWERS_OF_FIVES_INT", "[", "powerFive", "]", ";", "multiplyDestructive", "(", "decimal", ",", "multiplier", ")", ";", "}", "}" ]
Scale up the value for 5**fiveScale (decimal := decimal * 5**fiveScale).
[ "Scale", "up", "the", "value", "for", "5", "**", "fiveScale", "(", "decimal", ":", "=", "decimal", "*", "5", "**", "fiveScale", ")", "." ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-spi/src/main/java/com/facebook/presto/spi/type/UnscaledDecimal128Arithmetic.java#L867-L875
networknt/light-4j
client/src/main/java/com/networknt/client/ssl/APINameChecker.java
APINameChecker.verifyAndThrow
public static void verifyAndThrow(final String name, final X509Certificate cert) throws CertificateException { """ Perform server identify check using given name and throw CertificateException if the check fails. @param name @param cert @throws CertificateException """ if (!verify(name, cert)) { throw new CertificateException("No name matching " + name + " found"); } }
java
public static void verifyAndThrow(final String name, final X509Certificate cert) throws CertificateException{ if (!verify(name, cert)) { throw new CertificateException("No name matching " + name + " found"); } }
[ "public", "static", "void", "verifyAndThrow", "(", "final", "String", "name", ",", "final", "X509Certificate", "cert", ")", "throws", "CertificateException", "{", "if", "(", "!", "verify", "(", "name", ",", "cert", ")", ")", "{", "throw", "new", "CertificateException", "(", "\"No name matching \"", "+", "name", "+", "\" found\"", ")", ";", "}", "}" ]
Perform server identify check using given name and throw CertificateException if the check fails. @param name @param cert @throws CertificateException
[ "Perform", "server", "identify", "check", "using", "given", "name", "and", "throw", "CertificateException", "if", "the", "check", "fails", "." ]
train
https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/client/src/main/java/com/networknt/client/ssl/APINameChecker.java#L54-L58
bremersee/comparator
src/main/java/org/bremersee/comparator/ComparatorUtils.java
ComparatorUtils.doSetAscRecursively
public static void doSetAscRecursively(ComparatorItem comparatorItem, boolean asc) { """ Sets the sort order of all items. @param comparatorItem the (root) item @param asc the new sort order """ ComparatorItem tmp = comparatorItem; while (tmp != null) { tmp.setAsc(asc); tmp = tmp.getNextComparatorItem(); } }
java
public static void doSetAscRecursively(ComparatorItem comparatorItem, boolean asc) { ComparatorItem tmp = comparatorItem; while (tmp != null) { tmp.setAsc(asc); tmp = tmp.getNextComparatorItem(); } }
[ "public", "static", "void", "doSetAscRecursively", "(", "ComparatorItem", "comparatorItem", ",", "boolean", "asc", ")", "{", "ComparatorItem", "tmp", "=", "comparatorItem", ";", "while", "(", "tmp", "!=", "null", ")", "{", "tmp", ".", "setAsc", "(", "asc", ")", ";", "tmp", "=", "tmp", ".", "getNextComparatorItem", "(", ")", ";", "}", "}" ]
Sets the sort order of all items. @param comparatorItem the (root) item @param asc the new sort order
[ "Sets", "the", "sort", "order", "of", "all", "items", "." ]
train
https://github.com/bremersee/comparator/blob/6958e6e28a62589106705062f8ffc201a87d9b2a/src/main/java/org/bremersee/comparator/ComparatorUtils.java#L38-L44
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Asserter.java
Asserter.assertCurrentActivity
public void assertCurrentActivity(String message, String name) { """ Asserts that an expected {@link Activity} is currently active one. @param message the message that should be displayed if the assert fails @param name the name of the {@code Activity} that is expected to be active e.g. {@code "MyActivity"} """ boolean foundActivity = waiter.waitForActivity(name); if(!foundActivity){ Activity activity = activityUtils.getCurrentActivity(); if(activity != null){ Assert.assertEquals(message, name, activity.getClass().getSimpleName()); } else{ Assert.assertEquals(message, name, "No actvity found"); } } }
java
public void assertCurrentActivity(String message, String name) { boolean foundActivity = waiter.waitForActivity(name); if(!foundActivity){ Activity activity = activityUtils.getCurrentActivity(); if(activity != null){ Assert.assertEquals(message, name, activity.getClass().getSimpleName()); } else{ Assert.assertEquals(message, name, "No actvity found"); } } }
[ "public", "void", "assertCurrentActivity", "(", "String", "message", ",", "String", "name", ")", "{", "boolean", "foundActivity", "=", "waiter", ".", "waitForActivity", "(", "name", ")", ";", "if", "(", "!", "foundActivity", ")", "{", "Activity", "activity", "=", "activityUtils", ".", "getCurrentActivity", "(", ")", ";", "if", "(", "activity", "!=", "null", ")", "{", "Assert", ".", "assertEquals", "(", "message", ",", "name", ",", "activity", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "}", "else", "{", "Assert", ".", "assertEquals", "(", "message", ",", "name", ",", "\"No actvity found\"", ")", ";", "}", "}", "}" ]
Asserts that an expected {@link Activity} is currently active one. @param message the message that should be displayed if the assert fails @param name the name of the {@code Activity} that is expected to be active e.g. {@code "MyActivity"}
[ "Asserts", "that", "an", "expected", "{", "@link", "Activity", "}", "is", "currently", "active", "one", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Asserter.java#L37-L49
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataMaxCardinalityImpl_CustomFieldSerializer.java
OWLDataMaxCardinalityImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataMaxCardinalityImpl instance) throws SerializationException { """ Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful """ serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataMaxCardinalityImpl instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLDataMaxCardinalityImpl", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamWriter", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataMaxCardinalityImpl_CustomFieldSerializer.java#L73-L76
facebook/fresco
drawee/src/main/java/com/facebook/drawee/drawable/RoundedCornersDrawable.java
RoundedCornersDrawable.setBorder
@Override public void setBorder(int color, float width) { """ Sets the border @param color of the border @param width of the border """ mBorderColor = color; mBorderWidth = width; updatePath(); invalidateSelf(); }
java
@Override public void setBorder(int color, float width) { mBorderColor = color; mBorderWidth = width; updatePath(); invalidateSelf(); }
[ "@", "Override", "public", "void", "setBorder", "(", "int", "color", ",", "float", "width", ")", "{", "mBorderColor", "=", "color", ";", "mBorderWidth", "=", "width", ";", "updatePath", "(", ")", ";", "invalidateSelf", "(", ")", ";", "}" ]
Sets the border @param color of the border @param width of the border
[ "Sets", "the", "border" ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/drawable/RoundedCornersDrawable.java#L155-L161
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/stat/gslb/gslbdomain_stats.java
gslbdomain_stats.get
public static gslbdomain_stats get(nitro_service service, String name) throws Exception { """ Use this API to fetch statistics of gslbdomain_stats resource of given name . """ gslbdomain_stats obj = new gslbdomain_stats(); obj.set_name(name); gslbdomain_stats response = (gslbdomain_stats) obj.stat_resource(service); return response; }
java
public static gslbdomain_stats get(nitro_service service, String name) throws Exception{ gslbdomain_stats obj = new gslbdomain_stats(); obj.set_name(name); gslbdomain_stats response = (gslbdomain_stats) obj.stat_resource(service); return response; }
[ "public", "static", "gslbdomain_stats", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "gslbdomain_stats", "obj", "=", "new", "gslbdomain_stats", "(", ")", ";", "obj", ".", "set_name", "(", "name", ")", ";", "gslbdomain_stats", "response", "=", "(", "gslbdomain_stats", ")", "obj", ".", "stat_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch statistics of gslbdomain_stats resource of given name .
[ "Use", "this", "API", "to", "fetch", "statistics", "of", "gslbdomain_stats", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/gslb/gslbdomain_stats.java#L149-L154
Impetus/Kundera
src/kundera-rdbms/src/main/java/com/impetus/client/rdbms/HibernateClient.java
HibernateClient.onNativeUpdate
public int onNativeUpdate(String query, Map<Parameter, Object> parameterMap) { """ On native update. @param query the query @param parameterMap the parameter map @return the int """ s = getStatelessSession(); Query q = s.createSQLQuery(query); setParameters(parameterMap, q); // Transaction tx = s.getTransaction() == null ? s.beginTransaction(): // s.getTransaction(); // tx.begin(); int i = q.executeUpdate(); // tx.commit(); return i; }
java
public int onNativeUpdate(String query, Map<Parameter, Object> parameterMap) { s = getStatelessSession(); Query q = s.createSQLQuery(query); setParameters(parameterMap, q); // Transaction tx = s.getTransaction() == null ? s.beginTransaction(): // s.getTransaction(); // tx.begin(); int i = q.executeUpdate(); // tx.commit(); return i; }
[ "public", "int", "onNativeUpdate", "(", "String", "query", ",", "Map", "<", "Parameter", ",", "Object", ">", "parameterMap", ")", "{", "s", "=", "getStatelessSession", "(", ")", ";", "Query", "q", "=", "s", ".", "createSQLQuery", "(", "query", ")", ";", "setParameters", "(", "parameterMap", ",", "q", ")", ";", "// Transaction tx = s.getTransaction() == null ? s.beginTransaction():", "// s.getTransaction();", "// tx.begin();", "int", "i", "=", "q", ".", "executeUpdate", "(", ")", ";", "// tx.commit();", "return", "i", ";", "}" ]
On native update. @param query the query @param parameterMap the parameter map @return the int
[ "On", "native", "update", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-rdbms/src/main/java/com/impetus/client/rdbms/HibernateClient.java#L616-L632
elki-project/elki
elki-data-generator/src/main/java/de/lmu/ifi/dbs/elki/datasource/GeneratorXMLDatabaseConnection.java
GeneratorXMLDatabaseConnection.processElementTranslate
private void processElementTranslate(GeneratorSingleCluster cluster, Node cur) { """ Process a 'translate' Element in the XML stream. @param cluster @param cur Current document nod """ double[] offset = null; String vstr = ((Element) cur).getAttribute(ATTR_VECTOR); if(vstr != null && vstr.length() > 0) { offset = parseVector(vstr); } if(offset == null) { throw new AbortException("No translation vector given."); } // *** add new translation cluster.addTranslation(offset); // TODO: check for unknown attributes. XMLNodeIterator iter = new XMLNodeIterator(cur.getFirstChild()); while(iter.hasNext()) { Node child = iter.next(); if(child.getNodeType() == Node.ELEMENT_NODE) { LOG.warning("Unknown element in XML specification file: " + child.getNodeName()); } } }
java
private void processElementTranslate(GeneratorSingleCluster cluster, Node cur) { double[] offset = null; String vstr = ((Element) cur).getAttribute(ATTR_VECTOR); if(vstr != null && vstr.length() > 0) { offset = parseVector(vstr); } if(offset == null) { throw new AbortException("No translation vector given."); } // *** add new translation cluster.addTranslation(offset); // TODO: check for unknown attributes. XMLNodeIterator iter = new XMLNodeIterator(cur.getFirstChild()); while(iter.hasNext()) { Node child = iter.next(); if(child.getNodeType() == Node.ELEMENT_NODE) { LOG.warning("Unknown element in XML specification file: " + child.getNodeName()); } } }
[ "private", "void", "processElementTranslate", "(", "GeneratorSingleCluster", "cluster", ",", "Node", "cur", ")", "{", "double", "[", "]", "offset", "=", "null", ";", "String", "vstr", "=", "(", "(", "Element", ")", "cur", ")", ".", "getAttribute", "(", "ATTR_VECTOR", ")", ";", "if", "(", "vstr", "!=", "null", "&&", "vstr", ".", "length", "(", ")", ">", "0", ")", "{", "offset", "=", "parseVector", "(", "vstr", ")", ";", "}", "if", "(", "offset", "==", "null", ")", "{", "throw", "new", "AbortException", "(", "\"No translation vector given.\"", ")", ";", "}", "// *** add new translation", "cluster", ".", "addTranslation", "(", "offset", ")", ";", "// TODO: check for unknown attributes.", "XMLNodeIterator", "iter", "=", "new", "XMLNodeIterator", "(", "cur", ".", "getFirstChild", "(", ")", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "Node", "child", "=", "iter", ".", "next", "(", ")", ";", "if", "(", "child", ".", "getNodeType", "(", ")", "==", "Node", ".", "ELEMENT_NODE", ")", "{", "LOG", ".", "warning", "(", "\"Unknown element in XML specification file: \"", "+", "child", ".", "getNodeName", "(", ")", ")", ";", "}", "}", "}" ]
Process a 'translate' Element in the XML stream. @param cluster @param cur Current document nod
[ "Process", "a", "translate", "Element", "in", "the", "XML", "stream", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-data-generator/src/main/java/de/lmu/ifi/dbs/elki/datasource/GeneratorXMLDatabaseConnection.java#L572-L593
jbundle/jbundle
thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/ThinApplet.java
ThinApplet.addSubPanels
public boolean addSubPanels(Container parent, int options) { """ Add any applet sub-panel(s) now. Usually, you override this, although for a simple screen, just pass a screen=class param. @param parent The parent to add the new screen to. """ String strScreen = this.getProperty(Params.SCREEN); if ((strScreen == null) || (strScreen.length() == 0)) this.setProperty(Params.SCREEN, INITIAL_SCREEN); boolean success = super.addSubPanels(parent, options); if (success) if (strScreen == null) this.getProperties().remove(Params.SCREEN); return success; }
java
public boolean addSubPanels(Container parent, int options) { String strScreen = this.getProperty(Params.SCREEN); if ((strScreen == null) || (strScreen.length() == 0)) this.setProperty(Params.SCREEN, INITIAL_SCREEN); boolean success = super.addSubPanels(parent, options); if (success) if (strScreen == null) this.getProperties().remove(Params.SCREEN); return success; }
[ "public", "boolean", "addSubPanels", "(", "Container", "parent", ",", "int", "options", ")", "{", "String", "strScreen", "=", "this", ".", "getProperty", "(", "Params", ".", "SCREEN", ")", ";", "if", "(", "(", "strScreen", "==", "null", ")", "||", "(", "strScreen", ".", "length", "(", ")", "==", "0", ")", ")", "this", ".", "setProperty", "(", "Params", ".", "SCREEN", ",", "INITIAL_SCREEN", ")", ";", "boolean", "success", "=", "super", ".", "addSubPanels", "(", "parent", ",", "options", ")", ";", "if", "(", "success", ")", "if", "(", "strScreen", "==", "null", ")", "this", ".", "getProperties", "(", ")", ".", "remove", "(", "Params", ".", "SCREEN", ")", ";", "return", "success", ";", "}" ]
Add any applet sub-panel(s) now. Usually, you override this, although for a simple screen, just pass a screen=class param. @param parent The parent to add the new screen to.
[ "Add", "any", "applet", "sub", "-", "panel", "(", "s", ")", "now", ".", "Usually", "you", "override", "this", "although", "for", "a", "simple", "screen", "just", "pass", "a", "screen", "=", "class", "param", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/screen/screen/src/main/java/org/jbundle/thin/base/screen/ThinApplet.java#L80-L90
alkacon/opencms-core
src/org/opencms/util/CmsStringUtil.java
CmsStringUtil.mapAsString
public static <K, V> String mapAsString(Map<K, V> map, String sepItem, String sepKeyval) { """ Returns a string representation for the given map using the given separators.<p> @param <K> type of map keys @param <V> type of map values @param map the map to write @param sepItem the item separator string @param sepKeyval the key-value pair separator string @return the string representation for the given map """ StringBuffer string = new StringBuffer(128); Iterator<Map.Entry<K, V>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); string.append(entry.getKey()); string.append(sepKeyval); string.append(entry.getValue()); if (it.hasNext()) { string.append(sepItem); } } return string.toString(); }
java
public static <K, V> String mapAsString(Map<K, V> map, String sepItem, String sepKeyval) { StringBuffer string = new StringBuffer(128); Iterator<Map.Entry<K, V>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); string.append(entry.getKey()); string.append(sepKeyval); string.append(entry.getValue()); if (it.hasNext()) { string.append(sepItem); } } return string.toString(); }
[ "public", "static", "<", "K", ",", "V", ">", "String", "mapAsString", "(", "Map", "<", "K", ",", "V", ">", "map", ",", "String", "sepItem", ",", "String", "sepKeyval", ")", "{", "StringBuffer", "string", "=", "new", "StringBuffer", "(", "128", ")", ";", "Iterator", "<", "Map", ".", "Entry", "<", "K", ",", "V", ">", ">", "it", "=", "map", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "Map", ".", "Entry", "<", "K", ",", "V", ">", "entry", "=", "it", ".", "next", "(", ")", ";", "string", ".", "append", "(", "entry", ".", "getKey", "(", ")", ")", ";", "string", ".", "append", "(", "sepKeyval", ")", ";", "string", ".", "append", "(", "entry", ".", "getValue", "(", ")", ")", ";", "if", "(", "it", ".", "hasNext", "(", ")", ")", "{", "string", ".", "append", "(", "sepItem", ")", ";", "}", "}", "return", "string", ".", "toString", "(", ")", ";", "}" ]
Returns a string representation for the given map using the given separators.<p> @param <K> type of map keys @param <V> type of map values @param map the map to write @param sepItem the item separator string @param sepKeyval the key-value pair separator string @return the string representation for the given map
[ "Returns", "a", "string", "representation", "for", "the", "given", "map", "using", "the", "given", "separators", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsStringUtil.java#L1314-L1328
cfg4j/cfg4j
cfg4j-core/src/main/java/org/cfg4j/source/files/FilesConfigurationSource.java
FilesConfigurationSource.getConfiguration
@Override public Properties getConfiguration(Environment environment) { """ Get configuration set for a given {@code environment} from this source in a form of {@link Properties}. {@link Environment} name is prepended to all file paths from {@link ConfigFilesProvider} to form an absolute configuration file path. If environment name is empty paths are treated as relative to the user's home directory location. @param environment environment to use @return configuration set for {@code environment} @throws MissingEnvironmentException when requested environment couldn't be found @throws IllegalStateException when unable to fetch configuration """ Properties properties = new Properties(); Path rootPath; if (environment.getName().trim().isEmpty()) { rootPath = Paths.get(System.getProperty("user.home")); } else { rootPath = Paths.get(environment.getName()); } if (!rootPath.toFile().exists()) { throw new MissingEnvironmentException("Directory doesn't exist: " + rootPath); } List<Path> paths = new ArrayList<>(); for (Path path : configFilesProvider.getConfigFiles()) { paths.add(rootPath.resolve(path)); } for (Path path : paths) { try (InputStream input = new FileInputStream(path.toFile())) { PropertiesProvider provider = propertiesProviderSelector.getProvider(path.getFileName().toString()); properties.putAll(provider.getProperties(input)); } catch (IOException e) { throw new IllegalStateException("Unable to load properties from file: " + path, e); } } return properties; }
java
@Override public Properties getConfiguration(Environment environment) { Properties properties = new Properties(); Path rootPath; if (environment.getName().trim().isEmpty()) { rootPath = Paths.get(System.getProperty("user.home")); } else { rootPath = Paths.get(environment.getName()); } if (!rootPath.toFile().exists()) { throw new MissingEnvironmentException("Directory doesn't exist: " + rootPath); } List<Path> paths = new ArrayList<>(); for (Path path : configFilesProvider.getConfigFiles()) { paths.add(rootPath.resolve(path)); } for (Path path : paths) { try (InputStream input = new FileInputStream(path.toFile())) { PropertiesProvider provider = propertiesProviderSelector.getProvider(path.getFileName().toString()); properties.putAll(provider.getProperties(input)); } catch (IOException e) { throw new IllegalStateException("Unable to load properties from file: " + path, e); } } return properties; }
[ "@", "Override", "public", "Properties", "getConfiguration", "(", "Environment", "environment", ")", "{", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "Path", "rootPath", ";", "if", "(", "environment", ".", "getName", "(", ")", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "rootPath", "=", "Paths", ".", "get", "(", "System", ".", "getProperty", "(", "\"user.home\"", ")", ")", ";", "}", "else", "{", "rootPath", "=", "Paths", ".", "get", "(", "environment", ".", "getName", "(", ")", ")", ";", "}", "if", "(", "!", "rootPath", ".", "toFile", "(", ")", ".", "exists", "(", ")", ")", "{", "throw", "new", "MissingEnvironmentException", "(", "\"Directory doesn't exist: \"", "+", "rootPath", ")", ";", "}", "List", "<", "Path", ">", "paths", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Path", "path", ":", "configFilesProvider", ".", "getConfigFiles", "(", ")", ")", "{", "paths", ".", "add", "(", "rootPath", ".", "resolve", "(", "path", ")", ")", ";", "}", "for", "(", "Path", "path", ":", "paths", ")", "{", "try", "(", "InputStream", "input", "=", "new", "FileInputStream", "(", "path", ".", "toFile", "(", ")", ")", ")", "{", "PropertiesProvider", "provider", "=", "propertiesProviderSelector", ".", "getProvider", "(", "path", ".", "getFileName", "(", ")", ".", "toString", "(", ")", ")", ";", "properties", ".", "putAll", "(", "provider", ".", "getProperties", "(", "input", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Unable to load properties from file: \"", "+", "path", ",", "e", ")", ";", "}", "}", "return", "properties", ";", "}" ]
Get configuration set for a given {@code environment} from this source in a form of {@link Properties}. {@link Environment} name is prepended to all file paths from {@link ConfigFilesProvider} to form an absolute configuration file path. If environment name is empty paths are treated as relative to the user's home directory location. @param environment environment to use @return configuration set for {@code environment} @throws MissingEnvironmentException when requested environment couldn't be found @throws IllegalStateException when unable to fetch configuration
[ "Get", "configuration", "set", "for", "a", "given", "{", "@code", "environment", "}", "from", "this", "source", "in", "a", "form", "of", "{", "@link", "Properties", "}", ".", "{", "@link", "Environment", "}", "name", "is", "prepended", "to", "all", "file", "paths", "from", "{", "@link", "ConfigFilesProvider", "}", "to", "form", "an", "absolute", "configuration", "file", "path", ".", "If", "environment", "name", "is", "empty", "paths", "are", "treated", "as", "relative", "to", "the", "user", "s", "home", "directory", "location", "." ]
train
https://github.com/cfg4j/cfg4j/blob/47d4f63e5fc820c62631e557adc34a29d8ab396d/cfg4j-core/src/main/java/org/cfg4j/source/files/FilesConfigurationSource.java#L98-L130
UrielCh/ovh-java-sdk
ovh-java-sdk-overTheBox/src/main/java/net/minidev/ovh/api/ApiOvhOverTheBox.java
ApiOvhOverTheBox.serviceName_linkDevice_POST
public void serviceName_linkDevice_POST(String serviceName, String deviceId) throws IOException { """ Link a device to this service REST: POST /overTheBox/{serviceName}/linkDevice @param deviceId [required] The id of the device @param serviceName [required] The internal name of your overTheBox offer """ String qPath = "/overTheBox/{serviceName}/linkDevice"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "deviceId", deviceId); exec(qPath, "POST", sb.toString(), o); }
java
public void serviceName_linkDevice_POST(String serviceName, String deviceId) throws IOException { String qPath = "/overTheBox/{serviceName}/linkDevice"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "deviceId", deviceId); exec(qPath, "POST", sb.toString(), o); }
[ "public", "void", "serviceName_linkDevice_POST", "(", "String", "serviceName", ",", "String", "deviceId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/overTheBox/{serviceName}/linkDevice\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"deviceId\"", ",", "deviceId", ")", ";", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "}" ]
Link a device to this service REST: POST /overTheBox/{serviceName}/linkDevice @param deviceId [required] The id of the device @param serviceName [required] The internal name of your overTheBox offer
[ "Link", "a", "device", "to", "this", "service" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-overTheBox/src/main/java/net/minidev/ovh/api/ApiOvhOverTheBox.java#L321-L327
couchbase/couchbase-lite-java
src/main/java/okhttp3/internal/tls/CustomHostnameVerifier.java
CustomHostnameVerifier.verifyIpAddress
private boolean verifyIpAddress(String ipAddress, X509Certificate certificate) { """ Returns true if {@code certificate} matches {@code ipAddress}. """ List<String> altNames = getSubjectAltNames(certificate, ALT_IPA_NAME); for (int i = 0, size = altNames.size(); i < size; i++) { if (ipAddress.equalsIgnoreCase(altNames.get(i))) { return true; } } X500Principal principal = certificate.getSubjectX500Principal(); // RFC 2818 advises using the most specific name for matching. String cn = new DistinguishedNameParser(principal).findMostSpecific("cn"); // NOTE: In case of empty Common Name (CN), not checking return (cn == null) || ipAddress.equalsIgnoreCase(cn); }
java
private boolean verifyIpAddress(String ipAddress, X509Certificate certificate) { List<String> altNames = getSubjectAltNames(certificate, ALT_IPA_NAME); for (int i = 0, size = altNames.size(); i < size; i++) { if (ipAddress.equalsIgnoreCase(altNames.get(i))) { return true; } } X500Principal principal = certificate.getSubjectX500Principal(); // RFC 2818 advises using the most specific name for matching. String cn = new DistinguishedNameParser(principal).findMostSpecific("cn"); // NOTE: In case of empty Common Name (CN), not checking return (cn == null) || ipAddress.equalsIgnoreCase(cn); }
[ "private", "boolean", "verifyIpAddress", "(", "String", "ipAddress", ",", "X509Certificate", "certificate", ")", "{", "List", "<", "String", ">", "altNames", "=", "getSubjectAltNames", "(", "certificate", ",", "ALT_IPA_NAME", ")", ";", "for", "(", "int", "i", "=", "0", ",", "size", "=", "altNames", ".", "size", "(", ")", ";", "i", "<", "size", ";", "i", "++", ")", "{", "if", "(", "ipAddress", ".", "equalsIgnoreCase", "(", "altNames", ".", "get", "(", "i", ")", ")", ")", "{", "return", "true", ";", "}", "}", "X500Principal", "principal", "=", "certificate", ".", "getSubjectX500Principal", "(", ")", ";", "// RFC 2818 advises using the most specific name for matching.", "String", "cn", "=", "new", "DistinguishedNameParser", "(", "principal", ")", ".", "findMostSpecific", "(", "\"cn\"", ")", ";", "// NOTE: In case of empty Common Name (CN), not checking", "return", "(", "cn", "==", "null", ")", "||", "ipAddress", ".", "equalsIgnoreCase", "(", "cn", ")", ";", "}" ]
Returns true if {@code certificate} matches {@code ipAddress}.
[ "Returns", "true", "if", "{" ]
train
https://github.com/couchbase/couchbase-lite-java/blob/cb72c44186456e6191a9ad0a7feb310011d0b081/src/main/java/okhttp3/internal/tls/CustomHostnameVerifier.java#L76-L90
rollbar/rollbar-java
rollbar-android/src/main/java/com/rollbar/android/Rollbar.java
Rollbar.log
public void log(Throwable error, String description, Level level) { """ Record a debug error with human readable description at the specified level. @param error the error. @param description human readable description of error. @param level the level. """ log(error, null, description, level); }
java
public void log(Throwable error, String description, Level level) { log(error, null, description, level); }
[ "public", "void", "log", "(", "Throwable", "error", ",", "String", "description", ",", "Level", "level", ")", "{", "log", "(", "error", ",", "null", ",", "description", ",", "level", ")", ";", "}" ]
Record a debug error with human readable description at the specified level. @param error the error. @param description human readable description of error. @param level the level.
[ "Record", "a", "debug", "error", "with", "human", "readable", "description", "at", "the", "specified", "level", "." ]
train
https://github.com/rollbar/rollbar-java/blob/5eb4537d1363722b51cfcce55b427cbd8489f17b/rollbar-android/src/main/java/com/rollbar/android/Rollbar.java#L722-L724
Whiley/WhileyCompiler
src/main/java/wyc/io/WhileyFileParser.java
WhileyFileParser.tryAndMatchAtIndent
private Token tryAndMatchAtIndent(boolean terminated, Indent indent, Token.Kind... kinds) { """ Attempt to match a given token(s) at a given level of indent, whilst ignoring any whitespace in between. Note that, in the case it fails to match, then the index will be unchanged. This latter point is important, otherwise we could accidentally gobble up some important indentation. If more than one kind is provided then this will try to match any of them. @param terminated Indicates whether or not this function should be concerned with new lines. The terminated flag indicates whether or not the current construct being parsed is known to be terminated. If so, then we don't need to worry about newlines and can greedily consume them (i.e. since we'll eventually run into the terminating symbol). @param indent The indentation level to try and match the tokens at. @param kinds @return """ int start = index; Indent r = getIndent(); if (r != null && r.equivalent(indent)) { Token t = tryAndMatch(terminated, kinds); if (t != null) { return r; } } // backtrack in all failing cases. index = start; return null; }
java
private Token tryAndMatchAtIndent(boolean terminated, Indent indent, Token.Kind... kinds) { int start = index; Indent r = getIndent(); if (r != null && r.equivalent(indent)) { Token t = tryAndMatch(terminated, kinds); if (t != null) { return r; } } // backtrack in all failing cases. index = start; return null; }
[ "private", "Token", "tryAndMatchAtIndent", "(", "boolean", "terminated", ",", "Indent", "indent", ",", "Token", ".", "Kind", "...", "kinds", ")", "{", "int", "start", "=", "index", ";", "Indent", "r", "=", "getIndent", "(", ")", ";", "if", "(", "r", "!=", "null", "&&", "r", ".", "equivalent", "(", "indent", ")", ")", "{", "Token", "t", "=", "tryAndMatch", "(", "terminated", ",", "kinds", ")", ";", "if", "(", "t", "!=", "null", ")", "{", "return", "r", ";", "}", "}", "// backtrack in all failing cases.", "index", "=", "start", ";", "return", "null", ";", "}" ]
Attempt to match a given token(s) at a given level of indent, whilst ignoring any whitespace in between. Note that, in the case it fails to match, then the index will be unchanged. This latter point is important, otherwise we could accidentally gobble up some important indentation. If more than one kind is provided then this will try to match any of them. @param terminated Indicates whether or not this function should be concerned with new lines. The terminated flag indicates whether or not the current construct being parsed is known to be terminated. If so, then we don't need to worry about newlines and can greedily consume them (i.e. since we'll eventually run into the terminating symbol). @param indent The indentation level to try and match the tokens at. @param kinds @return
[ "Attempt", "to", "match", "a", "given", "token", "(", "s", ")", "at", "a", "given", "level", "of", "indent", "whilst", "ignoring", "any", "whitespace", "in", "between", ".", "Note", "that", "in", "the", "case", "it", "fails", "to", "match", "then", "the", "index", "will", "be", "unchanged", ".", "This", "latter", "point", "is", "important", "otherwise", "we", "could", "accidentally", "gobble", "up", "some", "important", "indentation", ".", "If", "more", "than", "one", "kind", "is", "provided", "then", "this", "will", "try", "to", "match", "any", "of", "them", "." ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyc/io/WhileyFileParser.java#L4229-L4241
infinispan/infinispan
core/src/main/java/org/infinispan/transaction/impl/TransactionTable.java
TransactionTable.markTransactionCompleted
public void markTransactionCompleted(GlobalTransaction gtx, boolean successful) { """ With the current state transfer implementation it is possible for a transaction to be prepared several times on a remote node. This might cause leaks, e.g. if the transaction is prepared, committed and prepared again. Once marked as completed (because of commit or rollback) any further prepare received on that transaction are discarded. """ if (completedTransactionsInfo != null) { completedTransactionsInfo.markTransactionCompleted(gtx, successful); } }
java
public void markTransactionCompleted(GlobalTransaction gtx, boolean successful) { if (completedTransactionsInfo != null) { completedTransactionsInfo.markTransactionCompleted(gtx, successful); } }
[ "public", "void", "markTransactionCompleted", "(", "GlobalTransaction", "gtx", ",", "boolean", "successful", ")", "{", "if", "(", "completedTransactionsInfo", "!=", "null", ")", "{", "completedTransactionsInfo", ".", "markTransactionCompleted", "(", "gtx", ",", "successful", ")", ";", "}", "}" ]
With the current state transfer implementation it is possible for a transaction to be prepared several times on a remote node. This might cause leaks, e.g. if the transaction is prepared, committed and prepared again. Once marked as completed (because of commit or rollback) any further prepare received on that transaction are discarded.
[ "With", "the", "current", "state", "transfer", "implementation", "it", "is", "possible", "for", "a", "transaction", "to", "be", "prepared", "several", "times", "on", "a", "remote", "node", ".", "This", "might", "cause", "leaks", "e", ".", "g", ".", "if", "the", "transaction", "is", "prepared", "committed", "and", "prepared", "again", ".", "Once", "marked", "as", "completed", "(", "because", "of", "commit", "or", "rollback", ")", "any", "further", "prepare", "received", "on", "that", "transaction", "are", "discarded", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/transaction/impl/TransactionTable.java#L692-L696
craftercms/profile
security-provider/src/main/java/org/craftercms/security/utils/social/ConnectionUtils.java
ConnectionUtils.addProviderProfileInfo
public static void addProviderProfileInfo(Profile profile, UserProfile providerProfile) { """ Adds the info from the provider profile to the specified profile. @param profile the target profile @param providerProfile the provider profile where to get the info """ String email = providerProfile.getEmail(); if (StringUtils.isEmpty(email)) { throw new IllegalStateException("No email included in provider profile"); } String username = providerProfile.getUsername(); if (StringUtils.isEmpty(username)) { username = email; } String firstName = providerProfile.getFirstName(); String lastName = providerProfile.getLastName(); profile.setUsername(username); profile.setEmail(email); profile.setAttribute(FIRST_NAME_ATTRIBUTE_NAME, firstName); profile.setAttribute(LAST_NAME_ATTRIBUTE_NAME, lastName); }
java
public static void addProviderProfileInfo(Profile profile, UserProfile providerProfile) { String email = providerProfile.getEmail(); if (StringUtils.isEmpty(email)) { throw new IllegalStateException("No email included in provider profile"); } String username = providerProfile.getUsername(); if (StringUtils.isEmpty(username)) { username = email; } String firstName = providerProfile.getFirstName(); String lastName = providerProfile.getLastName(); profile.setUsername(username); profile.setEmail(email); profile.setAttribute(FIRST_NAME_ATTRIBUTE_NAME, firstName); profile.setAttribute(LAST_NAME_ATTRIBUTE_NAME, lastName); }
[ "public", "static", "void", "addProviderProfileInfo", "(", "Profile", "profile", ",", "UserProfile", "providerProfile", ")", "{", "String", "email", "=", "providerProfile", ".", "getEmail", "(", ")", ";", "if", "(", "StringUtils", ".", "isEmpty", "(", "email", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"No email included in provider profile\"", ")", ";", "}", "String", "username", "=", "providerProfile", ".", "getUsername", "(", ")", ";", "if", "(", "StringUtils", ".", "isEmpty", "(", "username", ")", ")", "{", "username", "=", "email", ";", "}", "String", "firstName", "=", "providerProfile", ".", "getFirstName", "(", ")", ";", "String", "lastName", "=", "providerProfile", ".", "getLastName", "(", ")", ";", "profile", ".", "setUsername", "(", "username", ")", ";", "profile", ".", "setEmail", "(", "email", ")", ";", "profile", ".", "setAttribute", "(", "FIRST_NAME_ATTRIBUTE_NAME", ",", "firstName", ")", ";", "profile", ".", "setAttribute", "(", "LAST_NAME_ATTRIBUTE_NAME", ",", "lastName", ")", ";", "}" ]
Adds the info from the provider profile to the specified profile. @param profile the target profile @param providerProfile the provider profile where to get the info
[ "Adds", "the", "info", "from", "the", "provider", "profile", "to", "the", "specified", "profile", "." ]
train
https://github.com/craftercms/profile/blob/d829c1136b0fd21d87dc925cb7046cbd38a300a4/security-provider/src/main/java/org/craftercms/security/utils/social/ConnectionUtils.java#L217-L235
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/util/FileUtils.java
FileUtils.doCopyFile
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { """ Internal copy file method. @param srcFile the validated source file, must not be <code>null</code> @param destFile the validated destination file, must not be <code>null</code> @param preserveFileDate whether to preserve the file date @throws IOException if an error occurs """ if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); FileOutputStream output = new FileOutputStream(destFile); IOUtils.copy(input, output, true); if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
java
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); FileOutputStream output = new FileOutputStream(destFile); IOUtils.copy(input, output, true); if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
[ "private", "static", "void", "doCopyFile", "(", "File", "srcFile", ",", "File", "destFile", ",", "boolean", "preserveFileDate", ")", "throws", "IOException", "{", "if", "(", "destFile", ".", "exists", "(", ")", "&&", "destFile", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"Destination '\"", "+", "destFile", "+", "\"' exists but is a directory\"", ")", ";", "}", "FileInputStream", "input", "=", "new", "FileInputStream", "(", "srcFile", ")", ";", "FileOutputStream", "output", "=", "new", "FileOutputStream", "(", "destFile", ")", ";", "IOUtils", ".", "copy", "(", "input", ",", "output", ",", "true", ")", ";", "if", "(", "srcFile", ".", "length", "(", ")", "!=", "destFile", ".", "length", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"Failed to copy full contents from '\"", "+", "srcFile", "+", "\"' to '\"", "+", "destFile", "+", "\"'\"", ")", ";", "}", "if", "(", "preserveFileDate", ")", "{", "destFile", ".", "setLastModified", "(", "srcFile", ".", "lastModified", "(", ")", ")", ";", "}", "}" ]
Internal copy file method. @param srcFile the validated source file, must not be <code>null</code> @param destFile the validated destination file, must not be <code>null</code> @param preserveFileDate whether to preserve the file date @throws IOException if an error occurs
[ "Internal", "copy", "file", "method", "." ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/util/FileUtils.java#L228-L243
VoltDB/voltdb
third_party/java/src/org/apache/commons_voltpatches/cli/HelpFormatter.java
HelpFormatter.printWrapped
public void printWrapped(PrintWriter pw, int width, int nextLineTabStop, String text) { """ Print the specified text to the specified PrintWriter. @param pw The printWriter to write the help to @param width The number of characters to display per line @param nextLineTabStop The position on the next line for the first tab. @param text The text to be written to the PrintWriter """ StringBuffer sb = new StringBuffer(text.length()); renderWrappedTextBlock(sb, width, nextLineTabStop, text); pw.println(sb.toString()); }
java
public void printWrapped(PrintWriter pw, int width, int nextLineTabStop, String text) { StringBuffer sb = new StringBuffer(text.length()); renderWrappedTextBlock(sb, width, nextLineTabStop, text); pw.println(sb.toString()); }
[ "public", "void", "printWrapped", "(", "PrintWriter", "pw", ",", "int", "width", ",", "int", "nextLineTabStop", ",", "String", "text", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", "text", ".", "length", "(", ")", ")", ";", "renderWrappedTextBlock", "(", "sb", ",", "width", ",", "nextLineTabStop", ",", "text", ")", ";", "pw", ".", "println", "(", "sb", ".", "toString", "(", ")", ")", ";", "}" ]
Print the specified text to the specified PrintWriter. @param pw The printWriter to write the help to @param width The number of characters to display per line @param nextLineTabStop The position on the next line for the first tab. @param text The text to be written to the PrintWriter
[ "Print", "the", "specified", "text", "to", "the", "specified", "PrintWriter", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/commons_voltpatches/cli/HelpFormatter.java#L767-L773
io7m/jaffirm
com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Preconditions.java
Preconditions.checkPreconditionL
public static long checkPreconditionL( final long value, final LongPredicate predicate, final LongFunction<String> describer) { """ A {@code long} specialized version of {@link #checkPrecondition(Object, Predicate, Function)} @param value The value @param predicate The predicate @param describer The describer of the predicate @return value @throws PreconditionViolationException If the predicate is false """ final boolean ok; try { ok = predicate.test(value); } catch (final Throwable e) { final Violations violations = singleViolation(failedPredicate(e)); throw new PreconditionViolationException( failedMessage(Long.valueOf(value), violations), e, violations.count()); } return innerCheckL(value, ok, describer); }
java
public static long checkPreconditionL( final long value, final LongPredicate predicate, final LongFunction<String> describer) { final boolean ok; try { ok = predicate.test(value); } catch (final Throwable e) { final Violations violations = singleViolation(failedPredicate(e)); throw new PreconditionViolationException( failedMessage(Long.valueOf(value), violations), e, violations.count()); } return innerCheckL(value, ok, describer); }
[ "public", "static", "long", "checkPreconditionL", "(", "final", "long", "value", ",", "final", "LongPredicate", "predicate", ",", "final", "LongFunction", "<", "String", ">", "describer", ")", "{", "final", "boolean", "ok", ";", "try", "{", "ok", "=", "predicate", ".", "test", "(", "value", ")", ";", "}", "catch", "(", "final", "Throwable", "e", ")", "{", "final", "Violations", "violations", "=", "singleViolation", "(", "failedPredicate", "(", "e", ")", ")", ";", "throw", "new", "PreconditionViolationException", "(", "failedMessage", "(", "Long", ".", "valueOf", "(", "value", ")", ",", "violations", ")", ",", "e", ",", "violations", ".", "count", "(", ")", ")", ";", "}", "return", "innerCheckL", "(", "value", ",", "ok", ",", "describer", ")", ";", "}" ]
A {@code long} specialized version of {@link #checkPrecondition(Object, Predicate, Function)} @param value The value @param predicate The predicate @param describer The describer of the predicate @return value @throws PreconditionViolationException If the predicate is false
[ "A", "{", "@code", "long", "}", "specialized", "version", "of", "{", "@link", "#checkPrecondition", "(", "Object", "Predicate", "Function", ")", "}" ]
train
https://github.com/io7m/jaffirm/blob/c97d246242d381e48832838737418cfe4cb57b4d/com.io7m.jaffirm.core/src/main/java/com/io7m/jaffirm/core/Preconditions.java#L449-L464
mgormley/pacaya
src/main/java/edu/jhu/pacaya/gm/data/bayesnet/BayesNetReader.java
BayesNetReader.readBnAsFg
public FactorGraph readBnAsFg(InputStream networkIs, InputStream cpdIs) throws IOException { """ Reads a Bayesian Network from a network InputStream and a CPD InputStream, and returns a factor graph representation of it. """ // Read network file. BufferedReader networkReader = new BufferedReader(new InputStreamReader(networkIs)); // -- read the number of variables. int numVars = Integer.parseInt(networkReader.readLine().trim()); varMap = new HashMap<String,Var>(); VarSet allVars = new VarSet(); for (int i = 0; i < numVars; i++) { Var var = parseVar(networkReader.readLine()); allVars.add(var); varMap.put(var.getName(), var); } assert (allVars.size() == numVars); // -- read the dependencies between variables. // ....or not... networkReader.close(); // Read CPD file. BufferedReader cpdReader = new BufferedReader(new InputStreamReader(cpdIs)); factorMap = new LinkedHashMap<VarSet, ExplicitFactor>(); String line; while ((line = cpdReader.readLine()) != null) { // Parse out the variable configuration. VarConfig config = new VarConfig(); String[] assns = whitespaceOrComma.split(line); for (int i=0; i<assns.length-1; i++) { String assn = assns[i]; String[] va = equals.split(assn); assert(va.length == 2); String varName = va[0]; String stateName = va[1]; config.put(varMap.get(varName), stateName); } // The double is the last value on the line. double value = Double.parseDouble(assns[assns.length-1]); // Factor graphs store the log value. value = FastMath.log(value); // Get the factor for this configuration, creating a new one if necessary. VarSet vars = config.getVars(); ExplicitFactor f = factorMap.get(vars); if (f == null) { f = new ExplicitFactor(vars); } // Set the value in the factor. f.setValue(config.getConfigIndex(), value); factorMap.put(vars, f); } cpdReader.close(); // Create the factor graph. FactorGraph fg = new FactorGraph(); for (ExplicitFactor f : factorMap.values()) { fg.addFactor(f); } return fg; }
java
public FactorGraph readBnAsFg(InputStream networkIs, InputStream cpdIs) throws IOException { // Read network file. BufferedReader networkReader = new BufferedReader(new InputStreamReader(networkIs)); // -- read the number of variables. int numVars = Integer.parseInt(networkReader.readLine().trim()); varMap = new HashMap<String,Var>(); VarSet allVars = new VarSet(); for (int i = 0; i < numVars; i++) { Var var = parseVar(networkReader.readLine()); allVars.add(var); varMap.put(var.getName(), var); } assert (allVars.size() == numVars); // -- read the dependencies between variables. // ....or not... networkReader.close(); // Read CPD file. BufferedReader cpdReader = new BufferedReader(new InputStreamReader(cpdIs)); factorMap = new LinkedHashMap<VarSet, ExplicitFactor>(); String line; while ((line = cpdReader.readLine()) != null) { // Parse out the variable configuration. VarConfig config = new VarConfig(); String[] assns = whitespaceOrComma.split(line); for (int i=0; i<assns.length-1; i++) { String assn = assns[i]; String[] va = equals.split(assn); assert(va.length == 2); String varName = va[0]; String stateName = va[1]; config.put(varMap.get(varName), stateName); } // The double is the last value on the line. double value = Double.parseDouble(assns[assns.length-1]); // Factor graphs store the log value. value = FastMath.log(value); // Get the factor for this configuration, creating a new one if necessary. VarSet vars = config.getVars(); ExplicitFactor f = factorMap.get(vars); if (f == null) { f = new ExplicitFactor(vars); } // Set the value in the factor. f.setValue(config.getConfigIndex(), value); factorMap.put(vars, f); } cpdReader.close(); // Create the factor graph. FactorGraph fg = new FactorGraph(); for (ExplicitFactor f : factorMap.values()) { fg.addFactor(f); } return fg; }
[ "public", "FactorGraph", "readBnAsFg", "(", "InputStream", "networkIs", ",", "InputStream", "cpdIs", ")", "throws", "IOException", "{", "// Read network file.", "BufferedReader", "networkReader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "networkIs", ")", ")", ";", "// -- read the number of variables.", "int", "numVars", "=", "Integer", ".", "parseInt", "(", "networkReader", ".", "readLine", "(", ")", ".", "trim", "(", ")", ")", ";", "varMap", "=", "new", "HashMap", "<", "String", ",", "Var", ">", "(", ")", ";", "VarSet", "allVars", "=", "new", "VarSet", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numVars", ";", "i", "++", ")", "{", "Var", "var", "=", "parseVar", "(", "networkReader", ".", "readLine", "(", ")", ")", ";", "allVars", ".", "add", "(", "var", ")", ";", "varMap", ".", "put", "(", "var", ".", "getName", "(", ")", ",", "var", ")", ";", "}", "assert", "(", "allVars", ".", "size", "(", ")", "==", "numVars", ")", ";", "// -- read the dependencies between variables.", "// ....or not...", "networkReader", ".", "close", "(", ")", ";", "// Read CPD file.", "BufferedReader", "cpdReader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "cpdIs", ")", ")", ";", "factorMap", "=", "new", "LinkedHashMap", "<", "VarSet", ",", "ExplicitFactor", ">", "(", ")", ";", "String", "line", ";", "while", "(", "(", "line", "=", "cpdReader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "// Parse out the variable configuration. ", "VarConfig", "config", "=", "new", "VarConfig", "(", ")", ";", "String", "[", "]", "assns", "=", "whitespaceOrComma", ".", "split", "(", "line", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "assns", ".", "length", "-", "1", ";", "i", "++", ")", "{", "String", "assn", "=", "assns", "[", "i", "]", ";", "String", "[", "]", "va", "=", "equals", ".", "split", "(", "assn", ")", ";", "assert", "(", "va", ".", "length", "==", "2", ")", ";", "String", "varName", "=", "va", "[", "0", "]", ";", "String", "stateName", "=", "va", "[", "1", "]", ";", "config", ".", "put", "(", "varMap", ".", "get", "(", "varName", ")", ",", "stateName", ")", ";", "}", "// The double is the last value on the line.", "double", "value", "=", "Double", ".", "parseDouble", "(", "assns", "[", "assns", ".", "length", "-", "1", "]", ")", ";", "// Factor graphs store the log value.", "value", "=", "FastMath", ".", "log", "(", "value", ")", ";", "// Get the factor for this configuration, creating a new one if necessary.", "VarSet", "vars", "=", "config", ".", "getVars", "(", ")", ";", "ExplicitFactor", "f", "=", "factorMap", ".", "get", "(", "vars", ")", ";", "if", "(", "f", "==", "null", ")", "{", "f", "=", "new", "ExplicitFactor", "(", "vars", ")", ";", "}", "// Set the value in the factor.", "f", ".", "setValue", "(", "config", ".", "getConfigIndex", "(", ")", ",", "value", ")", ";", "factorMap", ".", "put", "(", "vars", ",", "f", ")", ";", "}", "cpdReader", ".", "close", "(", ")", ";", "// Create the factor graph.", "FactorGraph", "fg", "=", "new", "FactorGraph", "(", ")", ";", "for", "(", "ExplicitFactor", "f", ":", "factorMap", ".", "values", "(", ")", ")", "{", "fg", ".", "addFactor", "(", "f", ")", ";", "}", "return", "fg", ";", "}" ]
Reads a Bayesian Network from a network InputStream and a CPD InputStream, and returns a factor graph representation of it.
[ "Reads", "a", "Bayesian", "Network", "from", "a", "network", "InputStream", "and", "a", "CPD", "InputStream", "and", "returns", "a", "factor", "graph", "representation", "of", "it", "." ]
train
https://github.com/mgormley/pacaya/blob/786294cbac7cc65dbc32210c10acc32ed0c69233/src/main/java/edu/jhu/pacaya/gm/data/bayesnet/BayesNetReader.java#L50-L110
nguillaumin/slick2d-maven
slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/FontFileReader.java
FontFileReader.readTTFString
public final String readTTFString(int len) throws IOException { """ Read an ISO-8859-1 string of len bytes. @param len The length of the string to read @return A String @throws IOException If EOF is reached """ if ((len + current) > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } byte[] tmp = new byte[len]; System.arraycopy(file, current, tmp, 0, len); current += len; final String encoding; if ((tmp.length > 0) && (tmp[0] == 0)) { encoding = "UTF-16BE"; } else { encoding = "ISO-8859-1"; } return new String(tmp, encoding); }
java
public final String readTTFString(int len) throws IOException { if ((len + current) > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } byte[] tmp = new byte[len]; System.arraycopy(file, current, tmp, 0, len); current += len; final String encoding; if ((tmp.length > 0) && (tmp[0] == 0)) { encoding = "UTF-16BE"; } else { encoding = "ISO-8859-1"; } return new String(tmp, encoding); }
[ "public", "final", "String", "readTTFString", "(", "int", "len", ")", "throws", "IOException", "{", "if", "(", "(", "len", "+", "current", ")", ">", "fsize", ")", "{", "throw", "new", "java", ".", "io", ".", "EOFException", "(", "\"Reached EOF, file size=\"", "+", "fsize", ")", ";", "}", "byte", "[", "]", "tmp", "=", "new", "byte", "[", "len", "]", ";", "System", ".", "arraycopy", "(", "file", ",", "current", ",", "tmp", ",", "0", ",", "len", ")", ";", "current", "+=", "len", ";", "final", "String", "encoding", ";", "if", "(", "(", "tmp", ".", "length", ">", "0", ")", "&&", "(", "tmp", "[", "0", "]", "==", "0", ")", ")", "{", "encoding", "=", "\"UTF-16BE\"", ";", "}", "else", "{", "encoding", "=", "\"ISO-8859-1\"", ";", "}", "return", "new", "String", "(", "tmp", ",", "encoding", ")", ";", "}" ]
Read an ISO-8859-1 string of len bytes. @param len The length of the string to read @return A String @throws IOException If EOF is reached
[ "Read", "an", "ISO", "-", "8859", "-", "1", "string", "of", "len", "bytes", "." ]
train
https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/FontFileReader.java#L324-L339
openbase/jul
extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/MultiLanguageTextProcessor.java
MultiLanguageTextProcessor.buildMultiLanguageText
public static MultiLanguageText buildMultiLanguageText(final Locale locale, final String multiLanguageText) { """ Create a new multiLanguageTextBuilder and register multiLanguageText with given locale. @param locale the locale from which the language code is extracted for which the multiLanguageText is added @param multiLanguageText the multiLanguageText to be added @return the updated multiLanguageText builder """ return addMultiLanguageText(MultiLanguageText.newBuilder(), locale.getLanguage(), multiLanguageText).build(); }
java
public static MultiLanguageText buildMultiLanguageText(final Locale locale, final String multiLanguageText) { return addMultiLanguageText(MultiLanguageText.newBuilder(), locale.getLanguage(), multiLanguageText).build(); }
[ "public", "static", "MultiLanguageText", "buildMultiLanguageText", "(", "final", "Locale", "locale", ",", "final", "String", "multiLanguageText", ")", "{", "return", "addMultiLanguageText", "(", "MultiLanguageText", ".", "newBuilder", "(", ")", ",", "locale", ".", "getLanguage", "(", ")", ",", "multiLanguageText", ")", ".", "build", "(", ")", ";", "}" ]
Create a new multiLanguageTextBuilder and register multiLanguageText with given locale. @param locale the locale from which the language code is extracted for which the multiLanguageText is added @param multiLanguageText the multiLanguageText to be added @return the updated multiLanguageText builder
[ "Create", "a", "new", "multiLanguageTextBuilder", "and", "register", "multiLanguageText", "with", "given", "locale", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/MultiLanguageTextProcessor.java#L105-L107
Azure/azure-sdk-for-java
containerregistry/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2018_02_01_preview/implementation/BuildTasksInner.java
BuildTasksInner.beginUpdate
public BuildTaskInner beginUpdate(String resourceGroupName, String registryName, String buildTaskName, BuildTaskUpdateParameters buildTaskUpdateParameters) { """ Updates a build task with the specified parameters. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param buildTaskName The name of the container registry build task. @param buildTaskUpdateParameters The parameters for updating a build task. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the BuildTaskInner object if successful. """ return beginUpdateWithServiceResponseAsync(resourceGroupName, registryName, buildTaskName, buildTaskUpdateParameters).toBlocking().single().body(); }
java
public BuildTaskInner beginUpdate(String resourceGroupName, String registryName, String buildTaskName, BuildTaskUpdateParameters buildTaskUpdateParameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, registryName, buildTaskName, buildTaskUpdateParameters).toBlocking().single().body(); }
[ "public", "BuildTaskInner", "beginUpdate", "(", "String", "resourceGroupName", ",", "String", "registryName", ",", "String", "buildTaskName", ",", "BuildTaskUpdateParameters", "buildTaskUpdateParameters", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "registryName", ",", "buildTaskName", ",", "buildTaskUpdateParameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Updates a build task with the specified parameters. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param buildTaskName The name of the container registry build task. @param buildTaskUpdateParameters The parameters for updating a build task. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the BuildTaskInner object if successful.
[ "Updates", "a", "build", "task", "with", "the", "specified", "parameters", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_02_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2018_02_01_preview/implementation/BuildTasksInner.java#L888-L890
hexagonframework/spring-data-ebean
src/main/java/org/springframework/data/ebean/repository/query/ParameterBinder.java
ParameterBinder.bindAndPrepare
public EbeanQueryWrapper bindAndPrepare(EbeanQueryWrapper query) { """ Binds the parameters to the given query and applies special parameter types (e.g. pagination). @param query must not be {@literal null}. @return """ Assert.notNull(query, "query must not be null!"); return bindAndPrepare(query, parameters); }
java
public EbeanQueryWrapper bindAndPrepare(EbeanQueryWrapper query) { Assert.notNull(query, "query must not be null!"); return bindAndPrepare(query, parameters); }
[ "public", "EbeanQueryWrapper", "bindAndPrepare", "(", "EbeanQueryWrapper", "query", ")", "{", "Assert", ".", "notNull", "(", "query", ",", "\"query must not be null!\"", ")", ";", "return", "bindAndPrepare", "(", "query", ",", "parameters", ")", ";", "}" ]
Binds the parameters to the given query and applies special parameter types (e.g. pagination). @param query must not be {@literal null}. @return
[ "Binds", "the", "parameters", "to", "the", "given", "query", "and", "applies", "special", "parameter", "types", "(", "e", ".", "g", ".", "pagination", ")", "." ]
train
https://github.com/hexagonframework/spring-data-ebean/blob/dd11b97654982403b50dd1d5369cadad71fce410/src/main/java/org/springframework/data/ebean/repository/query/ParameterBinder.java#L75-L78
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.unsubscribeResourceFor
public void unsubscribeResourceFor(CmsDbContext dbc, String poolName, CmsPrincipal principal, CmsResource resource) throws CmsException { """ Unsubscribes the principal from the resource.<p> @param dbc the database context @param poolName the name of the database pool to use @param principal the principal that unsubscribes from the resource @param resource the resource to unsubscribe from @throws CmsException if something goes wrong """ getSubscriptionDriver().unsubscribeResourceFor(dbc, poolName, principal, resource); }
java
public void unsubscribeResourceFor(CmsDbContext dbc, String poolName, CmsPrincipal principal, CmsResource resource) throws CmsException { getSubscriptionDriver().unsubscribeResourceFor(dbc, poolName, principal, resource); }
[ "public", "void", "unsubscribeResourceFor", "(", "CmsDbContext", "dbc", ",", "String", "poolName", ",", "CmsPrincipal", "principal", ",", "CmsResource", "resource", ")", "throws", "CmsException", "{", "getSubscriptionDriver", "(", ")", ".", "unsubscribeResourceFor", "(", "dbc", ",", "poolName", ",", "principal", ",", "resource", ")", ";", "}" ]
Unsubscribes the principal from the resource.<p> @param dbc the database context @param poolName the name of the database pool to use @param principal the principal that unsubscribes from the resource @param resource the resource to unsubscribe from @throws CmsException if something goes wrong
[ "Unsubscribes", "the", "principal", "from", "the", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L9279-L9283
libgdx/packr
src/main/java/com/badlogicgames/packr/PackrFileUtils.java
PackrFileUtils.copyDirectory
static void copyDirectory(File sourceDirectory, File targetDirectory) throws IOException { """ Copies directories, preserving file attributes. <p> The {@link org.zeroturnaround.zip.commons.FileUtilsV2_2#copyDirectory(File, File)} function does not preserve file attributes. """ final Path sourcePath = Paths.get(sourceDirectory.toURI()).toRealPath(); final Path targetPath = Paths.get(targetDirectory.toURI()); Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path relative = sourcePath.relativize(dir); Path target = targetPath.resolve(relative); File folder = target.toFile(); if (!folder.exists()) { mkdirs(folder); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path relative = sourcePath.relativize(file); Path target = targetPath.resolve(relative); Files.copy(file, target, StandardCopyOption.COPY_ATTRIBUTES); return FileVisitResult.CONTINUE; } }); }
java
static void copyDirectory(File sourceDirectory, File targetDirectory) throws IOException { final Path sourcePath = Paths.get(sourceDirectory.toURI()).toRealPath(); final Path targetPath = Paths.get(targetDirectory.toURI()); Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path relative = sourcePath.relativize(dir); Path target = targetPath.resolve(relative); File folder = target.toFile(); if (!folder.exists()) { mkdirs(folder); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path relative = sourcePath.relativize(file); Path target = targetPath.resolve(relative); Files.copy(file, target, StandardCopyOption.COPY_ATTRIBUTES); return FileVisitResult.CONTINUE; } }); }
[ "static", "void", "copyDirectory", "(", "File", "sourceDirectory", ",", "File", "targetDirectory", ")", "throws", "IOException", "{", "final", "Path", "sourcePath", "=", "Paths", ".", "get", "(", "sourceDirectory", ".", "toURI", "(", ")", ")", ".", "toRealPath", "(", ")", ";", "final", "Path", "targetPath", "=", "Paths", ".", "get", "(", "targetDirectory", ".", "toURI", "(", ")", ")", ";", "Files", ".", "walkFileTree", "(", "sourcePath", ",", "new", "SimpleFileVisitor", "<", "Path", ">", "(", ")", "{", "@", "Override", "public", "FileVisitResult", "preVisitDirectory", "(", "Path", "dir", ",", "BasicFileAttributes", "attrs", ")", "throws", "IOException", "{", "Path", "relative", "=", "sourcePath", ".", "relativize", "(", "dir", ")", ";", "Path", "target", "=", "targetPath", ".", "resolve", "(", "relative", ")", ";", "File", "folder", "=", "target", ".", "toFile", "(", ")", ";", "if", "(", "!", "folder", ".", "exists", "(", ")", ")", "{", "mkdirs", "(", "folder", ")", ";", "}", "return", "FileVisitResult", ".", "CONTINUE", ";", "}", "@", "Override", "public", "FileVisitResult", "visitFile", "(", "Path", "file", ",", "BasicFileAttributes", "attrs", ")", "throws", "IOException", "{", "Path", "relative", "=", "sourcePath", ".", "relativize", "(", "file", ")", ";", "Path", "target", "=", "targetPath", ".", "resolve", "(", "relative", ")", ";", "Files", ".", "copy", "(", "file", ",", "target", ",", "StandardCopyOption", ".", "COPY_ATTRIBUTES", ")", ";", "return", "FileVisitResult", ".", "CONTINUE", ";", "}", "}", ")", ";", "}" ]
Copies directories, preserving file attributes. <p> The {@link org.zeroturnaround.zip.commons.FileUtilsV2_2#copyDirectory(File, File)} function does not preserve file attributes.
[ "Copies", "directories", "preserving", "file", "attributes", ".", "<p", ">", "The", "{" ]
train
https://github.com/libgdx/packr/blob/4dd00a1fb5075dc1b6cd84f46bfdd918eb3d50e9/src/main/java/com/badlogicgames/packr/PackrFileUtils.java#L55-L80
w3c/epubcheck
src/main/java/com/adobe/epubcheck/util/SearchDictionary.java
SearchDictionary.buildCSSTypesDictionary
void buildCSSTypesDictionary() { """ /* String[] validTypes = new String[] { "application/xhtml+xml", "application/x-dtbncx+xml", "text/css" }; """ String description; String value; TextSearchDictionaryEntry de; //search eval() expression description = "text/css"; value = "text/css"; de = new TextSearchDictionaryEntry(description, value, MessageId.CSS_009); v.add(de); }
java
void buildCSSTypesDictionary() { String description; String value; TextSearchDictionaryEntry de; //search eval() expression description = "text/css"; value = "text/css"; de = new TextSearchDictionaryEntry(description, value, MessageId.CSS_009); v.add(de); }
[ "void", "buildCSSTypesDictionary", "(", ")", "{", "String", "description", ";", "String", "value", ";", "TextSearchDictionaryEntry", "de", ";", "//search eval() expression", "description", "=", "\"text/css\"", ";", "value", "=", "\"text/css\"", ";", "de", "=", "new", "TextSearchDictionaryEntry", "(", "description", ",", "value", ",", "MessageId", ".", "CSS_009", ")", ";", "v", ".", "add", "(", "de", ")", ";", "}" ]
/* String[] validTypes = new String[] { "application/xhtml+xml", "application/x-dtbncx+xml", "text/css" };
[ "/", "*", "String", "[]", "validTypes", "=", "new", "String", "[]", "{", "application", "/", "xhtml", "+", "xml", "application", "/", "x", "-", "dtbncx", "+", "xml", "text", "/", "css", "}", ";" ]
train
https://github.com/w3c/epubcheck/blob/4d5a24d9f2878a2a5497eb11c036cc18fe2c0a78/src/main/java/com/adobe/epubcheck/util/SearchDictionary.java#L49-L63
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java
CPMeasurementUnitPersistenceImpl.countByG_P_T
@Override public int countByG_P_T(long groupId, boolean primary, int type) { """ Returns the number of cp measurement units where groupId = &#63; and primary = &#63; and type = &#63;. @param groupId the group ID @param primary the primary @param type the type @return the number of matching cp measurement units """ FinderPath finderPath = FINDER_PATH_COUNT_BY_G_P_T; Object[] finderArgs = new Object[] { groupId, primary, type }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(4); query.append(_SQL_COUNT_CPMEASUREMENTUNIT_WHERE); query.append(_FINDER_COLUMN_G_P_T_GROUPID_2); query.append(_FINDER_COLUMN_G_P_T_PRIMARY_2); query.append(_FINDER_COLUMN_G_P_T_TYPE_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(groupId); qPos.add(primary); qPos.add(type); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
java
@Override public int countByG_P_T(long groupId, boolean primary, int type) { FinderPath finderPath = FINDER_PATH_COUNT_BY_G_P_T; Object[] finderArgs = new Object[] { groupId, primary, type }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(4); query.append(_SQL_COUNT_CPMEASUREMENTUNIT_WHERE); query.append(_FINDER_COLUMN_G_P_T_GROUPID_2); query.append(_FINDER_COLUMN_G_P_T_PRIMARY_2); query.append(_FINDER_COLUMN_G_P_T_TYPE_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(groupId); qPos.add(primary); qPos.add(type); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
[ "@", "Override", "public", "int", "countByG_P_T", "(", "long", "groupId", ",", "boolean", "primary", ",", "int", "type", ")", "{", "FinderPath", "finderPath", "=", "FINDER_PATH_COUNT_BY_G_P_T", ";", "Object", "[", "]", "finderArgs", "=", "new", "Object", "[", "]", "{", "groupId", ",", "primary", ",", "type", "}", ";", "Long", "count", "=", "(", "Long", ")", "finderCache", ".", "getResult", "(", "finderPath", ",", "finderArgs", ",", "this", ")", ";", "if", "(", "count", "==", "null", ")", "{", "StringBundler", "query", "=", "new", "StringBundler", "(", "4", ")", ";", "query", ".", "append", "(", "_SQL_COUNT_CPMEASUREMENTUNIT_WHERE", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_G_P_T_GROUPID_2", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_G_P_T_PRIMARY_2", ")", ";", "query", ".", "append", "(", "_FINDER_COLUMN_G_P_T_TYPE_2", ")", ";", "String", "sql", "=", "query", ".", "toString", "(", ")", ";", "Session", "session", "=", "null", ";", "try", "{", "session", "=", "openSession", "(", ")", ";", "Query", "q", "=", "session", ".", "createQuery", "(", "sql", ")", ";", "QueryPos", "qPos", "=", "QueryPos", ".", "getInstance", "(", "q", ")", ";", "qPos", ".", "add", "(", "groupId", ")", ";", "qPos", ".", "add", "(", "primary", ")", ";", "qPos", ".", "add", "(", "type", ")", ";", "count", "=", "(", "Long", ")", "q", ".", "uniqueResult", "(", ")", ";", "finderCache", ".", "putResult", "(", "finderPath", ",", "finderArgs", ",", "count", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "finderCache", ".", "removeResult", "(", "finderPath", ",", "finderArgs", ")", ";", "throw", "processException", "(", "e", ")", ";", "}", "finally", "{", "closeSession", "(", "session", ")", ";", "}", "}", "return", "count", ".", "intValue", "(", ")", ";", "}" ]
Returns the number of cp measurement units where groupId = &#63; and primary = &#63; and type = &#63;. @param groupId the group ID @param primary the primary @param type the type @return the number of matching cp measurement units
[ "Returns", "the", "number", "of", "cp", "measurement", "units", "where", "groupId", "=", "&#63", ";", "and", "primary", "=", "&#63", ";", "and", "type", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPMeasurementUnitPersistenceImpl.java#L3344-L3395
bwkimmel/jdcp
jdcp-server/src/main/java/ca/eandb/jdcp/server/JobServer.java
JobServer.handleJobExecutionException
private void handleJobExecutionException(JobExecutionException e, UUID jobId) { """ Handles a <code>JobExcecutionException</code> thrown by a job managed by this server. @param e The <code>JobExecutionException</code> that was thrown by the job. @param jobId The <code>UUID</code> identifying the job that threw the exception. """ logger.error("Exception thrown from job " + jobId.toString(), e); removeScheduledJob(jobId, false); }
java
private void handleJobExecutionException(JobExecutionException e, UUID jobId) { logger.error("Exception thrown from job " + jobId.toString(), e); removeScheduledJob(jobId, false); }
[ "private", "void", "handleJobExecutionException", "(", "JobExecutionException", "e", ",", "UUID", "jobId", ")", "{", "logger", ".", "error", "(", "\"Exception thrown from job \"", "+", "jobId", ".", "toString", "(", ")", ",", "e", ")", ";", "removeScheduledJob", "(", "jobId", ",", "false", ")", ";", "}" ]
Handles a <code>JobExcecutionException</code> thrown by a job managed by this server. @param e The <code>JobExecutionException</code> that was thrown by the job. @param jobId The <code>UUID</code> identifying the job that threw the exception.
[ "Handles", "a", "<code", ">", "JobExcecutionException<", "/", "code", ">", "thrown", "by", "a", "job", "managed", "by", "this", "server", "." ]
train
https://github.com/bwkimmel/jdcp/blob/630c5150c245054e2556ff370f4bad2ec793dfb7/jdcp-server/src/main/java/ca/eandb/jdcp/server/JobServer.java#L537-L540
line/armeria
core/src/main/java/com/linecorp/armeria/common/logging/LoggingDecoratorBuilder.java
LoggingDecoratorBuilder.contentSanitizer
public T contentSanitizer(Function<Object, ?> contentSanitizer) { """ Sets the {@link Function} to use to sanitize request and response content before logging. It is common to have the {@link Function} that removes sensitive content, such as an GPS location query and an address, before logging. If unset, will use {@link Function#identity()}. This method is a shortcut of: <pre>{@code builder.requestContentSanitizer(contentSanitizer); builder.responseContentSanitizer(contentSanitizer); }</pre> @see #requestContentSanitizer(Function) @see #responseContentSanitizer(Function) """ requireNonNull(contentSanitizer, "contentSanitizer"); requestContentSanitizer(contentSanitizer); responseContentSanitizer(contentSanitizer); return self(); }
java
public T contentSanitizer(Function<Object, ?> contentSanitizer) { requireNonNull(contentSanitizer, "contentSanitizer"); requestContentSanitizer(contentSanitizer); responseContentSanitizer(contentSanitizer); return self(); }
[ "public", "T", "contentSanitizer", "(", "Function", "<", "Object", ",", "?", ">", "contentSanitizer", ")", "{", "requireNonNull", "(", "contentSanitizer", ",", "\"contentSanitizer\"", ")", ";", "requestContentSanitizer", "(", "contentSanitizer", ")", ";", "responseContentSanitizer", "(", "contentSanitizer", ")", ";", "return", "self", "(", ")", ";", "}" ]
Sets the {@link Function} to use to sanitize request and response content before logging. It is common to have the {@link Function} that removes sensitive content, such as an GPS location query and an address, before logging. If unset, will use {@link Function#identity()}. This method is a shortcut of: <pre>{@code builder.requestContentSanitizer(contentSanitizer); builder.responseContentSanitizer(contentSanitizer); }</pre> @see #requestContentSanitizer(Function) @see #responseContentSanitizer(Function)
[ "Sets", "the", "{", "@link", "Function", "}", "to", "use", "to", "sanitize", "request", "and", "response", "content", "before", "logging", ".", "It", "is", "common", "to", "have", "the", "{", "@link", "Function", "}", "that", "removes", "sensitive", "content", "such", "as", "an", "GPS", "location", "query", "and", "an", "address", "before", "logging", ".", "If", "unset", "will", "use", "{", "@link", "Function#identity", "()", "}", ".", "This", "method", "is", "a", "shortcut", "of", ":", "<pre", ">", "{", "@code", "builder", ".", "requestContentSanitizer", "(", "contentSanitizer", ")", ";", "builder", ".", "responseContentSanitizer", "(", "contentSanitizer", ")", ";", "}", "<", "/", "pre", ">" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/common/logging/LoggingDecoratorBuilder.java#L243-L248
nostra13/Android-Universal-Image-Loader
library/src/main/java/com/nostra13/universalimageloader/core/download/BaseImageDownloader.java
BaseImageDownloader.getStreamFromDrawable
protected InputStream getStreamFromDrawable(String imageUri, Object extra) { """ Retrieves {@link InputStream} of image by URI (image is located in drawable resources of application). @param imageUri Image URI @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) DisplayImageOptions.extraForDownloader(Object)}; can be null @return {@link InputStream} of image """ String drawableIdString = Scheme.DRAWABLE.crop(imageUri); int drawableId = Integer.parseInt(drawableIdString); return context.getResources().openRawResource(drawableId); }
java
protected InputStream getStreamFromDrawable(String imageUri, Object extra) { String drawableIdString = Scheme.DRAWABLE.crop(imageUri); int drawableId = Integer.parseInt(drawableIdString); return context.getResources().openRawResource(drawableId); }
[ "protected", "InputStream", "getStreamFromDrawable", "(", "String", "imageUri", ",", "Object", "extra", ")", "{", "String", "drawableIdString", "=", "Scheme", ".", "DRAWABLE", ".", "crop", "(", "imageUri", ")", ";", "int", "drawableId", "=", "Integer", ".", "parseInt", "(", "drawableIdString", ")", ";", "return", "context", ".", "getResources", "(", ")", ".", "openRawResource", "(", "drawableId", ")", ";", "}" ]
Retrieves {@link InputStream} of image by URI (image is located in drawable resources of application). @param imageUri Image URI @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) DisplayImageOptions.extraForDownloader(Object)}; can be null @return {@link InputStream} of image
[ "Retrieves", "{", "@link", "InputStream", "}", "of", "image", "by", "URI", "(", "image", "is", "located", "in", "drawable", "resources", "of", "application", ")", "." ]
train
https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/core/download/BaseImageDownloader.java#L260-L264
alkacon/opencms-core
src/org/opencms/search/documents/CmsExtractionResultCache.java
CmsExtractionResultCache.saveCacheObject
public void saveCacheObject(String rfsName, I_CmsExtractionResult content) throws IOException { """ Serializes the given extraction result and saves it in the disk cache.<p> @param rfsName the RFS name of the file to save the extraction result in @param content the extraction result to serialize and save @throws IOException in case of disk access errors """ byte[] byteContent = content.getBytes(); if (byteContent != null) { CmsVfsDiskCache.saveFile(rfsName, byteContent); } }
java
public void saveCacheObject(String rfsName, I_CmsExtractionResult content) throws IOException { byte[] byteContent = content.getBytes(); if (byteContent != null) { CmsVfsDiskCache.saveFile(rfsName, byteContent); } }
[ "public", "void", "saveCacheObject", "(", "String", "rfsName", ",", "I_CmsExtractionResult", "content", ")", "throws", "IOException", "{", "byte", "[", "]", "byteContent", "=", "content", ".", "getBytes", "(", ")", ";", "if", "(", "byteContent", "!=", "null", ")", "{", "CmsVfsDiskCache", ".", "saveFile", "(", "rfsName", ",", "byteContent", ")", ";", "}", "}" ]
Serializes the given extraction result and saves it in the disk cache.<p> @param rfsName the RFS name of the file to save the extraction result in @param content the extraction result to serialize and save @throws IOException in case of disk access errors
[ "Serializes", "the", "given", "extraction", "result", "and", "saves", "it", "in", "the", "disk", "cache", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/documents/CmsExtractionResultCache.java#L208-L214
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSType.java
JSType.getTypesUnderShallowEquality
public TypePair getTypesUnderShallowEquality(JSType that) { """ Computes the subset of {@code this} and {@code that} types under shallow equality. @return a pair containing the restricted type of {@code this} as the first component and the restricted type of {@code that} as the second element. The returned pair is never {@code null} even though its components may be {@code null}. """ JSType commonType = getGreatestSubtype(that); return new TypePair(commonType, commonType); }
java
public TypePair getTypesUnderShallowEquality(JSType that) { JSType commonType = getGreatestSubtype(that); return new TypePair(commonType, commonType); }
[ "public", "TypePair", "getTypesUnderShallowEquality", "(", "JSType", "that", ")", "{", "JSType", "commonType", "=", "getGreatestSubtype", "(", "that", ")", ";", "return", "new", "TypePair", "(", "commonType", ",", "commonType", ")", ";", "}" ]
Computes the subset of {@code this} and {@code that} types under shallow equality. @return a pair containing the restricted type of {@code this} as the first component and the restricted type of {@code that} as the second element. The returned pair is never {@code null} even though its components may be {@code null}.
[ "Computes", "the", "subset", "of", "{", "@code", "this", "}", "and", "{", "@code", "that", "}", "types", "under", "shallow", "equality", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSType.java#L1419-L1422
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/BaseRequest.java
BaseRequest.updateProgressListener
protected void updateProgressListener(ProgressListener progressListener, Response response) { """ As a download request progresses, periodically call the user's ProgressListener """ InputStream responseStream = response.getResponseByteStream(); int bytesDownloaded = 0; long totalBytesExpected = response.getContentLength(); // Reading 2 KiB at a time to be consistent with the upload segment size in ProgressRequestBody final int segmentSize = 2048; byte[] responseBytes; if (totalBytesExpected > Integer.MAX_VALUE) { logger.warn("The response body for " + getUrl() + " is too large to hold in a byte array. Only the first 2 GiB will be available."); responseBytes = new byte[Integer.MAX_VALUE]; } else { responseBytes = new byte[(int)totalBytesExpected]; } // For every 2 KiB downloaded: // 1) Call the user's ProgressListener // 2) Append the downloaded bytes into a byte array int nextByte; try { while ((nextByte = responseStream.read()) != -1) { if (bytesDownloaded % segmentSize == 0) { progressListener.onProgress(bytesDownloaded, totalBytesExpected); } responseBytes[bytesDownloaded] = (byte)nextByte; bytesDownloaded += 1; } } catch (IOException e) { logger.error("IO Exception: " + e.getMessage()); } // Transfer the downloaded data to the Response object so that the user can later retrieve it if (response instanceof ResponseImpl) { ((ResponseImpl)response).setResponseBytes(responseBytes); } }
java
protected void updateProgressListener(ProgressListener progressListener, Response response) { InputStream responseStream = response.getResponseByteStream(); int bytesDownloaded = 0; long totalBytesExpected = response.getContentLength(); // Reading 2 KiB at a time to be consistent with the upload segment size in ProgressRequestBody final int segmentSize = 2048; byte[] responseBytes; if (totalBytesExpected > Integer.MAX_VALUE) { logger.warn("The response body for " + getUrl() + " is too large to hold in a byte array. Only the first 2 GiB will be available."); responseBytes = new byte[Integer.MAX_VALUE]; } else { responseBytes = new byte[(int)totalBytesExpected]; } // For every 2 KiB downloaded: // 1) Call the user's ProgressListener // 2) Append the downloaded bytes into a byte array int nextByte; try { while ((nextByte = responseStream.read()) != -1) { if (bytesDownloaded % segmentSize == 0) { progressListener.onProgress(bytesDownloaded, totalBytesExpected); } responseBytes[bytesDownloaded] = (byte)nextByte; bytesDownloaded += 1; } } catch (IOException e) { logger.error("IO Exception: " + e.getMessage()); } // Transfer the downloaded data to the Response object so that the user can later retrieve it if (response instanceof ResponseImpl) { ((ResponseImpl)response).setResponseBytes(responseBytes); } }
[ "protected", "void", "updateProgressListener", "(", "ProgressListener", "progressListener", ",", "Response", "response", ")", "{", "InputStream", "responseStream", "=", "response", ".", "getResponseByteStream", "(", ")", ";", "int", "bytesDownloaded", "=", "0", ";", "long", "totalBytesExpected", "=", "response", ".", "getContentLength", "(", ")", ";", "// Reading 2 KiB at a time to be consistent with the upload segment size in ProgressRequestBody", "final", "int", "segmentSize", "=", "2048", ";", "byte", "[", "]", "responseBytes", ";", "if", "(", "totalBytesExpected", ">", "Integer", ".", "MAX_VALUE", ")", "{", "logger", ".", "warn", "(", "\"The response body for \"", "+", "getUrl", "(", ")", "+", "\" is too large to hold in a byte array. Only the first 2 GiB will be available.\"", ")", ";", "responseBytes", "=", "new", "byte", "[", "Integer", ".", "MAX_VALUE", "]", ";", "}", "else", "{", "responseBytes", "=", "new", "byte", "[", "(", "int", ")", "totalBytesExpected", "]", ";", "}", "// For every 2 KiB downloaded:", "// 1) Call the user's ProgressListener", "// 2) Append the downloaded bytes into a byte array", "int", "nextByte", ";", "try", "{", "while", "(", "(", "nextByte", "=", "responseStream", ".", "read", "(", ")", ")", "!=", "-", "1", ")", "{", "if", "(", "bytesDownloaded", "%", "segmentSize", "==", "0", ")", "{", "progressListener", ".", "onProgress", "(", "bytesDownloaded", ",", "totalBytesExpected", ")", ";", "}", "responseBytes", "[", "bytesDownloaded", "]", "=", "(", "byte", ")", "nextByte", ";", "bytesDownloaded", "+=", "1", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "error", "(", "\"IO Exception: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "// Transfer the downloaded data to the Response object so that the user can later retrieve it", "if", "(", "response", "instanceof", "ResponseImpl", ")", "{", "(", "(", "ResponseImpl", ")", "response", ")", ".", "setResponseBytes", "(", "responseBytes", ")", ";", "}", "}" ]
As a download request progresses, periodically call the user's ProgressListener
[ "As", "a", "download", "request", "progresses", "periodically", "call", "the", "user", "s", "ProgressListener" ]
train
https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-android-core/blob/8db4f00d0d564792397bfc0e5bd57d52a238b858/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/BaseRequest.java#L794-L832
Samsung/GearVRf
GVRf/Extensions/script/src/main/java/org/gearvrf/script/javascript/ExternalScriptable.java
ExternalScriptable.has
public synchronized boolean has(int index, Scriptable start) { """ Returns true if the property index is defined. @param index the numeric index for the property @param start the object in which the lookup began @return true if and only if the property was found in the object """ Integer key = new Integer(index); return indexedProps.containsKey(key); }
java
public synchronized boolean has(int index, Scriptable start) { Integer key = new Integer(index); return indexedProps.containsKey(key); }
[ "public", "synchronized", "boolean", "has", "(", "int", "index", ",", "Scriptable", "start", ")", "{", "Integer", "key", "=", "new", "Integer", "(", "index", ")", ";", "return", "indexedProps", ".", "containsKey", "(", "key", ")", ";", "}" ]
Returns true if the property index is defined. @param index the numeric index for the property @param start the object in which the lookup began @return true if and only if the property was found in the object
[ "Returns", "true", "if", "the", "property", "index", "is", "defined", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/script/src/main/java/org/gearvrf/script/javascript/ExternalScriptable.java#L161-L164
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/FileUtil.java
FileUtil.appendToFile
public static File appendToFile(String filename, String extraContent, boolean onNewLine) { """ Appends the extra content to the file, in UTF-8 encoding. @param filename file to create or append to. @param extraContent extraContent to write. @param onNewLine whether a new line should be created before appending the extra content @return file reference to file. """ PrintWriter pw = null; try { pw = new PrintWriter( new BufferedWriter( new OutputStreamWriter( new FileOutputStream(filename, true), FILE_ENCODING) ) ); if (onNewLine) { pw.println(); } pw.print(extraContent); } catch (FileNotFoundException e) { throw new IllegalArgumentException("Unable to write to: " + filename, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } finally { if (pw != null) { pw.close(); } } return new File(filename); }
java
public static File appendToFile(String filename, String extraContent, boolean onNewLine){ PrintWriter pw = null; try { pw = new PrintWriter( new BufferedWriter( new OutputStreamWriter( new FileOutputStream(filename, true), FILE_ENCODING) ) ); if (onNewLine) { pw.println(); } pw.print(extraContent); } catch (FileNotFoundException e) { throw new IllegalArgumentException("Unable to write to: " + filename, e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } finally { if (pw != null) { pw.close(); } } return new File(filename); }
[ "public", "static", "File", "appendToFile", "(", "String", "filename", ",", "String", "extraContent", ",", "boolean", "onNewLine", ")", "{", "PrintWriter", "pw", "=", "null", ";", "try", "{", "pw", "=", "new", "PrintWriter", "(", "new", "BufferedWriter", "(", "new", "OutputStreamWriter", "(", "new", "FileOutputStream", "(", "filename", ",", "true", ")", ",", "FILE_ENCODING", ")", ")", ")", ";", "if", "(", "onNewLine", ")", "{", "pw", ".", "println", "(", ")", ";", "}", "pw", ".", "print", "(", "extraContent", ")", ";", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Unable to write to: \"", "+", "filename", ",", "e", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "finally", "{", "if", "(", "pw", "!=", "null", ")", "{", "pw", ".", "close", "(", ")", ";", "}", "}", "return", "new", "File", "(", "filename", ")", ";", "}" ]
Appends the extra content to the file, in UTF-8 encoding. @param filename file to create or append to. @param extraContent extraContent to write. @param onNewLine whether a new line should be created before appending the extra content @return file reference to file.
[ "Appends", "the", "extra", "content", "to", "the", "file", "in", "UTF", "-", "8", "encoding", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/FileUtil.java#L287-L311
jglobus/JGlobus
io/src/main/java/org/globus/io/gass/client/internal/GASSProtocol.java
GASSProtocol.GET
public static String GET(String path, String host) { """ This method concatenates a properly formatted header for performing Globus Gass GETs with the given information. @param path the path of the file to get @param host the host which contains the file to get @return <code>String</code> the properly formatted header to be sent to a gass server """ return HTTPProtocol.createGETHeader("/" + path, host, USER_AGENT); }
java
public static String GET(String path, String host) { return HTTPProtocol.createGETHeader("/" + path, host, USER_AGENT); }
[ "public", "static", "String", "GET", "(", "String", "path", ",", "String", "host", ")", "{", "return", "HTTPProtocol", ".", "createGETHeader", "(", "\"/\"", "+", "path", ",", "host", ",", "USER_AGENT", ")", ";", "}" ]
This method concatenates a properly formatted header for performing Globus Gass GETs with the given information. @param path the path of the file to get @param host the host which contains the file to get @return <code>String</code> the properly formatted header to be sent to a gass server
[ "This", "method", "concatenates", "a", "properly", "formatted", "header", "for", "performing", "Globus", "Gass", "GETs", "with", "the", "given", "information", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/io/src/main/java/org/globus/io/gass/client/internal/GASSProtocol.java#L43-L45
wuman/orientdb-android
commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java
OMVRBTree.getEntry
public final OMVRBTreeEntry<K, V> getEntry(final Object key, final PartialSearchMode partialSearchMode) { """ Returns this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key. In case of {@link OCompositeKey} keys you can specify which key can be used: lowest, highest, any. @param key Key to search. @param partialSearchMode Which key can be used in case of {@link OCompositeKey} key is passed in. @return this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key @throws ClassCastException if the specified key cannot be compared with the keys currently in the map @throws NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys """ return getEntry(key, false, partialSearchMode); }
java
public final OMVRBTreeEntry<K, V> getEntry(final Object key, final PartialSearchMode partialSearchMode) { return getEntry(key, false, partialSearchMode); }
[ "public", "final", "OMVRBTreeEntry", "<", "K", ",", "V", ">", "getEntry", "(", "final", "Object", "key", ",", "final", "PartialSearchMode", "partialSearchMode", ")", "{", "return", "getEntry", "(", "key", ",", "false", ",", "partialSearchMode", ")", ";", "}" ]
Returns this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key. In case of {@link OCompositeKey} keys you can specify which key can be used: lowest, highest, any. @param key Key to search. @param partialSearchMode Which key can be used in case of {@link OCompositeKey} key is passed in. @return this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key @throws ClassCastException if the specified key cannot be compared with the keys currently in the map @throws NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
[ "Returns", "this", "map", "s", "entry", "for", "the", "given", "key", "or", "<tt", ">", "null<", "/", "tt", ">", "if", "the", "map", "does", "not", "contain", "an", "entry", "for", "the", "key", "." ]
train
https://github.com/wuman/orientdb-android/blob/ff9b17e4349f26168b2d0c4facb1a18cbfbe8cf0/commons/src/main/java/com/orientechnologies/common/collection/OMVRBTree.java#L350-L352
ow2-chameleon/fuchsia
bases/knx/calimero/src/main/java/tuwien/auto/calimero/tools/ProcComm.java
ProcComm.main
public static void main(String[] args) { """ Entry point for running ProcComm. <p> An IP host or port identifier has to be supplied, specifying the endpoint for the KNX network access.<br> To show the usage message of this tool on the console, supply the command line option -help (or -h).<br> Command line options are treated case sensitive. Available options for the communication connection: <ul> <li><code>-help -h</code> show help message</li> <li><code>-version</code> show tool/library version and exit</li> <li><code>-verbose -v</code> enable verbose status output</li> <li><code>-localhost</code> <i>id</i> &nbsp;local IP/host name</li> <li><code>-localport</code> <i>number</i> &nbsp;local UDP port (default system assigned)</li> <li><code>-port -p</code> <i>number</i> &nbsp;UDP port on host (default 3671)</li> <li><code>-nat -n</code> enable Network Address Translation</li> <li><code>-routing</code> use KNXnet/IP routing</li> <li><code>-serial -s</code> use FT1.2 serial communication</li> <li><code>-medium -m</code> <i>id</i> &nbsp;KNX medium [tp0|tp1|p110|p132|rf] (defaults to tp1)</li> </ul> Available commands for process communication: <ul> <li><code>read</code> <i>DPT &nbsp;KNX-address</i> &nbsp;read from group address, using DPT value format</li> <li><code>write</code> <i>DPT &nbsp;value &nbsp;KNX-address</i> &nbsp;write to group address, using DPT value format</li> </ul> For the more common datapoint types (DPTs) the following name aliases can be used instead of the general DPT number string: <ul> <li><code>switch</code> for DPT 1.001</li> <li><code>bool</code> for DPT 1.002</li> <li><code>string</code> for DPT 16.001</li> <li><code>float</code> for DPT 9.002</li> <li><code>ucount</code> for DPT 5.010</li> <li><code>angle</code> for DPT 5.003</li> </ul> @param args command line options for process communication """ try { final ProcComm pc = new ProcComm(args, null); // use a log writer for the console (System.out), setting the user // specified log level, if any pc.w = new ConsoleWriter(pc.options.containsKey("verbose")); if (pc.options.containsKey("read") == pc.options.containsKey("write")) throw new IllegalArgumentException("do either read or write"); try { pc.run(null); pc.readWrite(); } finally { pc.quit(); } } catch (final Throwable t) { if (t.getMessage() != null) System.out.println(t.getMessage()); } }
java
public static void main(String[] args) { try { final ProcComm pc = new ProcComm(args, null); // use a log writer for the console (System.out), setting the user // specified log level, if any pc.w = new ConsoleWriter(pc.options.containsKey("verbose")); if (pc.options.containsKey("read") == pc.options.containsKey("write")) throw new IllegalArgumentException("do either read or write"); try { pc.run(null); pc.readWrite(); } finally { pc.quit(); } } catch (final Throwable t) { if (t.getMessage() != null) System.out.println(t.getMessage()); } }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "try", "{", "final", "ProcComm", "pc", "=", "new", "ProcComm", "(", "args", ",", "null", ")", ";", "// use a log writer for the console (System.out), setting the user\r", "// specified log level, if any\r", "pc", ".", "w", "=", "new", "ConsoleWriter", "(", "pc", ".", "options", ".", "containsKey", "(", "\"verbose\"", ")", ")", ";", "if", "(", "pc", ".", "options", ".", "containsKey", "(", "\"read\"", ")", "==", "pc", ".", "options", ".", "containsKey", "(", "\"write\"", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"do either read or write\"", ")", ";", "try", "{", "pc", ".", "run", "(", "null", ")", ";", "pc", ".", "readWrite", "(", ")", ";", "}", "finally", "{", "pc", ".", "quit", "(", ")", ";", "}", "}", "catch", "(", "final", "Throwable", "t", ")", "{", "if", "(", "t", ".", "getMessage", "(", ")", "!=", "null", ")", "System", ".", "out", ".", "println", "(", "t", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Entry point for running ProcComm. <p> An IP host or port identifier has to be supplied, specifying the endpoint for the KNX network access.<br> To show the usage message of this tool on the console, supply the command line option -help (or -h).<br> Command line options are treated case sensitive. Available options for the communication connection: <ul> <li><code>-help -h</code> show help message</li> <li><code>-version</code> show tool/library version and exit</li> <li><code>-verbose -v</code> enable verbose status output</li> <li><code>-localhost</code> <i>id</i> &nbsp;local IP/host name</li> <li><code>-localport</code> <i>number</i> &nbsp;local UDP port (default system assigned)</li> <li><code>-port -p</code> <i>number</i> &nbsp;UDP port on host (default 3671)</li> <li><code>-nat -n</code> enable Network Address Translation</li> <li><code>-routing</code> use KNXnet/IP routing</li> <li><code>-serial -s</code> use FT1.2 serial communication</li> <li><code>-medium -m</code> <i>id</i> &nbsp;KNX medium [tp0|tp1|p110|p132|rf] (defaults to tp1)</li> </ul> Available commands for process communication: <ul> <li><code>read</code> <i>DPT &nbsp;KNX-address</i> &nbsp;read from group address, using DPT value format</li> <li><code>write</code> <i>DPT &nbsp;value &nbsp;KNX-address</i> &nbsp;write to group address, using DPT value format</li> </ul> For the more common datapoint types (DPTs) the following name aliases can be used instead of the general DPT number string: <ul> <li><code>switch</code> for DPT 1.001</li> <li><code>bool</code> for DPT 1.002</li> <li><code>string</code> for DPT 16.001</li> <li><code>float</code> for DPT 9.002</li> <li><code>ucount</code> for DPT 5.010</li> <li><code>angle</code> for DPT 5.003</li> </ul> @param args command line options for process communication
[ "Entry", "point", "for", "running", "ProcComm", ".", "<p", ">", "An", "IP", "host", "or", "port", "identifier", "has", "to", "be", "supplied", "specifying", "the", "endpoint", "for", "the", "KNX", "network", "access", ".", "<br", ">", "To", "show", "the", "usage", "message", "of", "this", "tool", "on", "the", "console", "supply", "the", "command", "line", "option", "-", "help", "(", "or", "-", "h", ")", ".", "<br", ">", "Command", "line", "options", "are", "treated", "case", "sensitive", ".", "Available", "options", "for", "the", "communication", "connection", ":", "<ul", ">", "<li", ">", "<code", ">", "-", "help", "-", "h<", "/", "code", ">", "show", "help", "message<", "/", "li", ">", "<li", ">", "<code", ">", "-", "version<", "/", "code", ">", "show", "tool", "/", "library", "version", "and", "exit<", "/", "li", ">", "<li", ">", "<code", ">", "-", "verbose", "-", "v<", "/", "code", ">", "enable", "verbose", "status", "output<", "/", "li", ">", "<li", ">", "<code", ">", "-", "localhost<", "/", "code", ">", "<i", ">", "id<", "/", "i", ">", "&nbsp", ";", "local", "IP", "/", "host", "name<", "/", "li", ">", "<li", ">", "<code", ">", "-", "localport<", "/", "code", ">", "<i", ">", "number<", "/", "i", ">", "&nbsp", ";", "local", "UDP", "port", "(", "default", "system", "assigned", ")", "<", "/", "li", ">", "<li", ">", "<code", ">", "-", "port", "-", "p<", "/", "code", ">", "<i", ">", "number<", "/", "i", ">", "&nbsp", ";", "UDP", "port", "on", "host", "(", "default", "3671", ")", "<", "/", "li", ">", "<li", ">", "<code", ">", "-", "nat", "-", "n<", "/", "code", ">", "enable", "Network", "Address", "Translation<", "/", "li", ">", "<li", ">", "<code", ">", "-", "routing<", "/", "code", ">", "use", "KNXnet", "/", "IP", "routing<", "/", "li", ">", "<li", ">", "<code", ">", "-", "serial", "-", "s<", "/", "code", ">", "use", "FT1", ".", "2", "serial", "communication<", "/", "li", ">", "<li", ">", "<code", ">", "-", "medium", "-", "m<", "/", "code", ">", "<i", ">", "id<", "/", "i", ">", "&nbsp", ";", "KNX", "medium", "[", "tp0|tp1|p110|p132|rf", "]", "(", "defaults", "to", "tp1", ")", "<", "/", "li", ">", "<", "/", "ul", ">", "Available", "commands", "for", "process", "communication", ":", "<ul", ">", "<li", ">", "<code", ">", "read<", "/", "code", ">", "<i", ">", "DPT", "&nbsp", ";", "KNX", "-", "address<", "/", "i", ">", "&nbsp", ";", "read", "from", "group", "address", "using", "DPT", "value", "format<", "/", "li", ">", "<li", ">", "<code", ">", "write<", "/", "code", ">", "<i", ">", "DPT", "&nbsp", ";", "value", "&nbsp", ";", "KNX", "-", "address<", "/", "i", ">", "&nbsp", ";", "write", "to", "group", "address", "using", "DPT", "value", "format<", "/", "li", ">", "<", "/", "ul", ">", "For", "the", "more", "common", "datapoint", "types", "(", "DPTs", ")", "the", "following", "name", "aliases", "can", "be", "used", "instead", "of", "the", "general", "DPT", "number", "string", ":", "<ul", ">", "<li", ">", "<code", ">", "switch<", "/", "code", ">", "for", "DPT", "1", ".", "001<", "/", "li", ">", "<li", ">", "<code", ">", "bool<", "/", "code", ">", "for", "DPT", "1", ".", "002<", "/", "li", ">", "<li", ">", "<code", ">", "string<", "/", "code", ">", "for", "DPT", "16", ".", "001<", "/", "li", ">", "<li", ">", "<code", ">", "float<", "/", "code", ">", "for", "DPT", "9", ".", "002<", "/", "li", ">", "<li", ">", "<code", ">", "ucount<", "/", "code", ">", "for", "DPT", "5", ".", "010<", "/", "li", ">", "<li", ">", "<code", ">", "angle<", "/", "code", ">", "for", "DPT", "5", ".", "003<", "/", "li", ">", "<", "/", "ul", ">" ]
train
https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/bases/knx/calimero/src/main/java/tuwien/auto/calimero/tools/ProcComm.java#L169-L190
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/activity_status.java
activity_status.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { """ <pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre> """ activity_status_responses result = (activity_status_responses) service.get_payload_formatter().string_to_resource(activity_status_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.activity_status_response_array); } activity_status[] result_activity_status = new activity_status[result.activity_status_response_array.length]; for(int i = 0; i < result.activity_status_response_array.length; i++) { result_activity_status[i] = result.activity_status_response_array[i].activity_status[0]; } return result_activity_status; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { activity_status_responses result = (activity_status_responses) service.get_payload_formatter().string_to_resource(activity_status_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.activity_status_response_array); } activity_status[] result_activity_status = new activity_status[result.activity_status_response_array.length]; for(int i = 0; i < result.activity_status_response_array.length; i++) { result_activity_status[i] = result.activity_status_response_array[i].activity_status[0]; } return result_activity_status; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "activity_status_responses", "result", "=", "(", "activity_status_responses", ")", "service", ".", "get_payload_formatter", "(", ")", ".", "string_to_resource", "(", "activity_status_responses", ".", "class", ",", "response", ")", ";", "if", "(", "result", ".", "errorcode", "!=", "0", ")", "{", "if", "(", "result", ".", "errorcode", "==", "SESSION_NOT_EXISTS", ")", "service", ".", "clear_session", "(", ")", ";", "throw", "new", "nitro_exception", "(", "result", ".", "message", ",", "result", ".", "errorcode", ",", "(", "base_response", "[", "]", ")", "result", ".", "activity_status_response_array", ")", ";", "}", "activity_status", "[", "]", "result_activity_status", "=", "new", "activity_status", "[", "result", ".", "activity_status_response_array", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "activity_status_response_array", ".", "length", ";", "i", "++", ")", "{", "result_activity_status", "[", "i", "]", "=", "result", ".", "activity_status_response_array", "[", "i", "]", ".", "activity_status", "[", "0", "]", ";", "}", "return", "result_activity_status", ";", "}" ]
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/activity_status.java#L281-L298
junit-team/junit4
src/main/java/org/junit/runner/Computer.java
Computer.getSuite
public Runner getSuite(final RunnerBuilder builder, Class<?>[] classes) throws InitializationError { """ Create a suite for {@code classes}, building Runners with {@code builder}. Throws an InitializationError if Runner construction fails """ return new Suite(new RunnerBuilder() { @Override public Runner runnerForClass(Class<?> testClass) throws Throwable { return getRunner(builder, testClass); } }, classes) { @Override protected String getName() { /* * #1320 The generated suite is not based on a real class so * only a 'null' description can be generated from it. This name * will be overridden here. */ return "classes"; } }; }
java
public Runner getSuite(final RunnerBuilder builder, Class<?>[] classes) throws InitializationError { return new Suite(new RunnerBuilder() { @Override public Runner runnerForClass(Class<?> testClass) throws Throwable { return getRunner(builder, testClass); } }, classes) { @Override protected String getName() { /* * #1320 The generated suite is not based on a real class so * only a 'null' description can be generated from it. This name * will be overridden here. */ return "classes"; } }; }
[ "public", "Runner", "getSuite", "(", "final", "RunnerBuilder", "builder", ",", "Class", "<", "?", ">", "[", "]", "classes", ")", "throws", "InitializationError", "{", "return", "new", "Suite", "(", "new", "RunnerBuilder", "(", ")", "{", "@", "Override", "public", "Runner", "runnerForClass", "(", "Class", "<", "?", ">", "testClass", ")", "throws", "Throwable", "{", "return", "getRunner", "(", "builder", ",", "testClass", ")", ";", "}", "}", ",", "classes", ")", "{", "@", "Override", "protected", "String", "getName", "(", ")", "{", "/*\n * #1320 The generated suite is not based on a real class so\n * only a 'null' description can be generated from it. This name\n * will be overridden here.\n */", "return", "\"classes\"", ";", "}", "}", ";", "}" ]
Create a suite for {@code classes}, building Runners with {@code builder}. Throws an InitializationError if Runner construction fails
[ "Create", "a", "suite", "for", "{" ]
train
https://github.com/junit-team/junit4/blob/d9861ecdb6e487f6c352437ee823879aca3b81d4/src/main/java/org/junit/runner/Computer.java#L26-L44
Harium/keel
src/main/java/com/harium/keel/catalano/math/function/Gaussian.java
Gaussian.Function2D
public double Function2D(double x, double y) { """ 2-D Gaussian function. @param x value. @param y value. @return Function's value at point (x,y). """ return Math.exp(-(x * x + y * y) / (2 * sqrSigma)) / (2 * Math.PI * sqrSigma); }
java
public double Function2D(double x, double y) { return Math.exp(-(x * x + y * y) / (2 * sqrSigma)) / (2 * Math.PI * sqrSigma); }
[ "public", "double", "Function2D", "(", "double", "x", ",", "double", "y", ")", "{", "return", "Math", ".", "exp", "(", "-", "(", "x", "*", "x", "+", "y", "*", "y", ")", "/", "(", "2", "*", "sqrSigma", ")", ")", "/", "(", "2", "*", "Math", ".", "PI", "*", "sqrSigma", ")", ";", "}" ]
2-D Gaussian function. @param x value. @param y value. @return Function's value at point (x,y).
[ "2", "-", "D", "Gaussian", "function", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/function/Gaussian.java#L91-L93
aol/cyclops
cyclops-futurestream/src/main/java/com/oath/cyclops/types/futurestream/EagerFutureStreamFunctions.java
EagerFutureStreamFunctions.closeOthers
static void closeOthers(final SimpleReactStream active, final List<SimpleReactStream> all) { """ Close all streams except the active one @param active Stream not to close @param all All streams potentially including the active stream """ all.stream() .filter(next -> next != active) .filter(s -> s instanceof BaseSimpleReactStream) .forEach(SimpleReactStream::cancel); }
java
static void closeOthers(final SimpleReactStream active, final List<SimpleReactStream> all) { all.stream() .filter(next -> next != active) .filter(s -> s instanceof BaseSimpleReactStream) .forEach(SimpleReactStream::cancel); }
[ "static", "void", "closeOthers", "(", "final", "SimpleReactStream", "active", ",", "final", "List", "<", "SimpleReactStream", ">", "all", ")", "{", "all", ".", "stream", "(", ")", ".", "filter", "(", "next", "->", "next", "!=", "active", ")", ".", "filter", "(", "s", "->", "s", "instanceof", "BaseSimpleReactStream", ")", ".", "forEach", "(", "SimpleReactStream", "::", "cancel", ")", ";", "}" ]
Close all streams except the active one @param active Stream not to close @param all All streams potentially including the active stream
[ "Close", "all", "streams", "except", "the", "active", "one" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops-futurestream/src/main/java/com/oath/cyclops/types/futurestream/EagerFutureStreamFunctions.java#L37-L43