repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
204
func_name
stringlengths
5
103
whole_func_string
stringlengths
87
3.44k
language
stringclasses
1 value
func_code_string
stringlengths
87
3.44k
func_code_tokens
listlengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
mediathekview/MLib
src/main/java/de/mediathekview/mlib/tool/FilenameUtils.java
FilenameUtils.convertToASCIIEncoding
private static String convertToASCIIEncoding(String fileName, boolean isPath) { String ret = fileName; ret = ret.replace("ä", "ae"); ret = ret.replace("ö", "oe"); ret = ret.replace("ü", "ue"); ret = ret.replace("Ä", "Ae"); ret = ret.replace("Ö", "Oe"); ret = ret.replace("Ü", "Ue"); ret = ret.replace("ß", "ss"); // ein Versuch zu vereinfachen ret = cleanUnicode(ret); ret = removeIllegalCharacters(ret, isPath); //convert our filename to OS encoding... try { final CharsetEncoder charsetEncoder = Charset.forName("US-ASCII").newEncoder(); charsetEncoder.onMalformedInput(CodingErrorAction.REPLACE); // otherwise breaks on first unconvertable char charsetEncoder.onUnmappableCharacter(CodingErrorAction.REPLACE); charsetEncoder.replaceWith(new byte[]{'_'}); final ByteBuffer buf = charsetEncoder.encode(CharBuffer.wrap(ret)); if (buf.hasArray()) { ret = new String(buf.array()); } //remove NUL character from conversion... ret = ret.replaceAll("\\u0000", ""); } catch (CharacterCodingException e) { e.printStackTrace(); } return ret; }
java
private static String convertToASCIIEncoding(String fileName, boolean isPath) { String ret = fileName; ret = ret.replace("ä", "ae"); ret = ret.replace("ö", "oe"); ret = ret.replace("ü", "ue"); ret = ret.replace("Ä", "Ae"); ret = ret.replace("Ö", "Oe"); ret = ret.replace("Ü", "Ue"); ret = ret.replace("ß", "ss"); // ein Versuch zu vereinfachen ret = cleanUnicode(ret); ret = removeIllegalCharacters(ret, isPath); //convert our filename to OS encoding... try { final CharsetEncoder charsetEncoder = Charset.forName("US-ASCII").newEncoder(); charsetEncoder.onMalformedInput(CodingErrorAction.REPLACE); // otherwise breaks on first unconvertable char charsetEncoder.onUnmappableCharacter(CodingErrorAction.REPLACE); charsetEncoder.replaceWith(new byte[]{'_'}); final ByteBuffer buf = charsetEncoder.encode(CharBuffer.wrap(ret)); if (buf.hasArray()) { ret = new String(buf.array()); } //remove NUL character from conversion... ret = ret.replaceAll("\\u0000", ""); } catch (CharacterCodingException e) { e.printStackTrace(); } return ret; }
[ "private", "static", "String", "convertToASCIIEncoding", "(", "String", "fileName", ",", "boolean", "isPath", ")", "{", "String", "ret", "=", "fileName", ";", "ret", "=", "ret", ".", "replace", "(", "\"ä\",", " ", "ae\")", ";", "", "ret", "=", "ret", "."...
Convert a filename from Java´s native UTF-16 to US-ASCII character encoding. @param fileName The UTF-16 filename string. @return US-ASCII encoded string for the OS.
[ "Convert", "a", "filename", "from", "Java´s", "native", "UTF", "-", "16", "to", "US", "-", "ASCII", "character", "encoding", "." ]
train
https://github.com/mediathekview/MLib/blob/01fd5791d87390fea7536275b8a2d4407fc00908/src/main/java/de/mediathekview/mlib/tool/FilenameUtils.java#L156-L191
mgm-tp/jfunk
jfunk-core/src/main/java/com/mgmtp/jfunk/core/mail/MailService.java
MailService.findMessage
public MailMessage findMessage(final MailAccount mailAccount, final Predicate<MailMessage> condition) { return findMessage(mailAccount, condition, defaultTimeoutSeconds); }
java
public MailMessage findMessage(final MailAccount mailAccount, final Predicate<MailMessage> condition) { return findMessage(mailAccount, condition, defaultTimeoutSeconds); }
[ "public", "MailMessage", "findMessage", "(", "final", "MailAccount", "mailAccount", ",", "final", "Predicate", "<", "MailMessage", ">", "condition", ")", "{", "return", "findMessage", "(", "mailAccount", ",", "condition", ",", "defaultTimeoutSeconds", ")", ";", "}...
<p> Tries to find a message for the specified mail account applying the specified {@code condition} until it times out using the default timeout ( {@link EmailConstants#MAIL_TIMEOUT_SECONDS} and {@link EmailConstants#MAIL_SLEEP_MILLIS}). </p> <b>Note:</b><br /> This method uses the specified mail account independently without reservation. If, however, the specified mail account has been reserved by any thread (including the current one), an {@link IllegalStateException} is thrown. </p> @param mailAccount the mail account @param condition the condition a message must meet @return the mail message
[ "<p", ">", "Tries", "to", "find", "a", "message", "for", "the", "specified", "mail", "account", "applying", "the", "specified", "{", "@code", "condition", "}", "until", "it", "times", "out", "using", "the", "default", "timeout", "(", "{", "@link", "EmailCo...
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-core/src/main/java/com/mgmtp/jfunk/core/mail/MailService.java#L100-L102
Netflix/Hystrix
hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesStrategy.java
HystrixPropertiesStrategy.getCommandProperties
public HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, HystrixCommandProperties.Setter builder) { return new HystrixPropertiesCommandDefault(commandKey, builder); }
java
public HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, HystrixCommandProperties.Setter builder) { return new HystrixPropertiesCommandDefault(commandKey, builder); }
[ "public", "HystrixCommandProperties", "getCommandProperties", "(", "HystrixCommandKey", "commandKey", ",", "HystrixCommandProperties", ".", "Setter", "builder", ")", "{", "return", "new", "HystrixPropertiesCommandDefault", "(", "commandKey", ",", "builder", ")", ";", "}" ...
Construct an implementation of {@link HystrixCommandProperties} for {@link HystrixCommand} instances with {@link HystrixCommandKey}. <p> <b>Default Implementation</b> <p> Constructs instance of {@link HystrixPropertiesCommandDefault}. @param commandKey {@link HystrixCommandKey} representing the name or type of {@link HystrixCommand} @param builder {@link com.netflix.hystrix.HystrixCommandProperties.Setter} with default overrides as injected from the {@link HystrixCommand} implementation. <p> The builder will return NULL for each value if no override was provided. @return Implementation of {@link HystrixCommandProperties}
[ "Construct", "an", "implementation", "of", "{", "@link", "HystrixCommandProperties", "}", "for", "{", "@link", "HystrixCommand", "}", "instances", "with", "{", "@link", "HystrixCommandKey", "}", ".", "<p", ">", "<b", ">", "Default", "Implementation<", "/", "b", ...
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesStrategy.java#L53-L55
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java
ElementsExceptionsFactory.newNoSuchFileException
public static NoSuchFileException newNoSuchFileException(String message, Object... args) { return newNoSuchFileException(null, message, args); }
java
public static NoSuchFileException newNoSuchFileException(String message, Object... args) { return newNoSuchFileException(null, message, args); }
[ "public", "static", "NoSuchFileException", "newNoSuchFileException", "(", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "newNoSuchFileException", "(", "null", ",", "message", ",", "args", ")", ";", "}" ]
Constructs and initializes a new {@link NoSuchFileException} with the given {@link String message} formatted with the given {@link Object[] arguments}. @param message {@link String} describing the {@link NoSuchFileException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link NoSuchFileException} with the given {@link String message}. @see #newNoSuchFileException(Throwable, String, Object...) @see org.cp.elements.io.NoSuchFileException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "NoSuchFileException", "}", "with", "the", "given", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", "Object", "[]", "arguments", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L213-L215
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/rest/RESTRegistry.java
RESTRegistry.registerCommand
private void registerCommand(String cmdOwner, RegisteredCommand cmd) { // Add to owner map in RESTCatalog. Map<String, RESTCommand> nameMap = getCmdNameMap(cmdOwner); String cmdName = cmd.getName(); RESTCommand oldCmd = nameMap.put(cmdName, cmd); if (oldCmd != null) { throw new RuntimeException("Duplicate REST command with same owner/name: " + "owner=" + cmdOwner + ", name=" + cmdName + ", [1]=" + cmd + ", [2]=" + oldCmd); } // Add to local evaluation map. Map<HttpMethod, SortedSet<RegisteredCommand>> evalMap = getCmdEvalMap(cmdOwner); for (HttpMethod method : cmd.getMethods()) { SortedSet<RegisteredCommand> methodSet = evalMap.get(method); if (methodSet == null) { methodSet = new TreeSet<>(); evalMap.put(method, methodSet); } if (!methodSet.add(cmd)) { throw new RuntimeException("Duplicate REST command: owner=" + cmdOwner + ", name=" + cmdName + ", commmand=" + cmd); } } }
java
private void registerCommand(String cmdOwner, RegisteredCommand cmd) { // Add to owner map in RESTCatalog. Map<String, RESTCommand> nameMap = getCmdNameMap(cmdOwner); String cmdName = cmd.getName(); RESTCommand oldCmd = nameMap.put(cmdName, cmd); if (oldCmd != null) { throw new RuntimeException("Duplicate REST command with same owner/name: " + "owner=" + cmdOwner + ", name=" + cmdName + ", [1]=" + cmd + ", [2]=" + oldCmd); } // Add to local evaluation map. Map<HttpMethod, SortedSet<RegisteredCommand>> evalMap = getCmdEvalMap(cmdOwner); for (HttpMethod method : cmd.getMethods()) { SortedSet<RegisteredCommand> methodSet = evalMap.get(method); if (methodSet == null) { methodSet = new TreeSet<>(); evalMap.put(method, methodSet); } if (!methodSet.add(cmd)) { throw new RuntimeException("Duplicate REST command: owner=" + cmdOwner + ", name=" + cmdName + ", commmand=" + cmd); } } }
[ "private", "void", "registerCommand", "(", "String", "cmdOwner", ",", "RegisteredCommand", "cmd", ")", "{", "// Add to owner map in RESTCatalog.\r", "Map", "<", "String", ",", "RESTCommand", ">", "nameMap", "=", "getCmdNameMap", "(", "cmdOwner", ")", ";", "String", ...
Register the given command and throw if is a duplicate name or command.
[ "Register", "the", "given", "command", "and", "throw", "if", "is", "a", "duplicate", "name", "or", "command", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/rest/RESTRegistry.java#L220-L245
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfStamperImp.java
PdfStamperImp.setDuration
void setDuration(int seconds, int page) { PdfDictionary pg = reader.getPageN(page); if (seconds < 0) pg.remove(PdfName.DUR); else pg.put(PdfName.DUR, new PdfNumber(seconds)); markUsed(pg); }
java
void setDuration(int seconds, int page) { PdfDictionary pg = reader.getPageN(page); if (seconds < 0) pg.remove(PdfName.DUR); else pg.put(PdfName.DUR, new PdfNumber(seconds)); markUsed(pg); }
[ "void", "setDuration", "(", "int", "seconds", ",", "int", "page", ")", "{", "PdfDictionary", "pg", "=", "reader", ".", "getPageN", "(", "page", ")", ";", "if", "(", "seconds", "<", "0", ")", "pg", ".", "remove", "(", "PdfName", ".", "DUR", ")", ";"...
Sets the display duration for the page (for presentations) @param seconds the number of seconds to display the page. A negative value removes the entry @param page the page where the duration will be applied. The first page is 1
[ "Sets", "the", "display", "duration", "for", "the", "page", "(", "for", "presentations", ")" ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfStamperImp.java#L1418-L1425
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Setter.java
Setter.setTimePicker
public void setTimePicker(final TimePicker timePicker, final int hour, final int minute) { if(timePicker != null){ Activity activity = activityUtils.getCurrentActivity(false); if(activity != null){ activity.runOnUiThread(new Runnable() { public void run() { try{ timePicker.setCurrentHour(hour); timePicker.setCurrentMinute(minute); }catch (Exception ignored){} } }); } } }
java
public void setTimePicker(final TimePicker timePicker, final int hour, final int minute) { if(timePicker != null){ Activity activity = activityUtils.getCurrentActivity(false); if(activity != null){ activity.runOnUiThread(new Runnable() { public void run() { try{ timePicker.setCurrentHour(hour); timePicker.setCurrentMinute(minute); }catch (Exception ignored){} } }); } } }
[ "public", "void", "setTimePicker", "(", "final", "TimePicker", "timePicker", ",", "final", "int", "hour", ",", "final", "int", "minute", ")", "{", "if", "(", "timePicker", "!=", "null", ")", "{", "Activity", "activity", "=", "activityUtils", ".", "getCurrent...
Sets the time in a given {@link TimePicker}. @param timePicker the {@code TimePicker} object. @param hour the hour e.g. 15 @param minute the minute e.g. 30
[ "Sets", "the", "time", "in", "a", "given", "{", "@link", "TimePicker", "}", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Setter.java#L80-L96
Azure/azure-sdk-for-java
containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/OpenShiftManagedClustersInner.java
OpenShiftManagedClustersInner.updateTags
public OpenShiftManagedClusterInner updateTags(String resourceGroupName, String resourceName) { return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().last().body(); }
java
public OpenShiftManagedClusterInner updateTags(String resourceGroupName, String resourceName) { return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().last().body(); }
[ "public", "OpenShiftManagedClusterInner", "updateTags", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "updateTagsWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "toBlocking", "(", ")", ".", "la...
Updates tags on an OpenShift managed cluster. Updates an OpenShift managed cluster with the specified tags. @param resourceGroupName The name of the resource group. @param resourceName The name of the OpenShift managed cluster resource. @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 OpenShiftManagedClusterInner object if successful.
[ "Updates", "tags", "on", "an", "OpenShift", "managed", "cluster", ".", "Updates", "an", "OpenShift", "managed", "cluster", "with", "the", "specified", "tags", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerservice/resource-manager/v2019_02_01/src/main/java/com/microsoft/azure/management/containerservice/v2019_02_01/implementation/OpenShiftManagedClustersInner.java#L619-L621
udoprog/ffwd-client-java
src/main/java/com/google/protobuf250/CodedOutputStream.java
CodedOutputStream.writeSFixed32
public void writeSFixed32(final int fieldNumber, final int value) throws IOException { writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32); writeSFixed32NoTag(value); }
java
public void writeSFixed32(final int fieldNumber, final int value) throws IOException { writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32); writeSFixed32NoTag(value); }
[ "public", "void", "writeSFixed32", "(", "final", "int", "fieldNumber", ",", "final", "int", "value", ")", "throws", "IOException", "{", "writeTag", "(", "fieldNumber", ",", "WireFormat", ".", "WIRETYPE_FIXED32", ")", ";", "writeSFixed32NoTag", "(", "value", ")",...
Write an {@code sfixed32} field, including tag, to the stream.
[ "Write", "an", "{" ]
train
https://github.com/udoprog/ffwd-client-java/blob/b4161d2b138e3edb8fa9420cc3cc653d5764cf5b/src/main/java/com/google/protobuf250/CodedOutputStream.java#L250-L254
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java
NetworkWatchersInner.verifyIPFlow
public VerificationIPFlowResultInner verifyIPFlow(String resourceGroupName, String networkWatcherName, VerificationIPFlowParameters parameters) { return verifyIPFlowWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).toBlocking().last().body(); }
java
public VerificationIPFlowResultInner verifyIPFlow(String resourceGroupName, String networkWatcherName, VerificationIPFlowParameters parameters) { return verifyIPFlowWithServiceResponseAsync(resourceGroupName, networkWatcherName, parameters).toBlocking().last().body(); }
[ "public", "VerificationIPFlowResultInner", "verifyIPFlow", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "VerificationIPFlowParameters", "parameters", ")", "{", "return", "verifyIPFlowWithServiceResponseAsync", "(", "resourceGroupName", ",", "net...
Verify IP flow from the specified VM to a location given the currently configured NSG rules. @param resourceGroupName The name of the resource group. @param networkWatcherName The name of the network watcher. @param parameters Parameters that define the IP flow to be verified. @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 VerificationIPFlowResultInner object if successful.
[ "Verify", "IP", "flow", "from", "the", "specified", "VM", "to", "a", "location", "given", "the", "currently", "configured", "NSG", "rules", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkWatchersInner.java#L958-L960
redkale/redkale
src/org/redkale/asm/MethodVisitor.java
MethodVisitor.visitParameter
public void visitParameter(String name, int access) { if (mv != null) { mv.visitParameter(name, access); } }
java
public void visitParameter(String name, int access) { if (mv != null) { mv.visitParameter(name, access); } }
[ "public", "void", "visitParameter", "(", "String", "name", ",", "int", "access", ")", "{", "if", "(", "mv", "!=", "null", ")", "{", "mv", ".", "visitParameter", "(", "name", ",", "access", ")", ";", "}", "}" ]
Visits a parameter of this method. @param name parameter name or null if none is provided. @param access the parameter's access flags, only <tt>ACC_FINAL</tt>, <tt>ACC_SYNTHETIC</tt> or/and <tt>ACC_MANDATED</tt> are allowed (see {@link Opcodes}).
[ "Visits", "a", "parameter", "of", "this", "method", "." ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/asm/MethodVisitor.java#L139-L143
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/GrahamScanConvexHull2D.java
GrahamScanConvexHull2D.mdist
private double mdist(double[] a, double[] b) { return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); }
java
private double mdist(double[] a, double[] b) { return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); }
[ "private", "double", "mdist", "(", "double", "[", "]", "a", ",", "double", "[", "]", "b", ")", "{", "return", "Math", ".", "abs", "(", "a", "[", "0", "]", "-", "b", "[", "0", "]", ")", "+", "Math", ".", "abs", "(", "a", "[", "1", "]", "-"...
Manhattan distance. @param a double[] A @param b double[] B @return Manhattan distance
[ "Manhattan", "distance", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/GrahamScanConvexHull2D.java#L211-L213
vlingo/vlingo-actors
src/main/java/io/vlingo/actors/World.java
World.actorFor
public Protocols actorFor(final Class<?>[] protocols, final Definition definition) { if (isTerminated()) { throw new IllegalStateException("vlingo/actors: Stopped."); } return stage().actorFor(protocols, definition); }
java
public Protocols actorFor(final Class<?>[] protocols, final Definition definition) { if (isTerminated()) { throw new IllegalStateException("vlingo/actors: Stopped."); } return stage().actorFor(protocols, definition); }
[ "public", "Protocols", "actorFor", "(", "final", "Class", "<", "?", ">", "[", "]", "protocols", ",", "final", "Definition", "definition", ")", "{", "if", "(", "isTerminated", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"vlingo/actors:...
Answers a {@code Protocols} that provides one or more supported protocols for the newly created {@code Actor} according to {@code definition}. @param protocols the {@code Class<?>[]} array of protocols that the {@code Actor} supports @param definition the {@code Definition} providing parameters to the {@code Actor} @return {@code Protocols}
[ "Answers", "a", "{" ]
train
https://github.com/vlingo/vlingo-actors/blob/c7d046fd139c0490cf0fd2588d7dc2f792f13493/src/main/java/io/vlingo/actors/World.java#L151-L157
Squarespace/cldr
core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java
UnitFactorMap.resolve
protected UnitFactor resolve(Unit from, Unit to) { if (from == to) { return new UnitFactor(Rational.ONE, to); } List<UnitFactor> path = getPath(from, to); if (path.isEmpty()) { throw new IllegalStateException("Can't find a path to convert " + from + " units into " + to); } UnitFactor factor = path.get(0); int size = path.size(); for (int i = 1; i < size; i++) { factor = factor.multiply(path.get(i)); } return factor; }
java
protected UnitFactor resolve(Unit from, Unit to) { if (from == to) { return new UnitFactor(Rational.ONE, to); } List<UnitFactor> path = getPath(from, to); if (path.isEmpty()) { throw new IllegalStateException("Can't find a path to convert " + from + " units into " + to); } UnitFactor factor = path.get(0); int size = path.size(); for (int i = 1; i < size; i++) { factor = factor.multiply(path.get(i)); } return factor; }
[ "protected", "UnitFactor", "resolve", "(", "Unit", "from", ",", "Unit", "to", ")", "{", "if", "(", "from", "==", "to", ")", "{", "return", "new", "UnitFactor", "(", "Rational", ".", "ONE", ",", "to", ")", ";", "}", "List", "<", "UnitFactor", ">", "...
Find the best conversion factor path between the FROM and TO units, multiply them together and return the resulting factor.
[ "Find", "the", "best", "conversion", "factor", "path", "between", "the", "FROM", "and", "TO", "units", "multiply", "them", "together", "and", "return", "the", "resulting", "factor", "." ]
train
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/core/src/main/java/com/squarespace/cldr/units/UnitFactorMap.java#L201-L216
cdk/cdk
legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java
CDKMCS.isIsomorph
public static boolean isIsomorph(IAtomContainer sourceGraph, IAtomContainer targetGraph, boolean shouldMatchBonds) throws CDKException { if (sourceGraph instanceof IQueryAtomContainer) { throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); } if (targetGraph.getAtomCount() != sourceGraph.getAtomCount()) { return false; } // check single atom case if (targetGraph.getAtomCount() == 1) { IAtom atom = sourceGraph.getAtom(0); IAtom atom2 = targetGraph.getAtom(0); if (atom instanceof IQueryAtom) { IQueryAtom qAtom = (IQueryAtom) atom; return qAtom.matches(targetGraph.getAtom(0)); } else if (atom2 instanceof IQueryAtom) { IQueryAtom qAtom = (IQueryAtom) atom2; return qAtom.matches(sourceGraph.getAtom(0)); } else { String atomSymbol = atom2.getSymbol(); return sourceGraph.getAtom(0).getSymbol().equals(atomSymbol); } } return (getIsomorphMap(sourceGraph, targetGraph, shouldMatchBonds) != null); }
java
public static boolean isIsomorph(IAtomContainer sourceGraph, IAtomContainer targetGraph, boolean shouldMatchBonds) throws CDKException { if (sourceGraph instanceof IQueryAtomContainer) { throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); } if (targetGraph.getAtomCount() != sourceGraph.getAtomCount()) { return false; } // check single atom case if (targetGraph.getAtomCount() == 1) { IAtom atom = sourceGraph.getAtom(0); IAtom atom2 = targetGraph.getAtom(0); if (atom instanceof IQueryAtom) { IQueryAtom qAtom = (IQueryAtom) atom; return qAtom.matches(targetGraph.getAtom(0)); } else if (atom2 instanceof IQueryAtom) { IQueryAtom qAtom = (IQueryAtom) atom2; return qAtom.matches(sourceGraph.getAtom(0)); } else { String atomSymbol = atom2.getSymbol(); return sourceGraph.getAtom(0).getSymbol().equals(atomSymbol); } } return (getIsomorphMap(sourceGraph, targetGraph, shouldMatchBonds) != null); }
[ "public", "static", "boolean", "isIsomorph", "(", "IAtomContainer", "sourceGraph", ",", "IAtomContainer", "targetGraph", ",", "boolean", "shouldMatchBonds", ")", "throws", "CDKException", "{", "if", "(", "sourceGraph", "instanceof", "IQueryAtomContainer", ")", "{", "t...
Tests if sourceGraph and targetGraph are isomorph. @param sourceGraph first molecule. Must not be an IQueryAtomContainer. @param targetGraph second molecule. May be an IQueryAtomContainer. @param shouldMatchBonds @return true if the 2 molecule are isomorph @throws org.openscience.cdk.exception.CDKException if the first molecule is an instance of IQueryAtomContainer
[ "Tests", "if", "sourceGraph", "and", "targetGraph", "are", "isomorph", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/smsd/algorithm/rgraph/CDKMCS.java#L156-L181
cdk/cdk
base/data/src/main/java/org/openscience/cdk/Reaction.java
Reaction.addReactant
@Override public void addReactant(IAtomContainer reactant, Double coefficient) { reactants.addAtomContainer(reactant, coefficient); notifyChanged(); }
java
@Override public void addReactant(IAtomContainer reactant, Double coefficient) { reactants.addAtomContainer(reactant, coefficient); notifyChanged(); }
[ "@", "Override", "public", "void", "addReactant", "(", "IAtomContainer", "reactant", ",", "Double", "coefficient", ")", "{", "reactants", ".", "addAtomContainer", "(", "reactant", ",", "coefficient", ")", ";", "notifyChanged", "(", ")", ";", "}" ]
Adds a reactant to this reaction with a stoichiometry coefficient. @param reactant Molecule added as reactant to this reaction @param coefficient Stoichiometry coefficient for this molecule @see #getReactants
[ "Adds", "a", "reactant", "to", "this", "reaction", "with", "a", "stoichiometry", "coefficient", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/data/src/main/java/org/openscience/cdk/Reaction.java#L244-L248
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF3.java
CommonOps_DDF3.add
public static void add( DMatrix3 a , DMatrix3 b , DMatrix3 c ) { c.a1 = a.a1 + b.a1; c.a2 = a.a2 + b.a2; c.a3 = a.a3 + b.a3; }
java
public static void add( DMatrix3 a , DMatrix3 b , DMatrix3 c ) { c.a1 = a.a1 + b.a1; c.a2 = a.a2 + b.a2; c.a3 = a.a3 + b.a3; }
[ "public", "static", "void", "add", "(", "DMatrix3", "a", ",", "DMatrix3", "b", ",", "DMatrix3", "c", ")", "{", "c", ".", "a1", "=", "a", ".", "a1", "+", "b", ".", "a1", ";", "c", ".", "a2", "=", "a", ".", "a2", "+", "b", ".", "a2", ";", "...
<p>Performs the following operation:<br> <br> c = a + b <br> c<sub>i</sub> = a<sub>i</sub> + b<sub>i</sub> <br> </p> <p> Vector C can be the same instance as Vector A and/or B. </p> @param a A Vector. Not modified. @param b A Vector. Not modified. @param c A Vector where the results are stored. Modified.
[ "<p", ">", "Performs", "the", "following", "operation", ":", "<br", ">", "<br", ">", "c", "=", "a", "+", "b", "<br", ">", "c<sub", ">", "i<", "/", "sub", ">", "=", "a<sub", ">", "i<", "/", "sub", ">", "+", "b<sub", ">", "i<", "/", "sub", ">",...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/fixed/CommonOps_DDF3.java#L74-L78
m-m-m/util
date/src/main/java/net/sf/mmm/util/date/base/Iso8601UtilLimitedImpl.java
Iso8601UtilLimitedImpl.formatDate
public void formatDate(int year, int month, int day, boolean extended, Appendable buffer) { try { // year String yearString = String.valueOf(year); buffer.append(yearString); if (extended) { buffer.append('-'); } // month String monthString = String.valueOf(month); if (monthString.length() < 2) { buffer.append('0'); } buffer.append(monthString); if (extended) { buffer.append('-'); } // day String dayString = String.valueOf(day); if (dayString.length() < 2) { buffer.append('0'); } buffer.append(dayString); } catch (IOException e) { throw new IllegalStateException(e); } }
java
public void formatDate(int year, int month, int day, boolean extended, Appendable buffer) { try { // year String yearString = String.valueOf(year); buffer.append(yearString); if (extended) { buffer.append('-'); } // month String monthString = String.valueOf(month); if (monthString.length() < 2) { buffer.append('0'); } buffer.append(monthString); if (extended) { buffer.append('-'); } // day String dayString = String.valueOf(day); if (dayString.length() < 2) { buffer.append('0'); } buffer.append(dayString); } catch (IOException e) { throw new IllegalStateException(e); } }
[ "public", "void", "formatDate", "(", "int", "year", ",", "int", "month", ",", "int", "day", ",", "boolean", "extended", ",", "Appendable", "buffer", ")", "{", "try", "{", "// year", "String", "yearString", "=", "String", ".", "valueOf", "(", "year", ")",...
@see #formatDate(Date, boolean, Appendable) @param year is the {@link java.util.Calendar#YEAR year} @param month is the month (1-12). @param day is the {@link java.util.Calendar#DAY_OF_MONTH day}. @param extended if {@code false} the basic date format ("yyyyMMdd") is used, if {@code true} the extended date format ("yyyy-MM-dd") is used. @param buffer is where to append the formatted date.
[ "@see", "#formatDate", "(", "Date", "boolean", "Appendable", ")" ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/date/src/main/java/net/sf/mmm/util/date/base/Iso8601UtilLimitedImpl.java#L96-L123
json-path/JsonPath
json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java
Utils.join
public static String join(String delimiter, String wrap, Iterable<?> objs) { Iterator<?> iter = objs.iterator(); if (!iter.hasNext()) { return ""; } StringBuilder buffer = new StringBuilder(); buffer.append(wrap).append(iter.next()).append(wrap); while (iter.hasNext()) { buffer.append(delimiter).append(wrap).append(iter.next()).append(wrap); } return buffer.toString(); }
java
public static String join(String delimiter, String wrap, Iterable<?> objs) { Iterator<?> iter = objs.iterator(); if (!iter.hasNext()) { return ""; } StringBuilder buffer = new StringBuilder(); buffer.append(wrap).append(iter.next()).append(wrap); while (iter.hasNext()) { buffer.append(delimiter).append(wrap).append(iter.next()).append(wrap); } return buffer.toString(); }
[ "public", "static", "String", "join", "(", "String", "delimiter", ",", "String", "wrap", ",", "Iterable", "<", "?", ">", "objs", ")", "{", "Iterator", "<", "?", ">", "iter", "=", "objs", ".", "iterator", "(", ")", ";", "if", "(", "!", "iter", ".", ...
accept a collection of objects, since all objects have toString()
[ "accept", "a", "collection", "of", "objects", "since", "all", "objects", "have", "toString", "()" ]
train
https://github.com/json-path/JsonPath/blob/5a09489c3252b74bbf81992aadb3073be59c04f9/json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java#L27-L38
baasbox/Android-SDK
library/src/main/java/com/baasbox/android/BaasUser.java
BaasUser.logoutSync
public BaasResult<Void> logoutSync(String registration) { BaasBox box = BaasBox.getDefaultChecked(); LogoutRequest request = new LogoutRequest(box, this, registration, RequestOptions.DEFAULT, null); return box.submitSync(request); }
java
public BaasResult<Void> logoutSync(String registration) { BaasBox box = BaasBox.getDefaultChecked(); LogoutRequest request = new LogoutRequest(box, this, registration, RequestOptions.DEFAULT, null); return box.submitSync(request); }
[ "public", "BaasResult", "<", "Void", ">", "logoutSync", "(", "String", "registration", ")", "{", "BaasBox", "box", "=", "BaasBox", ".", "getDefaultChecked", "(", ")", ";", "LogoutRequest", "request", "=", "new", "LogoutRequest", "(", "box", ",", "this", ",",...
Synchronously logouts current user from the server. @param registration a registration id to remove @return the result of the request
[ "Synchronously", "logouts", "current", "user", "from", "the", "server", "." ]
train
https://github.com/baasbox/Android-SDK/blob/6bb2203246b885b2ad63a7bfaf37c83caf15e0d8/library/src/main/java/com/baasbox/android/BaasUser.java#L881-L885
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/modules/r/interpolation2d/core/TPSInterpolator.java
TPSInterpolator.fillOsubMatrix
private void fillOsubMatrix( Coordinate[] controlPoints, GeneralMatrix L ) { int controlPointsNum = controlPoints.length; for( int i = controlPointsNum; i < (controlPointsNum + 3); i++ ) { for( int j = controlPointsNum; j < (controlPointsNum + 3); j++ ) { L.setElement(i, j, 0); } } }
java
private void fillOsubMatrix( Coordinate[] controlPoints, GeneralMatrix L ) { int controlPointsNum = controlPoints.length; for( int i = controlPointsNum; i < (controlPointsNum + 3); i++ ) { for( int j = controlPointsNum; j < (controlPointsNum + 3); j++ ) { L.setElement(i, j, 0); } } }
[ "private", "void", "fillOsubMatrix", "(", "Coordinate", "[", "]", "controlPoints", ",", "GeneralMatrix", "L", ")", "{", "int", "controlPointsNum", "=", "controlPoints", ".", "length", ";", "for", "(", "int", "i", "=", "controlPointsNum", ";", "i", "<", "(", ...
Fill O submatrix (<a href="http://elonen.iki.fi/code/tpsdemo/index.html"> see more here</a>)
[ "Fill", "O", "submatrix", "(", "<a", "href", "=", "http", ":", "//", "elonen", ".", "iki", ".", "fi", "/", "code", "/", "tpsdemo", "/", "index", ".", "html", ">", "see", "more", "here<", "/", "a", ">", ")" ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/modules/r/interpolation2d/core/TPSInterpolator.java#L155-L162
enioka/jqm
jqm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/JqmEngineFactory.java
JqmEngineFactory.startEngine
public static JqmEngineOperations startEngine(String name, JqmEngineHandler handler) { JqmEngine e = new JqmEngine(); e.start(name, handler); return e; }
java
public static JqmEngineOperations startEngine(String name, JqmEngineHandler handler) { JqmEngine e = new JqmEngine(); e.start(name, handler); return e; }
[ "public", "static", "JqmEngineOperations", "startEngine", "(", "String", "name", ",", "JqmEngineHandler", "handler", ")", "{", "JqmEngine", "e", "=", "new", "JqmEngine", "(", ")", ";", "e", ".", "start", "(", "name", ",", "handler", ")", ";", "return", "e"...
Creates and start an engine representing the node named as the given parameter. @param name name of the node, as present in the configuration (case sensitive) @param handler can be null. A set of callbacks hooked on different engine life cycle events. @return an object allowing to stop the engine.
[ "Creates", "and", "start", "an", "engine", "representing", "the", "node", "named", "as", "the", "given", "parameter", "." ]
train
https://github.com/enioka/jqm/blob/391733b8e291404b97c714c3727a241c4a861f98/jqm-all/jqm-engine/src/main/java/com/enioka/jqm/tools/JqmEngineFactory.java#L23-L28
line/armeria
core/src/main/java/com/linecorp/armeria/server/cors/CorsServiceBuilder.java
CorsServiceBuilder.preflightResponseHeader
public CorsServiceBuilder preflightResponseHeader(CharSequence name, Object... values) { firstPolicyBuilder.preflightResponseHeader(name, values); return this; }
java
public CorsServiceBuilder preflightResponseHeader(CharSequence name, Object... values) { firstPolicyBuilder.preflightResponseHeader(name, values); return this; }
[ "public", "CorsServiceBuilder", "preflightResponseHeader", "(", "CharSequence", "name", ",", "Object", "...", "values", ")", "{", "firstPolicyBuilder", ".", "preflightResponseHeader", "(", "name", ",", "values", ")", ";", "return", "this", ";", "}" ]
Returns HTTP response headers that should be added to a CORS preflight response. <p>An intermediary like a load balancer might require that a CORS preflight request have certain headers set. This enables such headers to be added. @param name the name of the HTTP header. @param values the values for the HTTP header. @return {@link CorsServiceBuilder} to support method chaining.
[ "Returns", "HTTP", "response", "headers", "that", "should", "be", "added", "to", "a", "CORS", "preflight", "response", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/server/cors/CorsServiceBuilder.java#L301-L304
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/br_broker/br_broker.java
br_broker.update
public static br_broker update(nitro_service client, br_broker resource) throws Exception { resource.validate("modify"); return ((br_broker[]) resource.update_resource(client))[0]; }
java
public static br_broker update(nitro_service client, br_broker resource) throws Exception { resource.validate("modify"); return ((br_broker[]) resource.update_resource(client))[0]; }
[ "public", "static", "br_broker", "update", "(", "nitro_service", "client", ",", "br_broker", "resource", ")", "throws", "Exception", "{", "resource", ".", "validate", "(", "\"modify\"", ")", ";", "return", "(", "(", "br_broker", "[", "]", ")", "resource", "....
<pre> Use this operation to modify Unified Repeater Instance. </pre>
[ "<pre", ">", "Use", "this", "operation", "to", "modify", "Unified", "Repeater", "Instance", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/br_broker/br_broker.java#L497-L501
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java
AbstractSecureRedirectStrategy.makeSecure
@Override public void makeSecure(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", secureUrl(request, response)); response.getOutputStream().flush(); response.getOutputStream().close(); }
java
@Override public void makeSecure(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", secureUrl(request, response)); response.getOutputStream().flush(); response.getOutputStream().close(); }
[ "@", "Override", "public", "void", "makeSecure", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "IOException", "{", "response", ".", "setStatus", "(", "HttpServletResponse", ".", "SC_MOVED_PERMANENTLY", ")", ";", "response...
Sends a moved perminately redirect to the secure form of the request URL. @request the request to make secure. @response the response for the request.
[ "Sends", "a", "moved", "perminately", "redirect", "to", "the", "secure", "form", "of", "the", "request", "URL", "." ]
train
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java#L154-L162
querydsl/querydsl
querydsl-core/src/main/java/com/querydsl/core/types/dsl/SimpleExpression.java
SimpleExpression.notIn
public final BooleanExpression notIn(CollectionExpression<?,? extends T> right) { return Expressions.booleanOperation(Ops.NOT_IN, mixin, right); }
java
public final BooleanExpression notIn(CollectionExpression<?,? extends T> right) { return Expressions.booleanOperation(Ops.NOT_IN, mixin, right); }
[ "public", "final", "BooleanExpression", "notIn", "(", "CollectionExpression", "<", "?", ",", "?", "extends", "T", ">", "right", ")", "{", "return", "Expressions", ".", "booleanOperation", "(", "Ops", ".", "NOT_IN", ",", "mixin", ",", "right", ")", ";", "}"...
Create a {@code this not in right} expression @param right rhs of the comparison @return this not in right
[ "Create", "a", "{", "@code", "this", "not", "in", "right", "}", "expression" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-core/src/main/java/com/querydsl/core/types/dsl/SimpleExpression.java#L320-L322
xvik/dropwizard-guicey
src/main/java/ru/vyarus/dropwizard/guice/module/context/option/mapper/OptionParser.java
OptionParser.parseValue
@SuppressWarnings("unchecked") public static <V, T extends Enum & Option> V parseValue(final T option, final String value) { Preconditions.checkState(StringUtils.isNotBlank(value), "Empty value is not allowed for option %s", option); try { return (V) StringConverter.convert(option.getType(), value); } catch (Exception ex) { throw new IllegalStateException(String.format("Failed to convert '%s' value for option %s.%s", value, option.getDeclaringClass().getSimpleName(), option), ex); } }
java
@SuppressWarnings("unchecked") public static <V, T extends Enum & Option> V parseValue(final T option, final String value) { Preconditions.checkState(StringUtils.isNotBlank(value), "Empty value is not allowed for option %s", option); try { return (V) StringConverter.convert(option.getType(), value); } catch (Exception ex) { throw new IllegalStateException(String.format("Failed to convert '%s' value for option %s.%s", value, option.getDeclaringClass().getSimpleName(), option), ex); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "V", ",", "T", "extends", "Enum", "&", "Option", ">", "V", "parseValue", "(", "final", "T", "option", ",", "final", "String", "value", ")", "{", "Preconditions", ".", "checkState"...
Parse option value from string. Only basic conversions are supported: like string, boolean, integer, double, enum value, enum by class and arrays of these types (see {@link StringConverter}). @param option option enum @param value string value @param <V> option value type @param <T> option type @return parsed option value
[ "Parse", "option", "value", "from", "string", ".", "Only", "basic", "conversions", "are", "supported", ":", "like", "string", "boolean", "integer", "double", "enum", "value", "enum", "by", "class", "and", "arrays", "of", "these", "types", "(", "see", "{", ...
train
https://github.com/xvik/dropwizard-guicey/blob/dd39ad77283555be21f606d5ebf0f11207a733d4/src/main/java/ru/vyarus/dropwizard/guice/module/context/option/mapper/OptionParser.java#L45-L55
xm-online/xm-commons
xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/service/PermissionCheckService.java
PermissionCheckService.createCondition
public String createCondition(Authentication authentication, Object privilegeKey, SpelTranslator translator) { if (!hasPermission(authentication, privilegeKey)) { throw new AccessDeniedException("Access is denied"); } String roleKey = getRoleKey(authentication); Permission permission = getPermission(roleKey, privilegeKey); Subject subject = getSubject(roleKey); if (!RoleConstant.SUPER_ADMIN.equals(roleKey) && permission != null && permission.getResourceCondition() != null) { return translator.translate(permission.getResourceCondition().getExpressionString(), subject); } return null; }
java
public String createCondition(Authentication authentication, Object privilegeKey, SpelTranslator translator) { if (!hasPermission(authentication, privilegeKey)) { throw new AccessDeniedException("Access is denied"); } String roleKey = getRoleKey(authentication); Permission permission = getPermission(roleKey, privilegeKey); Subject subject = getSubject(roleKey); if (!RoleConstant.SUPER_ADMIN.equals(roleKey) && permission != null && permission.getResourceCondition() != null) { return translator.translate(permission.getResourceCondition().getExpressionString(), subject); } return null; }
[ "public", "String", "createCondition", "(", "Authentication", "authentication", ",", "Object", "privilegeKey", ",", "SpelTranslator", "translator", ")", "{", "if", "(", "!", "hasPermission", "(", "authentication", ",", "privilegeKey", ")", ")", "{", "throw", "new"...
Create condition with replaced subject variables. <p>SpEL condition translated to SQL condition with replacing #returnObject to returnObject and enriching #subject.* from Subject object (see {@link Subject}). <p>As an option, SpEL could be translated to SQL via {@link SpelExpression} method {@code getAST()} with traversing through {@link SpelNode} nodes and building SQL expression. @param authentication the authentication @param privilegeKey the privilege key @param translator the spel translator @return condition if permitted, or null
[ "Create", "condition", "with", "replaced", "subject", "variables", "." ]
train
https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-permission/src/main/java/com/icthh/xm/commons/permission/service/PermissionCheckService.java#L118-L134
pressgang-ccms/PressGangCCMSContentSpecProcessor
src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecParser.java
ContentSpecParser.isSpecTopicMetaData
private boolean isSpecTopicMetaData(final String key, final String value) { if (ContentSpecUtilities.isSpecTopicMetaData(key)) { // Abstracts can be plain text so check an opening bracket exists if (key.equalsIgnoreCase(CommonConstants.CS_ABSTRACT_TITLE) || key.equalsIgnoreCase( CommonConstants.CS_ABSTRACT_ALTERNATE_TITLE)) { final String fixedValue = value.trim().replaceAll("(?i)^" + key + "\\s*", ""); return fixedValue.trim().startsWith("["); } else { return true; } } else { return false; } }
java
private boolean isSpecTopicMetaData(final String key, final String value) { if (ContentSpecUtilities.isSpecTopicMetaData(key)) { // Abstracts can be plain text so check an opening bracket exists if (key.equalsIgnoreCase(CommonConstants.CS_ABSTRACT_TITLE) || key.equalsIgnoreCase( CommonConstants.CS_ABSTRACT_ALTERNATE_TITLE)) { final String fixedValue = value.trim().replaceAll("(?i)^" + key + "\\s*", ""); return fixedValue.trim().startsWith("["); } else { return true; } } else { return false; } }
[ "private", "boolean", "isSpecTopicMetaData", "(", "final", "String", "key", ",", "final", "String", "value", ")", "{", "if", "(", "ContentSpecUtilities", ".", "isSpecTopicMetaData", "(", "key", ")", ")", "{", "// Abstracts can be plain text so check an opening bracket e...
Checks if a metadata line is a spec topic. @param key The metadata key. @param value The metadata value. @return True if the line is a spec topic metadata element, otherwise false.
[ "Checks", "if", "a", "metadata", "line", "is", "a", "spec", "topic", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecParser.java#L759-L772
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java
SVGPath.relativeEllipticalArc
public SVGPath relativeEllipticalArc(double rx, double ry, double ar, double la, double sp, double[] xy) { return append(PATH_ARC_RELATIVE).append(rx).append(ry).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]); }
java
public SVGPath relativeEllipticalArc(double rx, double ry, double ar, double la, double sp, double[] xy) { return append(PATH_ARC_RELATIVE).append(rx).append(ry).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]); }
[ "public", "SVGPath", "relativeEllipticalArc", "(", "double", "rx", ",", "double", "ry", ",", "double", "ar", ",", "double", "la", ",", "double", "sp", ",", "double", "[", "]", "xy", ")", "{", "return", "append", "(", "PATH_ARC_RELATIVE", ")", ".", "appen...
Elliptical arc curve to the given relative coordinates. @param rx x radius @param ry y radius @param ar x-axis-rotation @param la large arc flag, if angle &gt;= 180 deg @param sp sweep flag, if arc will be drawn in positive-angle direction @param xy new coordinates
[ "Elliptical", "arc", "curve", "to", "the", "given", "relative", "coordinates", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGPath.java#L605-L607
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Locale.java
Locale.createConstant
private static Locale createConstant(String lang, String country) { BaseLocale base = BaseLocale.createInstance(lang, country); return getInstance(base, null); }
java
private static Locale createConstant(String lang, String country) { BaseLocale base = BaseLocale.createInstance(lang, country); return getInstance(base, null); }
[ "private", "static", "Locale", "createConstant", "(", "String", "lang", ",", "String", "country", ")", "{", "BaseLocale", "base", "=", "BaseLocale", ".", "createInstance", "(", "lang", ",", "country", ")", ";", "return", "getInstance", "(", "base", ",", "nul...
This method must be called only for creating the Locale.* constants due to making shortcuts.
[ "This", "method", "must", "be", "called", "only", "for", "creating", "the", "Locale", ".", "*", "constants", "due", "to", "making", "shortcuts", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Locale.java#L709-L712
Azure/azure-sdk-for-java
labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/LabAccountsInner.java
LabAccountsInner.createLab
public void createLab(String resourceGroupName, String labAccountName, CreateLabProperties createLabProperties) { createLabWithServiceResponseAsync(resourceGroupName, labAccountName, createLabProperties).toBlocking().single().body(); }
java
public void createLab(String resourceGroupName, String labAccountName, CreateLabProperties createLabProperties) { createLabWithServiceResponseAsync(resourceGroupName, labAccountName, createLabProperties).toBlocking().single().body(); }
[ "public", "void", "createLab", "(", "String", "resourceGroupName", ",", "String", "labAccountName", ",", "CreateLabProperties", "createLabProperties", ")", "{", "createLabWithServiceResponseAsync", "(", "resourceGroupName", ",", "labAccountName", ",", "createLabProperties", ...
Create a lab in a lab account. @param resourceGroupName The name of the resource group. @param labAccountName The name of the lab Account. @param createLabProperties Properties for creating a managed lab and a default environment setting @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
[ "Create", "a", "lab", "in", "a", "lab", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/LabAccountsInner.java#L1118-L1120
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/component/selectOneMenu/SelectOneMenuRenderer.java
SelectOneMenuRenderer.renderSelectTag
protected void renderSelectTag(ResponseWriter rw, SelectOneMenu menu) throws IOException { rw.write("\n"); rw.startElement("select", menu); }
java
protected void renderSelectTag(ResponseWriter rw, SelectOneMenu menu) throws IOException { rw.write("\n"); rw.startElement("select", menu); }
[ "protected", "void", "renderSelectTag", "(", "ResponseWriter", "rw", ",", "SelectOneMenu", "menu", ")", "throws", "IOException", "{", "rw", ".", "write", "(", "\"\\n\"", ")", ";", "rw", ".", "startElement", "(", "\"select\"", ",", "menu", ")", ";", "}" ]
Renders the start of the input tag. This method is protected in order to allow third-party frameworks to derive from it. @param rw the response writer @throws IOException may be thrown by the response writer
[ "Renders", "the", "start", "of", "the", "input", "tag", ".", "This", "method", "is", "protected", "in", "order", "to", "allow", "third", "-", "party", "frameworks", "to", "derive", "from", "it", "." ]
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/selectOneMenu/SelectOneMenuRenderer.java#L529-L532
airlift/slice
src/main/java/io/airlift/slice/Slices.java
Slices.wrappedBuffer
public static Slice wrappedBuffer(byte[] array, int offset, int length) { if (length == 0) { return EMPTY_SLICE; } return new Slice(array, offset, length); }
java
public static Slice wrappedBuffer(byte[] array, int offset, int length) { if (length == 0) { return EMPTY_SLICE; } return new Slice(array, offset, length); }
[ "public", "static", "Slice", "wrappedBuffer", "(", "byte", "[", "]", "array", ",", "int", "offset", ",", "int", "length", ")", "{", "if", "(", "length", "==", "0", ")", "{", "return", "EMPTY_SLICE", ";", "}", "return", "new", "Slice", "(", "array", "...
Creates a slice over the specified array range. @param offset the array position at which the slice begins @param length the number of array positions to include in the slice
[ "Creates", "a", "slice", "over", "the", "specified", "array", "range", "." ]
train
https://github.com/airlift/slice/blob/7166cb0319e3655f8ba15f5a7ccf3d2f721c1242/src/main/java/io/airlift/slice/Slices.java#L149-L155
geomajas/geomajas-project-server
plugin/staticsecurity/staticsecurity/src/main/java/org/geomajas/plugin/staticsecurity/security/AuthenticationTokenService.java
AuthenticationTokenService.invalidateOldTokens
@Scheduled(fixedRate = 60000) // run every minute public void invalidateOldTokens() { List<String> invalidTokens = new ArrayList<String>(); // tokens to invalidate for (Map.Entry<String, TokenContainer> entry : tokens.entrySet()) { if (!entry.getValue().isValid()) { invalidTokens.add(entry.getKey()); } } for (String token : invalidTokens) { logout(token); } }
java
@Scheduled(fixedRate = 60000) // run every minute public void invalidateOldTokens() { List<String> invalidTokens = new ArrayList<String>(); // tokens to invalidate for (Map.Entry<String, TokenContainer> entry : tokens.entrySet()) { if (!entry.getValue().isValid()) { invalidTokens.add(entry.getKey()); } } for (String token : invalidTokens) { logout(token); } }
[ "@", "Scheduled", "(", "fixedRate", "=", "60000", ")", "// run every minute", "public", "void", "invalidateOldTokens", "(", ")", "{", "List", "<", "String", ">", "invalidTokens", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "// tokens to invalid...
Invalidate tokens which have passed their lifetime. Note that tokens are also checked when the authentication is fetched in {@link #getAuthentication(String)}.
[ "Invalidate", "tokens", "which", "have", "passed", "their", "lifetime", ".", "Note", "that", "tokens", "are", "also", "checked", "when", "the", "authentication", "is", "fetched", "in", "{" ]
train
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/plugin/staticsecurity/staticsecurity/src/main/java/org/geomajas/plugin/staticsecurity/security/AuthenticationTokenService.java#L106-L117
alkacon/opencms-core
src/org/opencms/file/types/A_CmsResourceType.java
A_CmsResourceType.replaceResource
@Deprecated public void replaceResource( CmsObject cms, CmsSecurityManager securityManager, CmsResource resource, int type, byte[] content, List<CmsProperty> properties) throws CmsException { securityManager.replaceResource(cms.getRequestContext(), resource, type, content, properties); // type may have changed from non link parseable to link parseable createRelations(cms, securityManager, resource.getRootPath()); }
java
@Deprecated public void replaceResource( CmsObject cms, CmsSecurityManager securityManager, CmsResource resource, int type, byte[] content, List<CmsProperty> properties) throws CmsException { securityManager.replaceResource(cms.getRequestContext(), resource, type, content, properties); // type may have changed from non link parseable to link parseable createRelations(cms, securityManager, resource.getRootPath()); }
[ "@", "Deprecated", "public", "void", "replaceResource", "(", "CmsObject", "cms", ",", "CmsSecurityManager", "securityManager", ",", "CmsResource", "resource", ",", "int", "type", ",", "byte", "[", "]", "content", ",", "List", "<", "CmsProperty", ">", "properties...
@see org.opencms.file.types.I_CmsResourceType#replaceResource(org.opencms.file.CmsObject, CmsSecurityManager, CmsResource, int, byte[], List) @deprecated Use {@link #replaceResource(CmsObject, CmsSecurityManager, CmsResource, I_CmsResourceType, byte[], List)} instead. Resource types should always be referenced either by its type class (preferred) or by type name. Use of int based resource type references will be discontinued in a future OpenCms release.
[ "@see", "org", ".", "opencms", ".", "file", ".", "types", ".", "I_CmsResourceType#replaceResource", "(", "org", ".", "opencms", ".", "file", ".", "CmsObject", "CmsSecurityManager", "CmsResource", "int", "byte", "[]", "List", ")" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/types/A_CmsResourceType.java#L822-L835
voldemort/voldemort
src/java/voldemort/store/stats/ClientSocketStats.java
ClientSocketStats.recordResourceRequestQueueLength
public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) { if(dest != null) { getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength); recordResourceRequestQueueLength(null, queueLength); } else { this.resourceRequestQueueLengthHistogram.insert(queueLength); checkMonitoringInterval(); } }
java
public void recordResourceRequestQueueLength(SocketDestination dest, int queueLength) { if(dest != null) { getOrCreateNodeStats(dest).recordResourceRequestQueueLength(null, queueLength); recordResourceRequestQueueLength(null, queueLength); } else { this.resourceRequestQueueLengthHistogram.insert(queueLength); checkMonitoringInterval(); } }
[ "public", "void", "recordResourceRequestQueueLength", "(", "SocketDestination", "dest", ",", "int", "queueLength", ")", "{", "if", "(", "dest", "!=", "null", ")", "{", "getOrCreateNodeStats", "(", "dest", ")", ".", "recordResourceRequestQueueLength", "(", "null", ...
Record the resource request queue length @param dest Destination of the socket for which resource request is enqueued. Will actually record if null. Otherwise will call this on self and corresponding child with this param null. @param queueLength The number of entries in the "asynchronous" resource request queue.
[ "Record", "the", "resource", "request", "queue", "length" ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/store/stats/ClientSocketStats.java#L321-L329
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-grpc/src/main/java/org/nd4j/graph/GraphInferenceGrpcClient.java
GraphInferenceGrpcClient.output
public <T> T output(long graphId, T value, OperandsAdapter<T> adapter) { return adapter.output(this.output(graphId, adapter.input(value))); }
java
public <T> T output(long graphId, T value, OperandsAdapter<T> adapter) { return adapter.output(this.output(graphId, adapter.input(value))); }
[ "public", "<", "T", ">", "T", "output", "(", "long", "graphId", ",", "T", "value", ",", "OperandsAdapter", "<", "T", ">", "adapter", ")", "{", "return", "adapter", ".", "output", "(", "this", ".", "output", "(", "graphId", ",", "adapter", ".", "input...
This method is suited for use of custom OperandsAdapters @param adapter @param <T> @return
[ "This", "method", "is", "suited", "for", "use", "of", "custom", "OperandsAdapters" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-serde/nd4j-grpc/src/main/java/org/nd4j/graph/GraphInferenceGrpcClient.java#L127-L129
js-lib-com/template.xhtml
src/main/java/js/template/xhtml/NumberingOperator.java
NumberingOperator.doExec
@Override protected Object doExec(Element element, Object scope, String format, Object... arguments) throws IOException { Stack<Index> indexes = this.serializer.getIndexes(); if(indexes.size() == 0) { throw new TemplateException("Required ordered collection index is missing. Numbering operator cancel execution."); } this.serializer.writeTextContent(getNumbering(this.serializer.getIndexes(), format)); return null; }
java
@Override protected Object doExec(Element element, Object scope, String format, Object... arguments) throws IOException { Stack<Index> indexes = this.serializer.getIndexes(); if(indexes.size() == 0) { throw new TemplateException("Required ordered collection index is missing. Numbering operator cancel execution."); } this.serializer.writeTextContent(getNumbering(this.serializer.getIndexes(), format)); return null; }
[ "@", "Override", "protected", "Object", "doExec", "(", "Element", "element", ",", "Object", "scope", ",", "String", "format", ",", "Object", "...", "arguments", ")", "throws", "IOException", "{", "Stack", "<", "Index", ">", "indexes", "=", "this", ".", "se...
Insert formatted numbering as element text content. If serializer indexes stack is empty throws templates exception; anyway, validation tool running on build catches numbering operator without surrounding ordered list. @param element element declaring numbering operator, @param scope scope object, @param format numbering format, see class description for syntax, @param arguments optional arguments, not used. @return always returns null to signal full processing. @throws TemplateException if serializer indexes stack is empty. @throws IOException if underlying writer fails to write.
[ "Insert", "formatted", "numbering", "as", "element", "text", "content", ".", "If", "serializer", "indexes", "stack", "is", "empty", "throws", "templates", "exception", ";", "anyway", "validation", "tool", "running", "on", "build", "catches", "numbering", "operator...
train
https://github.com/js-lib-com/template.xhtml/blob/d50cec08aca9ab9680baebe2a26a341c096564fb/src/main/java/js/template/xhtml/NumberingOperator.java#L94-L103
tango-controls/JTango
server/src/main/java/org/tango/logging/LoggingManager.java
LoggingManager.addDeviceAppender
public void addDeviceAppender(final String deviceTargetName, final Class<?> deviceClassName, final String loggingDeviceName) throws DevFailed { if (rootLoggerBack != null) { logger.debug("add device appender {} on {}", deviceTargetName, loggingDeviceName); final DeviceAppender appender = new DeviceAppender(deviceTargetName, loggingDeviceName); deviceAppenders.put(loggingDeviceName.toLowerCase(Locale.ENGLISH), appender); rootLoggerBack.addAppender(appender); // debug level by default setLoggingLevel(LoggingLevel.DEBUG.toInt(), deviceClassName); setLoggingLevel(loggingDeviceName, LoggingLevel.DEBUG.toInt()); appender.start(); } }
java
public void addDeviceAppender(final String deviceTargetName, final Class<?> deviceClassName, final String loggingDeviceName) throws DevFailed { if (rootLoggerBack != null) { logger.debug("add device appender {} on {}", deviceTargetName, loggingDeviceName); final DeviceAppender appender = new DeviceAppender(deviceTargetName, loggingDeviceName); deviceAppenders.put(loggingDeviceName.toLowerCase(Locale.ENGLISH), appender); rootLoggerBack.addAppender(appender); // debug level by default setLoggingLevel(LoggingLevel.DEBUG.toInt(), deviceClassName); setLoggingLevel(loggingDeviceName, LoggingLevel.DEBUG.toInt()); appender.start(); } }
[ "public", "void", "addDeviceAppender", "(", "final", "String", "deviceTargetName", ",", "final", "Class", "<", "?", ">", "deviceClassName", ",", "final", "String", "loggingDeviceName", ")", "throws", "DevFailed", "{", "if", "(", "rootLoggerBack", "!=", "null", "...
Logging of device sent to logviewer device @param deviceTargetName @param deviceClassName @param loggingDeviceName @throws DevFailed
[ "Logging", "of", "device", "sent", "to", "logviewer", "device" ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/logging/LoggingManager.java#L176-L188
maven-nar/nar-maven-plugin
src/main/java/com/github/maven_nar/NarProperties.java
NarProperties.getInstance
public static NarProperties getInstance(final MavenProject project) throws MojoFailureException { NarProperties instance = instances.get(project); if (instance == null) { if (project == null) { instance = new NarProperties(project, null, null); } else { String customPropertyLocation = project.getProperties().getProperty(CUSTOM_AOL_PROPERTY_KEY); if (customPropertyLocation == null) { // Try and read from the system property in case it's specified there customPropertyLocation = System.getProperties().getProperty(CUSTOM_AOL_PROPERTY_KEY); } File narFile = (customPropertyLocation != null) ? new File(customPropertyLocation) : new File(project.getBasedir(), AOL_PROPERTIES); if (narFile.exists()) { instance = new NarProperties(project, narFile, customPropertyLocation); } else { // use instance from parent instance = getInstance(project.getParent()); } } instances.put(project,instance); } return instance; }
java
public static NarProperties getInstance(final MavenProject project) throws MojoFailureException { NarProperties instance = instances.get(project); if (instance == null) { if (project == null) { instance = new NarProperties(project, null, null); } else { String customPropertyLocation = project.getProperties().getProperty(CUSTOM_AOL_PROPERTY_KEY); if (customPropertyLocation == null) { // Try and read from the system property in case it's specified there customPropertyLocation = System.getProperties().getProperty(CUSTOM_AOL_PROPERTY_KEY); } File narFile = (customPropertyLocation != null) ? new File(customPropertyLocation) : new File(project.getBasedir(), AOL_PROPERTIES); if (narFile.exists()) { instance = new NarProperties(project, narFile, customPropertyLocation); } else { // use instance from parent instance = getInstance(project.getParent()); } } instances.put(project,instance); } return instance; }
[ "public", "static", "NarProperties", "getInstance", "(", "final", "MavenProject", "project", ")", "throws", "MojoFailureException", "{", "NarProperties", "instance", "=", "instances", ".", "get", "(", "project", ")", ";", "if", "(", "instance", "==", "null", ")"...
Retrieve the NarProperties @param project may be null @return @throws MojoFailureException
[ "Retrieve", "the", "NarProperties" ]
train
https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/NarProperties.java#L54-L77
DaGeRe/KoPeMe
kopeme-analysis/src/main/java/de/dagere/kopeme/instrumentation/KiekerMeasureUtil.java
KiekerMeasureUtil.measureAfter
public OperationExecutionRecord measureAfter() { // measure after final long tout = TIME.getTime(); OperationExecutionRecord record = new OperationExecutionRecord(signature, sessionId, traceId, tin, tout, hostname, eoi, ess); CTRLINST.newMonitoringRecord(record); // cleanup if (entrypoint) { CFREGISTRY.unsetThreadLocalTraceId(); CFREGISTRY.unsetThreadLocalEOI(); CFREGISTRY.unsetThreadLocalESS(); } else { CFREGISTRY.storeThreadLocalESS(ess); // next operation is ess } return record; }
java
public OperationExecutionRecord measureAfter() { // measure after final long tout = TIME.getTime(); OperationExecutionRecord record = new OperationExecutionRecord(signature, sessionId, traceId, tin, tout, hostname, eoi, ess); CTRLINST.newMonitoringRecord(record); // cleanup if (entrypoint) { CFREGISTRY.unsetThreadLocalTraceId(); CFREGISTRY.unsetThreadLocalEOI(); CFREGISTRY.unsetThreadLocalESS(); } else { CFREGISTRY.storeThreadLocalESS(ess); // next operation is ess } return record; }
[ "public", "OperationExecutionRecord", "measureAfter", "(", ")", "{", "// measure after", "final", "long", "tout", "=", "TIME", ".", "getTime", "(", ")", ";", "OperationExecutionRecord", "record", "=", "new", "OperationExecutionRecord", "(", "signature", ",", "sessio...
Denotes that the method call has finished successfully, finishing the {@link OperationExecutionRecord} and saving it to Kieker. @return The recoreded value, mainly for testing purposes
[ "Denotes", "that", "the", "method", "call", "has", "finished", "successfully", "finishing", "the", "{", "@link", "OperationExecutionRecord", "}", "and", "saving", "it", "to", "Kieker", "." ]
train
https://github.com/DaGeRe/KoPeMe/blob/a4939113cba73cb20a2c7d6dc8d34d0139a3e340/kopeme-analysis/src/main/java/de/dagere/kopeme/instrumentation/KiekerMeasureUtil.java#L106-L120
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/XmlReader.java
XmlReader.readLong
public long readLong(long defaultValue, String attribute) { return Long.parseLong(getValue(String.valueOf(defaultValue), attribute)); }
java
public long readLong(long defaultValue, String attribute) { return Long.parseLong(getValue(String.valueOf(defaultValue), attribute)); }
[ "public", "long", "readLong", "(", "long", "defaultValue", ",", "String", "attribute", ")", "{", "return", "Long", ".", "parseLong", "(", "getValue", "(", "String", ".", "valueOf", "(", "defaultValue", ")", ",", "attribute", ")", ")", ";", "}" ]
Read a long. @param defaultValue The value returned if attribute not found. @param attribute The float name (must not be <code>null</code>). @return The long value. @throws LionEngineException If invalid argument.
[ "Read", "a", "long", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/XmlReader.java#L235-L238
kaazing/gateway
mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMResponses.java
NTLMResponses.getNTLM2SessionResponse
public static byte[] getNTLM2SessionResponse(String password, byte[] challenge, byte[] clientNonce) throws Exception { byte[] ntlmHash = ntlmHash(password); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(challenge); md5.update(clientNonce); byte[] sessionHash = new byte[8]; System.arraycopy(md5.digest(), 0, sessionHash, 0, 8); return lmResponse(ntlmHash, sessionHash); }
java
public static byte[] getNTLM2SessionResponse(String password, byte[] challenge, byte[] clientNonce) throws Exception { byte[] ntlmHash = ntlmHash(password); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(challenge); md5.update(clientNonce); byte[] sessionHash = new byte[8]; System.arraycopy(md5.digest(), 0, sessionHash, 0, 8); return lmResponse(ntlmHash, sessionHash); }
[ "public", "static", "byte", "[", "]", "getNTLM2SessionResponse", "(", "String", "password", ",", "byte", "[", "]", "challenge", ",", "byte", "[", "]", "clientNonce", ")", "throws", "Exception", "{", "byte", "[", "]", "ntlmHash", "=", "ntlmHash", "(", "pass...
Calculates the NTLM2 Session Response for the given challenge, using the specified password and client nonce. @param password The user's password. @param challenge The Type 2 challenge from the server. @param clientNonce The random 8-byte client nonce. @return The NTLM2 Session Response. This is placed in the NTLM response field of the Type 3 message; the LM response field contains the client nonce, null-padded to 24 bytes.
[ "Calculates", "the", "NTLM2", "Session", "Response", "for", "the", "given", "challenge", "using", "the", "specified", "password", "and", "client", "nonce", "." ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/proxy/handlers/http/ntlm/NTLMResponses.java#L161-L170
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/BitReferenceField.java
BitReferenceField.setupDefaultView
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) // Add this view to the list { if (targetScreen instanceof GridScreenParent) return super.setupDefaultView(itsLocation, targetScreen, converter, iDisplayFieldDesc, properties); Record record = this.makeReferenceRecord(); ScreenComponent screenField = null; Map<String,Object> staticMap = new HashMap<String,Object>(); staticMap.put(ScreenModel.DISPLAY_STRING, DBConstants.BLANK); createScreenComponent(ScreenModel.STATIC_STRING, itsLocation, targetScreen, null, 0, staticMap); String strDisplay = converter.getFieldDesc(); if ((strDisplay != null) && (strDisplay.length() > 0)) { ScreenLoc descLocation = targetScreen.getNextLocation(ScreenConstants.FIELD_DESC, ScreenConstants.DONT_SET_ANCHOR); staticMap.put(ScreenModel.DISPLAY_STRING, strDisplay); createScreenComponent(ScreenModel.STATIC_STRING, descLocation, targetScreen, null, 0, staticMap); } try { record.close(); while (record.hasNext()) // 0 = First Day -> 6 = Last Day of Week { record.next(); Converter dayConverter = (Converter)converter; String strWeek = record.getField(record.getDefaultDisplayFieldSeq()).toString(); if (strWeek.length() > 0) dayConverter = new FieldDescConverter(dayConverter, strWeek); int sBitPosition = (int)record.getCounterField().getValue(); m_iBitsToCheck |= 1 << sBitPosition; dayConverter = new BitConverter(dayConverter, sBitPosition, true, true); itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_CHECKBOX, ScreenConstants.DONT_SET_ANCHOR); screenField = dayConverter.setupDefaultView(itsLocation, targetScreen, iDisplayFieldDesc); } } catch (DBException e) { e.printStackTrace(); } return screenField; }
java
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) // Add this view to the list { if (targetScreen instanceof GridScreenParent) return super.setupDefaultView(itsLocation, targetScreen, converter, iDisplayFieldDesc, properties); Record record = this.makeReferenceRecord(); ScreenComponent screenField = null; Map<String,Object> staticMap = new HashMap<String,Object>(); staticMap.put(ScreenModel.DISPLAY_STRING, DBConstants.BLANK); createScreenComponent(ScreenModel.STATIC_STRING, itsLocation, targetScreen, null, 0, staticMap); String strDisplay = converter.getFieldDesc(); if ((strDisplay != null) && (strDisplay.length() > 0)) { ScreenLoc descLocation = targetScreen.getNextLocation(ScreenConstants.FIELD_DESC, ScreenConstants.DONT_SET_ANCHOR); staticMap.put(ScreenModel.DISPLAY_STRING, strDisplay); createScreenComponent(ScreenModel.STATIC_STRING, descLocation, targetScreen, null, 0, staticMap); } try { record.close(); while (record.hasNext()) // 0 = First Day -> 6 = Last Day of Week { record.next(); Converter dayConverter = (Converter)converter; String strWeek = record.getField(record.getDefaultDisplayFieldSeq()).toString(); if (strWeek.length() > 0) dayConverter = new FieldDescConverter(dayConverter, strWeek); int sBitPosition = (int)record.getCounterField().getValue(); m_iBitsToCheck |= 1 << sBitPosition; dayConverter = new BitConverter(dayConverter, sBitPosition, true, true); itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_CHECKBOX, ScreenConstants.DONT_SET_ANCHOR); screenField = dayConverter.setupDefaultView(itsLocation, targetScreen, iDisplayFieldDesc); } } catch (DBException e) { e.printStackTrace(); } return screenField; }
[ "public", "ScreenComponent", "setupDefaultView", "(", "ScreenLoc", "itsLocation", ",", "ComponentParent", "targetScreen", ",", "Convert", "converter", ",", "int", "iDisplayFieldDesc", ",", "Map", "<", "String", ",", "Object", ">", "properties", ")", "// Add this view ...
Set up the default screen control for this field. @param itsLocation Location of this component on screen (ie., GridBagConstraint). @param targetScreen Where to place this component (ie., Parent screen or GridBagLayout). @param converter The converter to set the screenfield to. @param iDisplayFieldDesc Display the label? (optional). @return Return the component or ScreenField that is created for this field.
[ "Set", "up", "the", "default", "screen", "control", "for", "this", "field", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/BitReferenceField.java#L79-L116
undertow-io/undertow
core/src/main/java/io/undertow/Handlers.java
Handlers.acl
public static final AccessControlListHandler acl(final HttpHandler next, boolean defaultAllow, ExchangeAttribute attribute) { return new AccessControlListHandler(next, attribute).setDefaultAllow(defaultAllow); }
java
public static final AccessControlListHandler acl(final HttpHandler next, boolean defaultAllow, ExchangeAttribute attribute) { return new AccessControlListHandler(next, attribute).setDefaultAllow(defaultAllow); }
[ "public", "static", "final", "AccessControlListHandler", "acl", "(", "final", "HttpHandler", "next", ",", "boolean", "defaultAllow", ",", "ExchangeAttribute", "attribute", ")", "{", "return", "new", "AccessControlListHandler", "(", "next", ",", "attribute", ")", "."...
Returns a new handler that can allow or deny access to a resource based an at attribute of the exchange @param next The next handler in the chain @param defaultAllow Determine if a non-matching user agent will be allowed by default @return A new user agent access control handler
[ "Returns", "a", "new", "handler", "that", "can", "allow", "or", "deny", "access", "to", "a", "resource", "based", "an", "at", "attribute", "of", "the", "exchange" ]
train
https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/Handlers.java#L329-L331
ribot/easy-adapter
library/src/main/java/uk/co/ribot/easyadapter/annotations/FieldAnnotationParser.java
FieldAnnotationParser.setViewFields
private static void setViewFields(final Object object, final ViewFinder viewFinder) { Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(ViewId.class)) { field.setAccessible(true); ViewId viewIdAnnotation = field.getAnnotation(ViewId.class); try { field.set(object, field.getType().cast(viewFinder.findViewById(viewIdAnnotation.value()))); } catch (IllegalAccessException e) { e.printStackTrace(); } } } }
java
private static void setViewFields(final Object object, final ViewFinder viewFinder) { Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(ViewId.class)) { field.setAccessible(true); ViewId viewIdAnnotation = field.getAnnotation(ViewId.class); try { field.set(object, field.getType().cast(viewFinder.findViewById(viewIdAnnotation.value()))); } catch (IllegalAccessException e) { e.printStackTrace(); } } } }
[ "private", "static", "void", "setViewFields", "(", "final", "Object", "object", ",", "final", "ViewFinder", "viewFinder", ")", "{", "Field", "[", "]", "fields", "=", "object", ".", "getClass", "(", ")", ".", "getDeclaredFields", "(", ")", ";", "for", "(", ...
Parse {@link ViewId} annotation and try to assign the view with that id to the annotated field. It will throw a {@link ClassCastException} if the field and the view with the given ID have different types. @param object object where the annotation is. @param viewFinder callback that provides a way of finding the view by the viewID given in the annotation.
[ "Parse", "{", "@link", "ViewId", "}", "annotation", "and", "try", "to", "assign", "the", "view", "with", "that", "id", "to", "the", "annotated", "field", ".", "It", "will", "throw", "a", "{", "@link", "ClassCastException", "}", "if", "the", "field", "and...
train
https://github.com/ribot/easy-adapter/blob/8cf85023a79c781aa2013e9dc39fd66734fb2019/library/src/main/java/uk/co/ribot/easyadapter/annotations/FieldAnnotationParser.java#L65-L79
tomgibara/bits
src/main/java/com/tomgibara/bits/Bits.java
Bits.resizedCopyOf
public static BitStore resizedCopyOf(BitStore store, int newSize, boolean anchorLeft) { if (newSize < 0) throw new IllegalArgumentException(); int size = store.size(); if (size == newSize) return store.mutableCopy(); int from; int to; if (anchorLeft) { from = size - newSize; to = size; } else { from = 0; to = newSize; } if (newSize < size) return store.range(from, to).mutableCopy(); BitStore copy = store(newSize); copy.setStore(-from, store); return copy; }
java
public static BitStore resizedCopyOf(BitStore store, int newSize, boolean anchorLeft) { if (newSize < 0) throw new IllegalArgumentException(); int size = store.size(); if (size == newSize) return store.mutableCopy(); int from; int to; if (anchorLeft) { from = size - newSize; to = size; } else { from = 0; to = newSize; } if (newSize < size) return store.range(from, to).mutableCopy(); BitStore copy = store(newSize); copy.setStore(-from, store); return copy; }
[ "public", "static", "BitStore", "resizedCopyOf", "(", "BitStore", "store", ",", "int", "newSize", ",", "boolean", "anchorLeft", ")", "{", "if", "(", "newSize", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", ")", ";", "int", "size", "=", "s...
Creates a mutable, resized copy of a {@link BitStore}. The new size may be equal, larger or smaller than original size. When the the new size is greater than the original size, the new bits are identically zero. The method makes no guarantees about the BitStore implementation that results, in particular, there is certainly no guarantee that the returned {@link BitStore} will share its implementation with the supplied {@link BitStore}. @param store a BitStore @param newSize a new size for the BitStore @param anchorLeft true if the most-significant bit of the original store should remain the most-significant bit of the resized store, false if the least-significant bit of the original store should remain the least-significant bit of the resized store @return a resized copy of the original {@link BitStore}
[ "Creates", "a", "mutable", "resized", "copy", "of", "a", "{", "@link", "BitStore", "}", ".", "The", "new", "size", "may", "be", "equal", "larger", "or", "smaller", "than", "original", "size", ".", "When", "the", "the", "new", "size", "is", "greater", "...
train
https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/Bits.java#L1023-L1040
jcuda/jcuda
JCudaJava/src/main/java/jcuda/runtime/JCuda.java
JCuda.cudaMemcpyToArray
public static int cudaMemcpyToArray(cudaArray dst, long wOffset, long hOffset, Pointer src, long count, int cudaMemcpyKind_kind) { return checkResult(cudaMemcpyToArrayNative(dst, wOffset, hOffset, src, count, cudaMemcpyKind_kind)); }
java
public static int cudaMemcpyToArray(cudaArray dst, long wOffset, long hOffset, Pointer src, long count, int cudaMemcpyKind_kind) { return checkResult(cudaMemcpyToArrayNative(dst, wOffset, hOffset, src, count, cudaMemcpyKind_kind)); }
[ "public", "static", "int", "cudaMemcpyToArray", "(", "cudaArray", "dst", ",", "long", "wOffset", ",", "long", "hOffset", ",", "Pointer", "src", ",", "long", "count", ",", "int", "cudaMemcpyKind_kind", ")", "{", "return", "checkResult", "(", "cudaMemcpyToArrayNat...
Copies data between host and device. <pre> cudaError_t cudaMemcpyToArray ( cudaArray_t dst, size_t wOffset, size_t hOffset, const void* src, size_t count, cudaMemcpyKind kind ) </pre> <div> <p>Copies data between host and device. Copies <tt>count</tt> bytes from the memory area pointed to by <tt>src</tt> to the CUDA array <tt>dst</tt> starting at the upper left corner (<tt>wOffset</tt>, <tt>hOffset</tt>), where <tt>kind</tt> is one of cudaMemcpyHostToHost, cudaMemcpyHostToDevice, cudaMemcpyDeviceToHost, or cudaMemcpyDeviceToDevice, and specifies the direction of the copy. </p> <div> <span>Note:</span> <ul> <li> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </li> <li> <p>This function exhibits synchronous behavior for most use cases. </p> </li> </ul> </div> </p> </div> @param dst Destination memory address @param wOffset Destination starting X offset @param hOffset Destination starting Y offset @param src Source memory address @param count Size in bytes to copy @param kind Type of transfer @return cudaSuccess, cudaErrorInvalidValue, cudaErrorInvalidDevicePointer, cudaErrorInvalidMemcpyDirection @see JCuda#cudaMemcpy @see JCuda#cudaMemcpy2D @see JCuda#cudaMemcpy2DToArray @see JCuda#cudaMemcpyFromArray @see JCuda#cudaMemcpy2DFromArray @see JCuda#cudaMemcpyArrayToArray @see JCuda#cudaMemcpy2DArrayToArray @see JCuda#cudaMemcpyToSymbol @see JCuda#cudaMemcpyFromSymbol @see JCuda#cudaMemcpyAsync @see JCuda#cudaMemcpy2DAsync @see JCuda#cudaMemcpyToArrayAsync @see JCuda#cudaMemcpy2DToArrayAsync @see JCuda#cudaMemcpyFromArrayAsync @see JCuda#cudaMemcpy2DFromArrayAsync @see JCuda#cudaMemcpyToSymbolAsync @see JCuda#cudaMemcpyFromSymbolAsync
[ "Copies", "data", "between", "host", "and", "device", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/runtime/JCuda.java#L4747-L4750
TNG/JGiven
jgiven-core/src/main/java/com/tngtech/jgiven/impl/util/ReflectionUtil.java
ReflectionUtil.getAllNonStaticFieldValuesFrom
public static List<Object> getAllNonStaticFieldValuesFrom( final Class<?> clazz, final Object target, final String errorDescription ) { return getAllFieldValues( target, getAllNonStaticFields( clazz ), errorDescription ); }
java
public static List<Object> getAllNonStaticFieldValuesFrom( final Class<?> clazz, final Object target, final String errorDescription ) { return getAllFieldValues( target, getAllNonStaticFields( clazz ), errorDescription ); }
[ "public", "static", "List", "<", "Object", ">", "getAllNonStaticFieldValuesFrom", "(", "final", "Class", "<", "?", ">", "clazz", ",", "final", "Object", "target", ",", "final", "String", "errorDescription", ")", "{", "return", "getAllFieldValues", "(", "target",...
Returns a {@link List} of objects reflecting all the non-static field values declared by the class or interface represented by the given {@link Class} object and defined by the given {@link Object}. This includes {@code public}, {@code protected}, default (package) access, and {@code private} fields, but excludes inherited fields. The elements in the {@link List} returned are not sorted and are not in any particular order. This method returns an empty {@link List} if the class or interface declares no fields, or if the given {@link Class} object represents a primitive type, an array class, or void. @param clazz class or interface declaring fields @param target instance of given {@code clazz} from which field values should be retrieved @param errorDescription customizable part of logged error message @return a {@link List} containing all the found field values (never {@code null})
[ "Returns", "a", "{", "@link", "List", "}", "of", "objects", "reflecting", "all", "the", "non", "-", "static", "field", "values", "declared", "by", "the", "class", "or", "interface", "represented", "by", "the", "given", "{", "@link", "Class", "}", "object",...
train
https://github.com/TNG/JGiven/blob/1a69248fc6d7eb380cdc4542e3be273842889748/jgiven-core/src/main/java/com/tngtech/jgiven/impl/util/ReflectionUtil.java#L203-L205
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java
CommonOps_DDRM.columnsToVector
public static DMatrixRMaj[] columnsToVector(DMatrixRMaj A, DMatrixRMaj[] v) { DMatrixRMaj[]ret; if( v == null || v.length < A.numCols ) { ret = new DMatrixRMaj[ A.numCols ]; } else { ret = v; } for( int i = 0; i < ret.length; i++ ) { if( ret[i] == null ) { ret[i] = new DMatrixRMaj(A.numRows,1); } else { ret[i].reshape(A.numRows,1, false); } DMatrixRMaj u = ret[i]; for( int j = 0; j < A.numRows; j++ ) { u.set(j,0, A.get(j,i)); } } return ret; }
java
public static DMatrixRMaj[] columnsToVector(DMatrixRMaj A, DMatrixRMaj[] v) { DMatrixRMaj[]ret; if( v == null || v.length < A.numCols ) { ret = new DMatrixRMaj[ A.numCols ]; } else { ret = v; } for( int i = 0; i < ret.length; i++ ) { if( ret[i] == null ) { ret[i] = new DMatrixRMaj(A.numRows,1); } else { ret[i].reshape(A.numRows,1, false); } DMatrixRMaj u = ret[i]; for( int j = 0; j < A.numRows; j++ ) { u.set(j,0, A.get(j,i)); } } return ret; }
[ "public", "static", "DMatrixRMaj", "[", "]", "columnsToVector", "(", "DMatrixRMaj", "A", ",", "DMatrixRMaj", "[", "]", "v", ")", "{", "DMatrixRMaj", "[", "]", "ret", ";", "if", "(", "v", "==", "null", "||", "v", ".", "length", "<", "A", ".", "numCols...
Converts the columns in a matrix into a set of vectors. @param A Matrix. Not modified. @param v @return An array of vectors.
[ "Converts", "the", "columns", "in", "a", "matrix", "into", "a", "set", "of", "vectors", "." ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L878-L902
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/db/entitymanager/cache/DbEntityCache.java
DbEntityCache.getCachedEntity
public CachedDbEntity getCachedEntity(Class<?> type, String id) { Class<?> cacheKey = cacheKeyMapping.getEntityCacheKey(type); Map<String, CachedDbEntity> entitiesByType = cachedEntites.get(cacheKey); if(entitiesByType != null) { return entitiesByType.get(id); } else { return null; } }
java
public CachedDbEntity getCachedEntity(Class<?> type, String id) { Class<?> cacheKey = cacheKeyMapping.getEntityCacheKey(type); Map<String, CachedDbEntity> entitiesByType = cachedEntites.get(cacheKey); if(entitiesByType != null) { return entitiesByType.get(id); } else { return null; } }
[ "public", "CachedDbEntity", "getCachedEntity", "(", "Class", "<", "?", ">", "type", ",", "String", "id", ")", "{", "Class", "<", "?", ">", "cacheKey", "=", "cacheKeyMapping", ".", "getEntityCacheKey", "(", "type", ")", ";", "Map", "<", "String", ",", "Ca...
Looks up an entity in the cache. @param type the type of the object @param id the id of the CachedEntity to lookup @return the cached entity or null if the entity does not exist.
[ "Looks", "up", "an", "entity", "in", "the", "cache", "." ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/db/entitymanager/cache/DbEntityCache.java#L126-L134
apache/groovy
subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java
NioGroovyMethods.withObjectOutputStream
public static <T> T withObjectOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.ObjectOutputStream") Closure<T> closure) throws IOException { return IOGroovyMethods.withStream(newObjectOutputStream(self), closure); }
java
public static <T> T withObjectOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.ObjectOutputStream") Closure<T> closure) throws IOException { return IOGroovyMethods.withStream(newObjectOutputStream(self), closure); }
[ "public", "static", "<", "T", ">", "T", "withObjectOutputStream", "(", "Path", "self", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.io.ObjectOutputStream\"", ")", "Closure", "<", "T", ">", "closure", ...
Create a new ObjectOutputStream for this path and then pass it to the closure. This method ensures the stream is closed after the closure returns. @param self a Path @param closure a closure @return the value returned by the closure @throws java.io.IOException if an IOException occurs. @see IOGroovyMethods#withStream(java.io.OutputStream, groovy.lang.Closure) @since 2.3.0
[ "Create", "a", "new", "ObjectOutputStream", "for", "this", "path", "and", "then", "pass", "it", "to", "the", "closure", ".", "This", "method", "ensures", "the", "stream", "is", "closed", "after", "the", "closure", "returns", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L121-L123
lastaflute/lastaflute
src/main/java/org/lastaflute/web/path/ActionPathResolver.java
ActionPathResolver.toActionUrl
public String toActionUrl(Class<?> actionType, UrlChain chain) { assertArgumentNotNull("actionType", actionType); assertArgumentNotNull("chain", chain); final UrlReverseOption option = customizeActionUrlReverse(actionType, chain); // not null, empty allowed final StringBuilder sb = new StringBuilder(); buildActionPath(sb, actionType, option); buildUrlParts(sb, chain); buildGetParam(sb, chain); buildHashOnUrl(sb, chain); return sb.toString(); }
java
public String toActionUrl(Class<?> actionType, UrlChain chain) { assertArgumentNotNull("actionType", actionType); assertArgumentNotNull("chain", chain); final UrlReverseOption option = customizeActionUrlReverse(actionType, chain); // not null, empty allowed final StringBuilder sb = new StringBuilder(); buildActionPath(sb, actionType, option); buildUrlParts(sb, chain); buildGetParam(sb, chain); buildHashOnUrl(sb, chain); return sb.toString(); }
[ "public", "String", "toActionUrl", "(", "Class", "<", "?", ">", "actionType", ",", "UrlChain", "chain", ")", "{", "assertArgumentNotNull", "(", "\"actionType\"", ",", "actionType", ")", ";", "assertArgumentNotNull", "(", "\"chain\"", ",", "chain", ")", ";", "f...
Convert to URL string to move the action. <br> e.g. ProductListAction with moreUrl(3) to /product/list/3 <br> And not contain context path. @param actionType The class type of action that it redirects to. (NotNull) @param chain The chain of URL to build additional info on URL. (NotNull) @return The URL string to move to the action. (NotNull)
[ "Convert", "to", "URL", "string", "to", "move", "the", "action", ".", "<br", ">", "e", ".", "g", ".", "ProductListAction", "with", "moreUrl", "(", "3", ")", "to", "/", "product", "/", "list", "/", "3", "<br", ">", "And", "not", "contain", "context", ...
train
https://github.com/lastaflute/lastaflute/blob/17b56dda8322e4c6d79043532c1dda917d6b60a8/src/main/java/org/lastaflute/web/path/ActionPathResolver.java#L374-L384
cucumber/cucumber-jvm
java/src/main/java/cucumber/runtime/java/MethodScanner.java
MethodScanner.scan
public void scan(JavaBackend javaBackend, Method method, Class<?> glueCodeClass) { Annotation[] methodAnnotations = method.getAnnotations(); for (Annotation annotation : methodAnnotations) { if (isHookAnnotation(annotation)) { validateMethod(method, glueCodeClass); javaBackend.addHook(annotation, method); } else if (isStepdefAnnotation(annotation)) { validateMethod(method, glueCodeClass); javaBackend.addStepDefinition(annotation, method); } } }
java
public void scan(JavaBackend javaBackend, Method method, Class<?> glueCodeClass) { Annotation[] methodAnnotations = method.getAnnotations(); for (Annotation annotation : methodAnnotations) { if (isHookAnnotation(annotation)) { validateMethod(method, glueCodeClass); javaBackend.addHook(annotation, method); } else if (isStepdefAnnotation(annotation)) { validateMethod(method, glueCodeClass); javaBackend.addStepDefinition(annotation, method); } } }
[ "public", "void", "scan", "(", "JavaBackend", "javaBackend", ",", "Method", "method", ",", "Class", "<", "?", ">", "glueCodeClass", ")", "{", "Annotation", "[", "]", "methodAnnotations", "=", "method", ".", "getAnnotations", "(", ")", ";", "for", "(", "Ann...
Registers step definitions and hooks. @param javaBackend the backend where stepdefs and hooks will be registered. @param method a candidate for being a stepdef or hook. @param glueCodeClass the class where the method is declared.
[ "Registers", "step", "definitions", "and", "hooks", "." ]
train
https://github.com/cucumber/cucumber-jvm/blob/437bb3a1f1d91b56f44059c835765b395eefc777/java/src/main/java/cucumber/runtime/java/MethodScanner.java#L56-L67
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.beginGeneratevpnclientpackageAsync
public Observable<String> beginGeneratevpnclientpackageAsync(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters) { return beginGeneratevpnclientpackageWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, parameters).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); }
java
public Observable<String> beginGeneratevpnclientpackageAsync(String resourceGroupName, String virtualNetworkGatewayName, VpnClientParameters parameters) { return beginGeneratevpnclientpackageWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, parameters).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); }
[ "public", "Observable", "<", "String", ">", "beginGeneratevpnclientpackageAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ",", "VpnClientParameters", "parameters", ")", "{", "return", "beginGeneratevpnclientpackageWithServiceResponseAsync",...
Generates VPN client package for P2S client of the virtual network gateway in the specified resource group. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param parameters Parameters supplied to the generate virtual network gateway VPN client package operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the String object
[ "Generates", "VPN", "client", "package", "for", "P2S", "client", "of", "the", "virtual", "network", "gateway", "in", "the", "specified", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L1567-L1574
infinispan/infinispan
server/integration/commons/src/main/java/org/infinispan/server/commons/features/Feature.java
Feature.isAvailableOrThrowException
public static Features isAvailableOrThrowException(Features features, String feature, ClassLoader classLoader) { if (features == null) { features = new Features(classLoader); } isAvailableOrThrowException(features, feature); return features; }
java
public static Features isAvailableOrThrowException(Features features, String feature, ClassLoader classLoader) { if (features == null) { features = new Features(classLoader); } isAvailableOrThrowException(features, feature); return features; }
[ "public", "static", "Features", "isAvailableOrThrowException", "(", "Features", "features", ",", "String", "feature", ",", "ClassLoader", "classLoader", ")", "{", "if", "(", "features", "==", "null", ")", "{", "features", "=", "new", "Features", "(", "classLoade...
Verify that the specified feature is enabled. Initializes features if the provided one is null, allowing for lazily initialized Features instance. @param features existing instance or null. @param feature the feature string to check. @param classLoader to create the {@link Features} instance with if it doesn't already exist. @return the features instance that was checked, always non null @throws org.infinispan.commons.CacheConfigurationException thrown if the feature was disabled
[ "Verify", "that", "the", "specified", "feature", "is", "enabled", ".", "Initializes", "features", "if", "the", "provided", "one", "is", "null", "allowing", "for", "lazily", "initialized", "Features", "instance", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/integration/commons/src/main/java/org/infinispan/server/commons/features/Feature.java#L20-L26
kaazing/java.client
ws/ws/src/main/java/org/kaazing/gateway/client/util/WrappedByteBuffer.java
WrappedByteBuffer.putBytesAt
public WrappedByteBuffer putBytesAt(int index, byte[] b) { _checkForWriteAt(index, b.length); int pos = _buf.position(); _buf.position(index); _buf.put(b, 0, b.length); _buf.position(pos); return this; }
java
public WrappedByteBuffer putBytesAt(int index, byte[] b) { _checkForWriteAt(index, b.length); int pos = _buf.position(); _buf.position(index); _buf.put(b, 0, b.length); _buf.position(pos); return this; }
[ "public", "WrappedByteBuffer", "putBytesAt", "(", "int", "index", ",", "byte", "[", "]", "b", ")", "{", "_checkForWriteAt", "(", "index", ",", "b", ".", "length", ")", ";", "int", "pos", "=", "_buf", ".", "position", "(", ")", ";", "_buf", ".", "posi...
Puts a single-byte array into the buffer at the specified index. @param index the index @param v the single-byte array @return the buffer
[ "Puts", "a", "single", "-", "byte", "array", "into", "the", "buffer", "at", "the", "specified", "index", "." ]
train
https://github.com/kaazing/java.client/blob/25ad2ae5bb24aa9d6b79400fce649b518dcfbe26/ws/ws/src/main/java/org/kaazing/gateway/client/util/WrappedByteBuffer.java#L635-L642
looly/hutool
hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java
DateUtil.formatBetween
public static String formatBetween(Date beginDate, Date endDate) { return formatBetween(between(beginDate, endDate, DateUnit.MS)); }
java
public static String formatBetween(Date beginDate, Date endDate) { return formatBetween(between(beginDate, endDate, DateUnit.MS)); }
[ "public", "static", "String", "formatBetween", "(", "Date", "beginDate", ",", "Date", "endDate", ")", "{", "return", "formatBetween", "(", "between", "(", "beginDate", ",", "endDate", ",", "DateUnit", ".", "MS", ")", ")", ";", "}" ]
格式化日期间隔输出,精确到毫秒 @param beginDate 起始日期 @param endDate 结束日期 @return XX天XX小时XX分XX秒 @since 3.0.1
[ "格式化日期间隔输出,精确到毫秒" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java#L1330-L1332
OpenLiberty/open-liberty
dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/AbstractDirector.java
AbstractDirector.isEmpty
boolean isEmpty(Map<String, List<List<RepositoryResource>>> installResources) { if (installResources == null) return true; for (List<List<RepositoryResource>> targetList : installResources.values()) { for (List<RepositoryResource> mrList : targetList) { if (!mrList.isEmpty()) return false; } } return true; }
java
boolean isEmpty(Map<String, List<List<RepositoryResource>>> installResources) { if (installResources == null) return true; for (List<List<RepositoryResource>> targetList : installResources.values()) { for (List<RepositoryResource> mrList : targetList) { if (!mrList.isEmpty()) return false; } } return true; }
[ "boolean", "isEmpty", "(", "Map", "<", "String", ",", "List", "<", "List", "<", "RepositoryResource", ">", ">", ">", "installResources", ")", "{", "if", "(", "installResources", "==", "null", ")", "return", "true", ";", "for", "(", "List", "<", "List", ...
Checks if installResources map contains any resources @param installResources the map of installResources @return true if all lists in the map are empty
[ "Checks", "if", "installResources", "map", "contains", "any", "resources" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/AbstractDirector.java#L119-L129
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Scroller.java
Scroller.scrollViewToSide
public void scrollViewToSide(View view, Side side, float scrollPosition, int stepCount) { int[] corners = new int[2]; view.getLocationOnScreen(corners); int viewHeight = view.getHeight(); int viewWidth = view.getWidth(); float x = corners[0] + viewWidth * scrollPosition; float y = corners[1] + viewHeight / 2.0f; if (side == Side.LEFT) drag(corners[0], x, y, y, stepCount); else if (side == Side.RIGHT) drag(x, corners[0], y, y, stepCount); }
java
public void scrollViewToSide(View view, Side side, float scrollPosition, int stepCount) { int[] corners = new int[2]; view.getLocationOnScreen(corners); int viewHeight = view.getHeight(); int viewWidth = view.getWidth(); float x = corners[0] + viewWidth * scrollPosition; float y = corners[1] + viewHeight / 2.0f; if (side == Side.LEFT) drag(corners[0], x, y, y, stepCount); else if (side == Side.RIGHT) drag(x, corners[0], y, y, stepCount); }
[ "public", "void", "scrollViewToSide", "(", "View", "view", ",", "Side", "side", ",", "float", "scrollPosition", ",", "int", "stepCount", ")", "{", "int", "[", "]", "corners", "=", "new", "int", "[", "2", "]", ";", "view", ".", "getLocationOnScreen", "(",...
Scrolls view horizontally. @param view the view to scroll @param side the side to which to scroll; {@link Side#RIGHT} or {@link Side#LEFT} @param scrollPosition the position to scroll to, from 0 to 1 where 1 is all the way. Example is: 0.55. @param stepCount how many move steps to include in the scroll. Less steps results in a faster scroll
[ "Scrolls", "view", "horizontally", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Scroller.java#L372-L383
lucee/Lucee
core/src/main/java/lucee/transformer/bytecode/util/ASMUtil.java
ASMUtil.getAttributeBoolean
public static Boolean getAttributeBoolean(Tag tag, String attrName, Boolean defaultValue) { Literal lit = getAttributeLiteral(tag, attrName, null); if (lit == null) return defaultValue; return lit.getBoolean(defaultValue); }
java
public static Boolean getAttributeBoolean(Tag tag, String attrName, Boolean defaultValue) { Literal lit = getAttributeLiteral(tag, attrName, null); if (lit == null) return defaultValue; return lit.getBoolean(defaultValue); }
[ "public", "static", "Boolean", "getAttributeBoolean", "(", "Tag", "tag", ",", "String", "attrName", ",", "Boolean", "defaultValue", ")", "{", "Literal", "lit", "=", "getAttributeLiteral", "(", "tag", ",", "attrName", ",", "null", ")", ";", "if", "(", "lit", ...
extract the content of a attribut @param cfxdTag @param attrName @return attribute value @throws EvaluatorException
[ "extract", "the", "content", "of", "a", "attribut" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/transformer/bytecode/util/ASMUtil.java#L331-L335
tractionsoftware/gwt-traction
src/main/java/com/tractionsoftware/gwt/user/client/util/RgbaColor.java
RgbaColor.withHsl
private RgbaColor withHsl(int index, float value) { float[] HSL = convertToHsl(); HSL[index] = value; return RgbaColor.fromHsl(HSL); }
java
private RgbaColor withHsl(int index, float value) { float[] HSL = convertToHsl(); HSL[index] = value; return RgbaColor.fromHsl(HSL); }
[ "private", "RgbaColor", "withHsl", "(", "int", "index", ",", "float", "value", ")", "{", "float", "[", "]", "HSL", "=", "convertToHsl", "(", ")", ";", "HSL", "[", "index", "]", "=", "value", ";", "return", "RgbaColor", ".", "fromHsl", "(", "HSL", ")"...
Returns a new color with a new value of the specified HSL component.
[ "Returns", "a", "new", "color", "with", "a", "new", "value", "of", "the", "specified", "HSL", "component", "." ]
train
https://github.com/tractionsoftware/gwt-traction/blob/efc1423c619439763fb064b777b7235e9ce414a3/src/main/java/com/tractionsoftware/gwt/user/client/util/RgbaColor.java#L389-L393
alkacon/opencms-core
src/org/opencms/xml/CmsXmlGenericWrapper.java
CmsXmlGenericWrapper.elementIterable
public static Iterable<Element> elementIterable(final Element element, final String name) { return new Iterable<Element>() { public Iterator<Element> iterator() { return elementIterator(element, name); } }; }
java
public static Iterable<Element> elementIterable(final Element element, final String name) { return new Iterable<Element>() { public Iterator<Element> iterator() { return elementIterator(element, name); } }; }
[ "public", "static", "Iterable", "<", "Element", ">", "elementIterable", "(", "final", "Element", "element", ",", "final", "String", "name", ")", "{", "return", "new", "Iterable", "<", "Element", ">", "(", ")", "{", "public", "Iterator", "<", "Element", ">"...
Returns an element iterator.<p> @param element the element @param name the name @return the iterator
[ "Returns", "an", "element", "iterator", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/CmsXmlGenericWrapper.java#L74-L83
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/NodeVector.java
NodeVector.insertElementAt
public void insertElementAt(int value, int at) { if (null == m_map) { m_map = new int[m_blocksize]; m_mapSize = m_blocksize; } else if ((m_firstFree + 1) >= m_mapSize) { m_mapSize += m_blocksize; int newMap[] = new int[m_mapSize]; System.arraycopy(m_map, 0, newMap, 0, m_firstFree + 1); m_map = newMap; } if (at <= (m_firstFree - 1)) { System.arraycopy(m_map, at, m_map, at + 1, m_firstFree - at); } m_map[at] = value; m_firstFree++; }
java
public void insertElementAt(int value, int at) { if (null == m_map) { m_map = new int[m_blocksize]; m_mapSize = m_blocksize; } else if ((m_firstFree + 1) >= m_mapSize) { m_mapSize += m_blocksize; int newMap[] = new int[m_mapSize]; System.arraycopy(m_map, 0, newMap, 0, m_firstFree + 1); m_map = newMap; } if (at <= (m_firstFree - 1)) { System.arraycopy(m_map, at, m_map, at + 1, m_firstFree - at); } m_map[at] = value; m_firstFree++; }
[ "public", "void", "insertElementAt", "(", "int", "value", ",", "int", "at", ")", "{", "if", "(", "null", "==", "m_map", ")", "{", "m_map", "=", "new", "int", "[", "m_blocksize", "]", ";", "m_mapSize", "=", "m_blocksize", ";", "}", "else", "if", "(", ...
Inserts the specified node in this vector at the specified index. Each component in this vector with an index greater or equal to the specified index is shifted upward to have an index one greater than the value it had previously. @param value Node to insert @param at Position where to insert
[ "Inserts", "the", "specified", "node", "in", "this", "vector", "at", "the", "specified", "index", ".", "Each", "component", "in", "this", "vector", "with", "an", "index", "greater", "or", "equal", "to", "the", "specified", "index", "is", "shifted", "upward",...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/NodeVector.java#L362-L389
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java
AmazonS3Client.getResourceUrl
public String getResourceUrl(String bucketName, String key) { try { return getUrl(bucketName, key).toString(); } catch ( Exception e ) { return null; } }
java
public String getResourceUrl(String bucketName, String key) { try { return getUrl(bucketName, key).toString(); } catch ( Exception e ) { return null; } }
[ "public", "String", "getResourceUrl", "(", "String", "bucketName", ",", "String", "key", ")", "{", "try", "{", "return", "getUrl", "(", "bucketName", ",", "key", ")", ".", "toString", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "retur...
Returns the URL to the key in the bucket given, using the client's scheme and endpoint. Returns null if the given bucket and key cannot be converted to a URL.
[ "Returns", "the", "URL", "to", "the", "key", "in", "the", "bucket", "given", "using", "the", "client", "s", "scheme", "and", "endpoint", ".", "Returns", "null", "if", "the", "given", "bucket", "and", "key", "cannot", "be", "converted", "to", "a", "URL", ...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java#L4559-L4565
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringHelper.java
StringHelper.getIndexOf
public static int getIndexOf (@Nullable final String sText, final char cSearch) { return sText != null && sText.length () >= 1 ? sText.indexOf (cSearch) : STRING_NOT_FOUND; }
java
public static int getIndexOf (@Nullable final String sText, final char cSearch) { return sText != null && sText.length () >= 1 ? sText.indexOf (cSearch) : STRING_NOT_FOUND; }
[ "public", "static", "int", "getIndexOf", "(", "@", "Nullable", "final", "String", "sText", ",", "final", "char", "cSearch", ")", "{", "return", "sText", "!=", "null", "&&", "sText", ".", "length", "(", ")", ">=", "1", "?", "sText", ".", "indexOf", "(",...
Get the first index of cSearch within sText. @param sText The text to search in. May be <code>null</code>. @param cSearch The character to search for. May be <code>null</code>. @return The first index of sSearch within sText or {@value #STRING_NOT_FOUND} if cSearch was not found or if any parameter was <code>null</code>. @see String#indexOf(int)
[ "Get", "the", "first", "index", "of", "cSearch", "within", "sText", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L2755-L2758
jenkinsci/jenkins
core/src/main/java/jenkins/util/JSONSignatureValidator.java
JSONSignatureValidator.checkSpecificSignature
private FormValidation checkSpecificSignature(JSONObject json, JSONObject signatureJson, MessageDigest digest, String digestEntry, Signature signature, String signatureEntry, String digestName) throws IOException { // this is for computing a digest to check sanity DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), digest); SignatureOutputStream sos = new SignatureOutputStream(signature); String providedDigest = signatureJson.optString(digestEntry, null); if (providedDigest == null) { return FormValidation.warning("No '" + digestEntry + "' found"); } String providedSignature = signatureJson.optString(signatureEntry, null); if (providedSignature == null) { return FormValidation.warning("No '" + signatureEntry + "' found"); } // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature) // that only covers the earlier portion of the file. This was caused by the lack of close() call // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to // the digest output stream. This affects Jenkins [1.424,1,431]. // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it // compute the correct digest, but it breaks all the existing UC json metadata out there. We then // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature, // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*). // // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature" // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated // correctly. // // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows // the attacker to inject a fragment at the end of the json. json.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos,sos), Charsets.UTF_8)).close(); // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n // (which is more likely than someone tampering with update center), we can tell if (!digestMatches(digest.digest(), providedDigest)) { String msg = digestName + " digest mismatch: expected=" + providedDigest + " in '" + name + "'"; if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(msg); LOGGER.severe(json.toString(2)); } return FormValidation.error(msg); } if (!verifySignature(signature, providedSignature)) { return FormValidation.error(digestName + " based signature in the update center doesn't match with the certificate in '"+name + "'"); } return FormValidation.ok(); }
java
private FormValidation checkSpecificSignature(JSONObject json, JSONObject signatureJson, MessageDigest digest, String digestEntry, Signature signature, String signatureEntry, String digestName) throws IOException { // this is for computing a digest to check sanity DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), digest); SignatureOutputStream sos = new SignatureOutputStream(signature); String providedDigest = signatureJson.optString(digestEntry, null); if (providedDigest == null) { return FormValidation.warning("No '" + digestEntry + "' found"); } String providedSignature = signatureJson.optString(signatureEntry, null); if (providedSignature == null) { return FormValidation.warning("No '" + signatureEntry + "' found"); } // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature) // that only covers the earlier portion of the file. This was caused by the lack of close() call // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to // the digest output stream. This affects Jenkins [1.424,1,431]. // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it // compute the correct digest, but it breaks all the existing UC json metadata out there. We then // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature, // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*). // // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature" // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated // correctly. // // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows // the attacker to inject a fragment at the end of the json. json.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos,sos), Charsets.UTF_8)).close(); // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n // (which is more likely than someone tampering with update center), we can tell if (!digestMatches(digest.digest(), providedDigest)) { String msg = digestName + " digest mismatch: expected=" + providedDigest + " in '" + name + "'"; if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(msg); LOGGER.severe(json.toString(2)); } return FormValidation.error(msg); } if (!verifySignature(signature, providedSignature)) { return FormValidation.error(digestName + " based signature in the update center doesn't match with the certificate in '"+name + "'"); } return FormValidation.ok(); }
[ "private", "FormValidation", "checkSpecificSignature", "(", "JSONObject", "json", ",", "JSONObject", "signatureJson", ",", "MessageDigest", "digest", ",", "String", "digestEntry", ",", "Signature", "signature", ",", "String", "signatureEntry", ",", "String", "digestName...
Computes the specified {@code digest} and {@code signature} for the provided {@code json} object and checks whether they match {@code digestEntry} and {@signatureEntry} in the provided {@code signatureJson} object. @param json the full update-center.json content @param signatureJson signature block from update-center.json @param digest digest to compute @param digestEntry key of the digest entry in {@code signatureJson} to check @param signature signature to compute @param signatureEntry key of the signature entry in {@code signatureJson} to check @param digestName name of the digest used for log/error messages @return {@link FormValidation.Kind#WARNING} if digest or signature are not provided, {@link FormValidation.Kind#OK} if check is successful, {@link FormValidation.Kind#ERROR} otherwise. @throws IOException if this somehow fails to write the canonical JSON representation to an in-memory stream.
[ "Computes", "the", "specified", "{", "@code", "digest", "}", "and", "{", "@code", "signature", "}", "for", "the", "provided", "{", "@code", "json", "}", "object", "and", "checks", "whether", "they", "match", "{", "@code", "digestEntry", "}", "and", "{", ...
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/util/JSONSignatureValidator.java#L155-L204
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java
TemperatureConversion.convertToKelvin
public static double convertToKelvin(TemperatureScale from, double temperature) { switch(from) { case FARENHEIT: return convertFarenheitToKelvin(temperature); case CELSIUS: return convertCelsiusToKelvin(temperature); case KELVIN: return temperature; case RANKINE: return convertRankineToKelvin(temperature); default: throw(new RuntimeException("Invalid termpature conversion")); } }
java
public static double convertToKelvin(TemperatureScale from, double temperature) { switch(from) { case FARENHEIT: return convertFarenheitToKelvin(temperature); case CELSIUS: return convertCelsiusToKelvin(temperature); case KELVIN: return temperature; case RANKINE: return convertRankineToKelvin(temperature); default: throw(new RuntimeException("Invalid termpature conversion")); } }
[ "public", "static", "double", "convertToKelvin", "(", "TemperatureScale", "from", ",", "double", "temperature", ")", "{", "switch", "(", "from", ")", "{", "case", "FARENHEIT", ":", "return", "convertFarenheitToKelvin", "(", "temperature", ")", ";", "case", "CELS...
Convert a temperature value from another temperature scale into the Kelvin temperature scale. @param from TemperatureScale @param temperature value from other scale @return converted temperature value in Kelvin
[ "Convert", "a", "temperature", "value", "from", "another", "temperature", "scale", "into", "the", "Kelvin", "temperature", "scale", "." ]
train
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L193-L208
kaazing/gateway
transport/http/src/main/java/org/kaazing/gateway/transport/http/HttpUtils.java
HttpUtils.getRequestURI
public static URI getRequestURI(HttpRequestMessage request, IoSession session) { URI requestURI = request.getRequestURI(); String host = request.getHeader("Host"); return getRequestURI(requestURI, host, session); }
java
public static URI getRequestURI(HttpRequestMessage request, IoSession session) { URI requestURI = request.getRequestURI(); String host = request.getHeader("Host"); return getRequestURI(requestURI, host, session); }
[ "public", "static", "URI", "getRequestURI", "(", "HttpRequestMessage", "request", ",", "IoSession", "session", ")", "{", "URI", "requestURI", "=", "request", ".", "getRequestURI", "(", ")", ";", "String", "host", "=", "request", ".", "getHeader", "(", "\"Host\...
constructs an http specific request uri with host, port (or explicit default port), and path
[ "constructs", "an", "http", "specific", "request", "uri", "with", "host", "port", "(", "or", "explicit", "default", "port", ")", "and", "path" ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/transport/http/src/main/java/org/kaazing/gateway/transport/http/HttpUtils.java#L390-L394
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/raw/DataDecoder.java
DataDecoder.decodeSingle
public static byte[] decodeSingle(byte[] src, int prefixPadding, int suffixPadding) throws CorruptEncodingException { try { int length = src.length - suffixPadding - prefixPadding; if (length == 0) { return EMPTY_BYTE_ARRAY; } if (prefixPadding <= 0 && suffixPadding <= 0) { // Always return a new byte array instance return src.clone(); } byte[] dst = new byte[length]; System.arraycopy(src, prefixPadding, dst, 0, length); return dst; } catch (IndexOutOfBoundsException e) { throw new CorruptEncodingException(null, e); } }
java
public static byte[] decodeSingle(byte[] src, int prefixPadding, int suffixPadding) throws CorruptEncodingException { try { int length = src.length - suffixPadding - prefixPadding; if (length == 0) { return EMPTY_BYTE_ARRAY; } if (prefixPadding <= 0 && suffixPadding <= 0) { // Always return a new byte array instance return src.clone(); } byte[] dst = new byte[length]; System.arraycopy(src, prefixPadding, dst, 0, length); return dst; } catch (IndexOutOfBoundsException e) { throw new CorruptEncodingException(null, e); } }
[ "public", "static", "byte", "[", "]", "decodeSingle", "(", "byte", "[", "]", "src", ",", "int", "prefixPadding", ",", "int", "suffixPadding", ")", "throws", "CorruptEncodingException", "{", "try", "{", "int", "length", "=", "src", ".", "length", "-", "suff...
Decodes the given byte array which was encoded by {@link DataEncoder#encodeSingle}. Always returns a new byte array instance. @param prefixPadding amount of extra bytes to skip from start of encoded byte array @param suffixPadding amount of extra bytes to skip at end of encoded byte array
[ "Decodes", "the", "given", "byte", "array", "which", "was", "encoded", "by", "{", "@link", "DataEncoder#encodeSingle", "}", ".", "Always", "returns", "a", "new", "byte", "array", "instance", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/raw/DataDecoder.java#L666-L684
aws/aws-sdk-java
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/StepExecution.java
StepExecution.withOverriddenParameters
public StepExecution withOverriddenParameters(java.util.Map<String, java.util.List<String>> overriddenParameters) { setOverriddenParameters(overriddenParameters); return this; }
java
public StepExecution withOverriddenParameters(java.util.Map<String, java.util.List<String>> overriddenParameters) { setOverriddenParameters(overriddenParameters); return this; }
[ "public", "StepExecution", "withOverriddenParameters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "java", ".", "util", ".", "List", "<", "String", ">", ">", "overriddenParameters", ")", "{", "setOverriddenParameters", "(", "overriddenParameters", ...
<p> A user-specified list of parameters to override when running a step. </p> @param overriddenParameters A user-specified list of parameters to override when running a step. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "user", "-", "specified", "list", "of", "parameters", "to", "override", "when", "running", "a", "step", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/StepExecution.java#L901-L904
j256/ormlite-core
src/main/java/com/j256/ormlite/misc/TransactionManager.java
TransactionManager.callInTransaction
public <T> T callInTransaction(String tableName, final Callable<T> callable) throws SQLException { return callInTransaction(tableName, connectionSource, callable); }
java
public <T> T callInTransaction(String tableName, final Callable<T> callable) throws SQLException { return callInTransaction(tableName, connectionSource, callable); }
[ "public", "<", "T", ">", "T", "callInTransaction", "(", "String", "tableName", ",", "final", "Callable", "<", "T", ">", "callable", ")", "throws", "SQLException", "{", "return", "callInTransaction", "(", "tableName", ",", "connectionSource", ",", "callable", "...
Same as {@link #callInTransaction(Callable)} except as a this has a table-name specified. <p> WARNING: it is up to you to properly synchronize around this method if multiple threads are using a connection-source which works gives out a single-connection. The reason why this is necessary is that multiple operations are performed on the connection and race-conditions will exist with multiple threads working on the same connection. </p>
[ "Same", "as", "{", "@link", "#callInTransaction", "(", "Callable", ")", "}", "except", "as", "a", "this", "has", "a", "table", "-", "name", "specified", "." ]
train
https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/misc/TransactionManager.java#L142-L144
fernandospr/java-wns
src/main/java/ar/com/fernandospr/wns/WnsService.java
WnsService.pushBadge
public List<WnsNotificationResponse> pushBadge(List<String> channelUris, WnsBadge badge) throws WnsException { return this.pushBadge(channelUris, null, badge); }
java
public List<WnsNotificationResponse> pushBadge(List<String> channelUris, WnsBadge badge) throws WnsException { return this.pushBadge(channelUris, null, badge); }
[ "public", "List", "<", "WnsNotificationResponse", ">", "pushBadge", "(", "List", "<", "String", ">", "channelUris", ",", "WnsBadge", "badge", ")", "throws", "WnsException", "{", "return", "this", ".", "pushBadge", "(", "channelUris", ",", "null", ",", "badge",...
Pushes a badge to channelUris @param channelUris @param badge which should be built with {@link ar.com.fernandospr.wns.model.builders.WnsBadgeBuilder} @return list of WnsNotificationResponse for each channelUri, please see response headers from <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465435.aspx#send_notification_response">http://msdn.microsoft.com/en-us/library/windows/apps/hh465435.aspx#send_notification_response</a> @throws WnsException when authentication fails
[ "Pushes", "a", "badge", "to", "channelUris" ]
train
https://github.com/fernandospr/java-wns/blob/cd621b9c17d1e706f6284e0913531d834904a90d/src/main/java/ar/com/fernandospr/wns/WnsService.java#L191-L193
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementToolbar.java
ElementToolbar.addToolbarComponent
public void addToolbarComponent(BaseComponent component, String action) { BaseComponent ref = toolbar.getFirstChild(); if (component instanceof Toolbar) { BaseComponent child; while ((child = component.getFirstChild()) != null) { toolbar.addChild(child, ref); } } else { toolbar.addChild(component, ref); ActionUtil.addAction(component, action); } }
java
public void addToolbarComponent(BaseComponent component, String action) { BaseComponent ref = toolbar.getFirstChild(); if (component instanceof Toolbar) { BaseComponent child; while ((child = component.getFirstChild()) != null) { toolbar.addChild(child, ref); } } else { toolbar.addChild(component, ref); ActionUtil.addAction(component, action); } }
[ "public", "void", "addToolbarComponent", "(", "BaseComponent", "component", ",", "String", "action", ")", "{", "BaseComponent", "ref", "=", "toolbar", ".", "getFirstChild", "(", ")", ";", "if", "(", "component", "instanceof", "Toolbar", ")", "{", "BaseComponent"...
Adds a component to the toolbar. @param component Component to add. If the component is a toolbar itself, its children will be added to the toolbar. @param action The action to associate with the component.
[ "Adds", "a", "component", "to", "the", "toolbar", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/elements/ElementToolbar.java#L72-L86
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlSerialMethodWriter.java
HtmlSerialMethodWriter.addMemberTags
public void addMemberTags(MethodDoc member, Content methodsContentTree) { Content tagContent = new ContentBuilder(); TagletManager tagletManager = configuration.tagletManager; TagletWriter.genTagOuput(tagletManager, member, tagletManager.getSerializedFormTaglets(), writer.getTagletWriterInstance(false), tagContent); Content dlTags = new HtmlTree(HtmlTag.DL); dlTags.addContent(tagContent); methodsContentTree.addContent(dlTags); MethodDoc method = member; if (method.name().compareTo("writeExternal") == 0 && method.tags("serialData").length == 0) { serialWarning(member.position(), "doclet.MissingSerialDataTag", method.containingClass().qualifiedName(), method.name()); } }
java
public void addMemberTags(MethodDoc member, Content methodsContentTree) { Content tagContent = new ContentBuilder(); TagletManager tagletManager = configuration.tagletManager; TagletWriter.genTagOuput(tagletManager, member, tagletManager.getSerializedFormTaglets(), writer.getTagletWriterInstance(false), tagContent); Content dlTags = new HtmlTree(HtmlTag.DL); dlTags.addContent(tagContent); methodsContentTree.addContent(dlTags); MethodDoc method = member; if (method.name().compareTo("writeExternal") == 0 && method.tags("serialData").length == 0) { serialWarning(member.position(), "doclet.MissingSerialDataTag", method.containingClass().qualifiedName(), method.name()); } }
[ "public", "void", "addMemberTags", "(", "MethodDoc", "member", ",", "Content", "methodsContentTree", ")", "{", "Content", "tagContent", "=", "new", "ContentBuilder", "(", ")", ";", "TagletManager", "tagletManager", "=", "configuration", ".", "tagletManager", ";", ...
Add the tag information for this member. @param member the method to document. @param methodsContentTree the tree to which the member tags info will be added
[ "Add", "the", "tag", "information", "for", "this", "member", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlSerialMethodWriter.java#L145-L161
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.getEntityAsync
public Observable<EntityExtractor> getEntityAsync(UUID appId, String versionId, UUID entityId) { return getEntityWithServiceResponseAsync(appId, versionId, entityId).map(new Func1<ServiceResponse<EntityExtractor>, EntityExtractor>() { @Override public EntityExtractor call(ServiceResponse<EntityExtractor> response) { return response.body(); } }); }
java
public Observable<EntityExtractor> getEntityAsync(UUID appId, String versionId, UUID entityId) { return getEntityWithServiceResponseAsync(appId, versionId, entityId).map(new Func1<ServiceResponse<EntityExtractor>, EntityExtractor>() { @Override public EntityExtractor call(ServiceResponse<EntityExtractor> response) { return response.body(); } }); }
[ "public", "Observable", "<", "EntityExtractor", ">", "getEntityAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ")", "{", "return", "getEntityWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "entityId", ")", ".", ...
Gets information about the entity model. @param appId The application ID. @param versionId The version ID. @param entityId The entity extractor ID. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the EntityExtractor object
[ "Gets", "information", "about", "the", "entity", "model", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L3312-L3319
elki-project/elki
elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/correlation/UncenteredCorrelationDistanceFunction.java
UncenteredCorrelationDistanceFunction.uncenteredCorrelation
public static double uncenteredCorrelation(double[] x, double[] y) { final int xdim = x.length, ydim = y.length; if(xdim != ydim) { throw new IllegalArgumentException("Invalid arguments: number vectors differ in dimensionality."); } double sumXX = 0., sumYY = 0., sumXY = 0.; for(int i = 0; i < xdim; i++) { final double xv = x[i], yv = y[i]; sumXX += xv * xv; sumYY += yv * yv; sumXY += xv * yv; } // One or both series were constant: if(!(sumXX > 0. && sumYY > 0.)) { return (sumXX == sumYY) ? 1. : 0.; } return sumXY / FastMath.sqrt(sumXX * sumYY); }
java
public static double uncenteredCorrelation(double[] x, double[] y) { final int xdim = x.length, ydim = y.length; if(xdim != ydim) { throw new IllegalArgumentException("Invalid arguments: number vectors differ in dimensionality."); } double sumXX = 0., sumYY = 0., sumXY = 0.; for(int i = 0; i < xdim; i++) { final double xv = x[i], yv = y[i]; sumXX += xv * xv; sumYY += yv * yv; sumXY += xv * yv; } // One or both series were constant: if(!(sumXX > 0. && sumYY > 0.)) { return (sumXX == sumYY) ? 1. : 0.; } return sumXY / FastMath.sqrt(sumXX * sumYY); }
[ "public", "static", "double", "uncenteredCorrelation", "(", "double", "[", "]", "x", ",", "double", "[", "]", "y", ")", "{", "final", "int", "xdim", "=", "x", ".", "length", ",", "ydim", "=", "y", ".", "length", ";", "if", "(", "xdim", "!=", "ydim"...
Compute the uncentered correlation of two vectors. @param x first NumberVector @param y second NumberVector @return the uncentered correlation coefficient for x and y
[ "Compute", "the", "uncentered", "correlation", "of", "two", "vectors", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/correlation/UncenteredCorrelationDistanceFunction.java#L86-L103
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfFileSpecification.java
PdfFileSpecification.fileEmbedded
public static PdfFileSpecification fileEmbedded(PdfWriter writer, String filePath, String fileDisplay, byte fileStore[], boolean compress) throws IOException { return fileEmbedded(writer, filePath, fileDisplay, fileStore, null, null, compress ? PdfStream.BEST_COMPRESSION : PdfStream.NO_COMPRESSION); }
java
public static PdfFileSpecification fileEmbedded(PdfWriter writer, String filePath, String fileDisplay, byte fileStore[], boolean compress) throws IOException { return fileEmbedded(writer, filePath, fileDisplay, fileStore, null, null, compress ? PdfStream.BEST_COMPRESSION : PdfStream.NO_COMPRESSION); }
[ "public", "static", "PdfFileSpecification", "fileEmbedded", "(", "PdfWriter", "writer", ",", "String", "filePath", ",", "String", "fileDisplay", ",", "byte", "fileStore", "[", "]", ",", "boolean", "compress", ")", "throws", "IOException", "{", "return", "fileEmbed...
Creates a file specification with the file embedded. The file may come from the file system or from a byte array. @param writer the <CODE>PdfWriter</CODE> @param filePath the file path @param fileDisplay the file information that is presented to the user @param fileStore the byte array with the file. If it is not <CODE>null</CODE> it takes precedence over <CODE>filePath</CODE> @param compress sets the compression on the data. Multimedia content will benefit little from compression @throws IOException on error @return the file specification
[ "Creates", "a", "file", "specification", "with", "the", "file", "embedded", ".", "The", "file", "may", "come", "from", "the", "file", "system", "or", "from", "a", "byte", "array", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfFileSpecification.java#L131-L133
cloudinary/cloudinary_java
cloudinary-core/src/main/java/com/cloudinary/utils/StringUtils.java
StringUtils.urlEncode
public static String urlEncode(String url, Pattern unsafe, Charset charset) { StringBuffer sb = new StringBuffer(url.length()); Matcher matcher = unsafe.matcher(url); while (matcher.find()) { String str = matcher.group(0); byte[] bytes = str.getBytes(charset); StringBuilder escaped = new StringBuilder(str.length() * 3); for (byte aByte : bytes) { escaped.append('%'); char ch = Character.forDigit((aByte >> 4) & 0xF, 16); escaped.append(ch); ch = Character.forDigit(aByte & 0xF, 16); escaped.append(ch); } matcher.appendReplacement(sb, Matcher.quoteReplacement(escaped.toString().toLowerCase())); } matcher.appendTail(sb); return sb.toString(); }
java
public static String urlEncode(String url, Pattern unsafe, Charset charset) { StringBuffer sb = new StringBuffer(url.length()); Matcher matcher = unsafe.matcher(url); while (matcher.find()) { String str = matcher.group(0); byte[] bytes = str.getBytes(charset); StringBuilder escaped = new StringBuilder(str.length() * 3); for (byte aByte : bytes) { escaped.append('%'); char ch = Character.forDigit((aByte >> 4) & 0xF, 16); escaped.append(ch); ch = Character.forDigit(aByte & 0xF, 16); escaped.append(ch); } matcher.appendReplacement(sb, Matcher.quoteReplacement(escaped.toString().toLowerCase())); } matcher.appendTail(sb); return sb.toString(); }
[ "public", "static", "String", "urlEncode", "(", "String", "url", ",", "Pattern", "unsafe", ",", "Charset", "charset", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", "url", ".", "length", "(", ")", ")", ";", "Matcher", "matcher", "=", "u...
Replaces the unsafe characters in url with url-encoded values. This is based on {@link java.net.URLEncoder#encode(String, String)} @param url The url to encode @param unsafe Regex pattern of unsafe caracters @param charset @return An encoded url string
[ "Replaces", "the", "unsafe", "characters", "in", "url", "with", "url", "-", "encoded", "values", ".", "This", "is", "based", "on", "{" ]
train
https://github.com/cloudinary/cloudinary_java/blob/58ee1823180da2dea6a2eb7e5cf00d5a760f8aef/cloudinary-core/src/main/java/com/cloudinary/utils/StringUtils.java#L223-L244
apptik/jus
android/jus-android/src/main/java/io/apptik/comm/jus/AndroidJus.java
AndroidJus.newRequestQueue
public static RequestQueue newRequestQueue(Context context, HttpStack stack) { JusLog.log = new ALog(); File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); String userAgent = "jus/0"; try { String packageName = context.getPackageName(); PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); userAgent = packageName + "/" + info.versionCode; } catch (NameNotFoundException e) { } if (stack == null) { stack = new HurlStack(); } Network network = new HttpNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network, RequestQueue.DEFAULT_NETWORK_THREAD_POOL_SIZE, new AndroidExecutorDelivery(new Handler(Looper.getMainLooper()))); queue.withCacheDispatcher( new AndroidCacheDispatcher( queue.cacheQueue, queue.networkQueue, queue.cache, queue.delivery)) .withNetworkDispatcherFactory( new AndroidNetworkDispatcher.NetworkDispatcherFactory( queue.networkQueue, queue.network, queue.cache, queue.delivery)); queue.start(); return queue; }
java
public static RequestQueue newRequestQueue(Context context, HttpStack stack) { JusLog.log = new ALog(); File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); String userAgent = "jus/0"; try { String packageName = context.getPackageName(); PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); userAgent = packageName + "/" + info.versionCode; } catch (NameNotFoundException e) { } if (stack == null) { stack = new HurlStack(); } Network network = new HttpNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network, RequestQueue.DEFAULT_NETWORK_THREAD_POOL_SIZE, new AndroidExecutorDelivery(new Handler(Looper.getMainLooper()))); queue.withCacheDispatcher( new AndroidCacheDispatcher( queue.cacheQueue, queue.networkQueue, queue.cache, queue.delivery)) .withNetworkDispatcherFactory( new AndroidNetworkDispatcher.NetworkDispatcherFactory( queue.networkQueue, queue.network, queue.cache, queue.delivery)); queue.start(); return queue; }
[ "public", "static", "RequestQueue", "newRequestQueue", "(", "Context", "context", ",", "HttpStack", "stack", ")", "{", "JusLog", ".", "log", "=", "new", "ALog", "(", ")", ";", "File", "cacheDir", "=", "new", "File", "(", "context", ".", "getCacheDir", "(",...
Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. @param context A {@link Context} to use for creating the cache dir. @param stack An {@link HttpStack} to use for the network, or null for default. @return A started {@link RequestQueue} instance.
[ "Creates", "a", "default", "instance", "of", "the", "worker", "pool", "and", "calls", "{", "@link", "RequestQueue#start", "()", "}", "on", "it", "." ]
train
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/android/jus-android/src/main/java/io/apptik/comm/jus/AndroidJus.java#L46-L77
UrielCh/ovh-java-sdk
ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java
ApiOvhIpLoadbalancing.serviceName_http_farm_POST
public OvhBackendHttp serviceName_http_farm_POST(String serviceName, OvhBalanceHTTPEnum balance, String displayName, Long port, OvhBackendProbe probe, OvhStickinessHTTPEnum stickiness, Long vrackNetworkId, String zone) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/http/farm"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "balance", balance); addBody(o, "displayName", displayName); addBody(o, "port", port); addBody(o, "probe", probe); addBody(o, "stickiness", stickiness); addBody(o, "vrackNetworkId", vrackNetworkId); addBody(o, "zone", zone); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhBackendHttp.class); }
java
public OvhBackendHttp serviceName_http_farm_POST(String serviceName, OvhBalanceHTTPEnum balance, String displayName, Long port, OvhBackendProbe probe, OvhStickinessHTTPEnum stickiness, Long vrackNetworkId, String zone) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/http/farm"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "balance", balance); addBody(o, "displayName", displayName); addBody(o, "port", port); addBody(o, "probe", probe); addBody(o, "stickiness", stickiness); addBody(o, "vrackNetworkId", vrackNetworkId); addBody(o, "zone", zone); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhBackendHttp.class); }
[ "public", "OvhBackendHttp", "serviceName_http_farm_POST", "(", "String", "serviceName", ",", "OvhBalanceHTTPEnum", "balance", ",", "String", "displayName", ",", "Long", "port", ",", "OvhBackendProbe", "probe", ",", "OvhStickinessHTTPEnum", "stickiness", ",", "Long", "vr...
Add a new HTTP Farm on your IP Load Balancing REST: POST /ipLoadbalancing/{serviceName}/http/farm @param zone [required] Zone of your farm @param balance [required] Load balancing algorithm. 'roundrobin' if null @param stickiness [required] Stickiness type. No stickiness if null @param probe [required] Probe used to determine if a backend is alive and can handle requests @param vrackNetworkId [required] Internal Load Balancer identifier of the vRack private network to attach to your farm, mandatory when your Load Balancer is attached to a vRack @param displayName [required] Human readable name for your backend, this field is for you @param port [required] Port attached to your farm ([1..49151]). Inherited from frontend if null @param serviceName [required] The internal name of your IP load balancing
[ "Add", "a", "new", "HTTP", "Farm", "on", "your", "IP", "Load", "Balancing" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/ApiOvhIpLoadbalancing.java#L529-L542
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java
BaseDataPublisher.publishMetadata
@Override public void publishMetadata(Collection<? extends WorkUnitState> states) throws IOException { Set<String> partitions = new HashSet<>(); // There should be one merged metadata file per branch; first merge all of the pieces together mergeMetadataAndCollectPartitionNames(states, partitions); partitions.removeIf(Objects::isNull); // Now, pick an arbitrary WorkUnitState to get config information around metadata such as // the desired output filename. We assume that publisher config settings // are the same across all workunits so it doesn't really matter which workUnit we retrieve this information // from. WorkUnitState anyState = states.iterator().next(); for (int branchId = 0; branchId < numBranches; branchId++) { String mdOutputPath = getMetadataOutputPathFromState(anyState, branchId); String userSpecifiedPath = getUserSpecifiedOutputPathFromState(anyState, branchId); if (partitions.isEmpty() || userSpecifiedPath != null) { publishMetadata(getMergedMetadataForPartitionAndBranch(null, branchId), branchId, getMetadataOutputFileForBranch(anyState, branchId)); } else { String metadataFilename = getMetadataFileNameForBranch(anyState, branchId); if (mdOutputPath == null || metadataFilename == null) { LOG.info("Metadata filename not set for branch " + String.valueOf(branchId) + ": not publishing metadata."); continue; } for (String partition : partitions) { publishMetadata(getMergedMetadataForPartitionAndBranch(partition, branchId), branchId, new Path(new Path(mdOutputPath, partition), metadataFilename)); } } } }
java
@Override public void publishMetadata(Collection<? extends WorkUnitState> states) throws IOException { Set<String> partitions = new HashSet<>(); // There should be one merged metadata file per branch; first merge all of the pieces together mergeMetadataAndCollectPartitionNames(states, partitions); partitions.removeIf(Objects::isNull); // Now, pick an arbitrary WorkUnitState to get config information around metadata such as // the desired output filename. We assume that publisher config settings // are the same across all workunits so it doesn't really matter which workUnit we retrieve this information // from. WorkUnitState anyState = states.iterator().next(); for (int branchId = 0; branchId < numBranches; branchId++) { String mdOutputPath = getMetadataOutputPathFromState(anyState, branchId); String userSpecifiedPath = getUserSpecifiedOutputPathFromState(anyState, branchId); if (partitions.isEmpty() || userSpecifiedPath != null) { publishMetadata(getMergedMetadataForPartitionAndBranch(null, branchId), branchId, getMetadataOutputFileForBranch(anyState, branchId)); } else { String metadataFilename = getMetadataFileNameForBranch(anyState, branchId); if (mdOutputPath == null || metadataFilename == null) { LOG.info("Metadata filename not set for branch " + String.valueOf(branchId) + ": not publishing metadata."); continue; } for (String partition : partitions) { publishMetadata(getMergedMetadataForPartitionAndBranch(partition, branchId), branchId, new Path(new Path(mdOutputPath, partition), metadataFilename)); } } } }
[ "@", "Override", "public", "void", "publishMetadata", "(", "Collection", "<", "?", "extends", "WorkUnitState", ">", "states", ")", "throws", "IOException", "{", "Set", "<", "String", ">", "partitions", "=", "new", "HashSet", "<>", "(", ")", ";", "// There sh...
Merge all of the metadata output from each work-unit and publish the merged record. @param states States from all tasks @throws IOException If there is an error publishing the file
[ "Merge", "all", "of", "the", "metadata", "output", "from", "each", "work", "-", "unit", "and", "publish", "the", "merged", "record", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java#L539-L576
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/BorderLayoutExample.java
BorderLayoutExample.createPanelWithText
private WPanel createPanelWithText(final String title, final String text) { WPanel panel = new WPanel(WPanel.Type.CHROME); panel.setTitleText(title); WText textComponent = new WText(text); textComponent.setEncodeText(false); panel.add(textComponent); return panel; }
java
private WPanel createPanelWithText(final String title, final String text) { WPanel panel = new WPanel(WPanel.Type.CHROME); panel.setTitleText(title); WText textComponent = new WText(text); textComponent.setEncodeText(false); panel.add(textComponent); return panel; }
[ "private", "WPanel", "createPanelWithText", "(", "final", "String", "title", ",", "final", "String", "text", ")", "{", "WPanel", "panel", "=", "new", "WPanel", "(", "WPanel", ".", "Type", ".", "CHROME", ")", ";", "panel", ".", "setTitleText", "(", "title",...
Convenience method to create a WPanel with the given title and text. @param title the panel title. @param text the panel text. @return a new WPanel with the given title and text.
[ "Convenience", "method", "to", "create", "a", "WPanel", "with", "the", "given", "title", "and", "text", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/layout/BorderLayoutExample.java#L148-L156
jcuda/jcusparse
JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java
JCusparse.cusparseSgebsr2gebsr_bufferSize
public static int cusparseSgebsr2gebsr_bufferSize( cusparseHandle handle, int dirA, int mb, int nb, int nnzb, cusparseMatDescr descrA, Pointer bsrSortedValA, Pointer bsrSortedRowPtrA, Pointer bsrSortedColIndA, int rowBlockDimA, int colBlockDimA, int rowBlockDimC, int colBlockDimC, int[] pBufferSizeInBytes) { return checkResult(cusparseSgebsr2gebsr_bufferSizeNative(handle, dirA, mb, nb, nnzb, descrA, bsrSortedValA, bsrSortedRowPtrA, bsrSortedColIndA, rowBlockDimA, colBlockDimA, rowBlockDimC, colBlockDimC, pBufferSizeInBytes)); }
java
public static int cusparseSgebsr2gebsr_bufferSize( cusparseHandle handle, int dirA, int mb, int nb, int nnzb, cusparseMatDescr descrA, Pointer bsrSortedValA, Pointer bsrSortedRowPtrA, Pointer bsrSortedColIndA, int rowBlockDimA, int colBlockDimA, int rowBlockDimC, int colBlockDimC, int[] pBufferSizeInBytes) { return checkResult(cusparseSgebsr2gebsr_bufferSizeNative(handle, dirA, mb, nb, nnzb, descrA, bsrSortedValA, bsrSortedRowPtrA, bsrSortedColIndA, rowBlockDimA, colBlockDimA, rowBlockDimC, colBlockDimC, pBufferSizeInBytes)); }
[ "public", "static", "int", "cusparseSgebsr2gebsr_bufferSize", "(", "cusparseHandle", "handle", ",", "int", "dirA", ",", "int", "mb", ",", "int", "nb", ",", "int", "nnzb", ",", "cusparseMatDescr", "descrA", ",", "Pointer", "bsrSortedValA", ",", "Pointer", "bsrSor...
Description: This routine converts a sparse matrix in general block-CSR storage format to a sparse matrix in general block-CSR storage format with different block size.
[ "Description", ":", "This", "routine", "converts", "a", "sparse", "matrix", "in", "general", "block", "-", "CSR", "storage", "format", "to", "a", "sparse", "matrix", "in", "general", "block", "-", "CSR", "storage", "format", "with", "different", "block", "si...
train
https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L13614-L13631
beangle/beangle3
commons/core/src/main/java/org/beangle/commons/lang/Strings.java
Strings.indexOf
private static int indexOf(CharSequence cs, CharSequence searchChar, int start) { return cs.toString().indexOf(searchChar.toString(), start); }
java
private static int indexOf(CharSequence cs, CharSequence searchChar, int start) { return cs.toString().indexOf(searchChar.toString(), start); }
[ "private", "static", "int", "indexOf", "(", "CharSequence", "cs", ",", "CharSequence", "searchChar", ",", "int", "start", ")", "{", "return", "cs", ".", "toString", "(", ")", ".", "indexOf", "(", "searchChar", ".", "toString", "(", ")", ",", "start", ")"...
Returns index of searchChar in cs with begin index {@code start} @param searchChar @param start
[ "Returns", "index", "of", "searchChar", "in", "cs", "with", "begin", "index", "{", "@code", "start", "}" ]
train
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/lang/Strings.java#L202-L204
h2oai/h2o-3
h2o-core/src/main/java/water/api/MetadataHandler.java
MetadataHandler.listRoutes
@SuppressWarnings("unused") // called through reflection by RequestServer public MetadataV3 listRoutes(int version, MetadataV3 docs) { MarkdownBuilder builder = new MarkdownBuilder(); builder.comment("Preview with http://jbt.github.io/markdown-editor"); builder.heading1("REST API Routes Table of Contents"); builder.hline(); builder.tableHeader("HTTP method", "URI pattern", "Input schema", "Output schema", "Summary"); docs.routes = new RouteV3[RequestServer.numRoutes()]; int i = 0; for (Route route : RequestServer.routes()) { RouteV3 schema = new RouteV3(route); docs.routes[i] = schema; // ModelBuilder input / output schema hackery MetadataV3 look = new MetadataV3(); look.routes = new RouteV3[1]; look.routes[0] = schema; look.path = route._url; look.http_method = route._http_method; fetchRoute(version, look); schema.input_schema = look.routes[0].input_schema; schema.output_schema = look.routes[0].output_schema; builder.tableRow( route._http_method, route._url, Handler.getHandlerMethodInputSchema(route._handler_method).getSimpleName(), Handler.getHandlerMethodOutputSchema(route._handler_method).getSimpleName(), route._summary); i++; } docs.markdown = builder.toString(); return docs; }
java
@SuppressWarnings("unused") // called through reflection by RequestServer public MetadataV3 listRoutes(int version, MetadataV3 docs) { MarkdownBuilder builder = new MarkdownBuilder(); builder.comment("Preview with http://jbt.github.io/markdown-editor"); builder.heading1("REST API Routes Table of Contents"); builder.hline(); builder.tableHeader("HTTP method", "URI pattern", "Input schema", "Output schema", "Summary"); docs.routes = new RouteV3[RequestServer.numRoutes()]; int i = 0; for (Route route : RequestServer.routes()) { RouteV3 schema = new RouteV3(route); docs.routes[i] = schema; // ModelBuilder input / output schema hackery MetadataV3 look = new MetadataV3(); look.routes = new RouteV3[1]; look.routes[0] = schema; look.path = route._url; look.http_method = route._http_method; fetchRoute(version, look); schema.input_schema = look.routes[0].input_schema; schema.output_schema = look.routes[0].output_schema; builder.tableRow( route._http_method, route._url, Handler.getHandlerMethodInputSchema(route._handler_method).getSimpleName(), Handler.getHandlerMethodOutputSchema(route._handler_method).getSimpleName(), route._summary); i++; } docs.markdown = builder.toString(); return docs; }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "// called through reflection by RequestServer", "public", "MetadataV3", "listRoutes", "(", "int", "version", ",", "MetadataV3", "docs", ")", "{", "MarkdownBuilder", "builder", "=", "new", "MarkdownBuilder", "(", ")", "...
Return a list of all REST API Routes and a Markdown Table of Contents.
[ "Return", "a", "list", "of", "all", "REST", "API", "Routes", "and", "a", "Markdown", "Table", "of", "Contents", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/api/MetadataHandler.java#L25-L62
datumbox/datumbox-framework
datumbox-framework-common/src/main/java/com/datumbox/framework/common/concurrency/ThreadMethods.java
ThreadMethods.throttledExecution
public static <T> void throttledExecution(Stream<T> stream, Consumer<T> consumer, ConcurrencyConfiguration concurrencyConfiguration) { if(concurrencyConfiguration.isParallelized()) { int maxThreads = concurrencyConfiguration.getMaxNumberOfThreadsPerTask(); int maxTasks = 2*maxThreads; ExecutorService executorService = Executors.newFixedThreadPool(maxThreads); ThrottledExecutor executor = new ThrottledExecutor(executorService, maxTasks); stream.sequential().forEach(i -> { executor.execute(() -> { consumer.accept(i); }); }); executorService.shutdown(); try { executorService.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } else { Runnable runnable = () -> stream.forEach(consumer); runnable.run(); } }
java
public static <T> void throttledExecution(Stream<T> stream, Consumer<T> consumer, ConcurrencyConfiguration concurrencyConfiguration) { if(concurrencyConfiguration.isParallelized()) { int maxThreads = concurrencyConfiguration.getMaxNumberOfThreadsPerTask(); int maxTasks = 2*maxThreads; ExecutorService executorService = Executors.newFixedThreadPool(maxThreads); ThrottledExecutor executor = new ThrottledExecutor(executorService, maxTasks); stream.sequential().forEach(i -> { executor.execute(() -> { consumer.accept(i); }); }); executorService.shutdown(); try { executorService.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } else { Runnable runnable = () -> stream.forEach(consumer); runnable.run(); } }
[ "public", "static", "<", "T", ">", "void", "throttledExecution", "(", "Stream", "<", "T", ">", "stream", ",", "Consumer", "<", "T", ">", "consumer", ",", "ConcurrencyConfiguration", "concurrencyConfiguration", ")", "{", "if", "(", "concurrencyConfiguration", "."...
Takes the items of the stream in a throttled way and provides them to the consumer. It uses as many threads as the available processors and it does not start more tasks than 2 times the previous number. @param <T> @param stream @param consumer @param concurrencyConfiguration
[ "Takes", "the", "items", "of", "the", "stream", "in", "a", "throttled", "way", "and", "provides", "them", "to", "the", "consumer", ".", "It", "uses", "as", "many", "threads", "as", "the", "available", "processors", "and", "it", "does", "not", "start", "m...
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-common/src/main/java/com/datumbox/framework/common/concurrency/ThreadMethods.java#L39-L65
groovy/groovy-core
src/main/org/codehaus/groovy/runtime/typehandling/NumberMath.java
NumberMath.getMath
public static NumberMath getMath(Number left, Number right) { if (isFloatingPoint(left) || isFloatingPoint(right)) { return FloatingPointMath.INSTANCE; } if (isBigDecimal(left) || isBigDecimal(right)) { return BigDecimalMath.INSTANCE; } if (isBigInteger(left) || isBigInteger(right)) { return BigIntegerMath.INSTANCE; } if (isLong(left) || isLong(right)){ return LongMath.INSTANCE; } return IntegerMath.INSTANCE; }
java
public static NumberMath getMath(Number left, Number right) { if (isFloatingPoint(left) || isFloatingPoint(right)) { return FloatingPointMath.INSTANCE; } if (isBigDecimal(left) || isBigDecimal(right)) { return BigDecimalMath.INSTANCE; } if (isBigInteger(left) || isBigInteger(right)) { return BigIntegerMath.INSTANCE; } if (isLong(left) || isLong(right)){ return LongMath.INSTANCE; } return IntegerMath.INSTANCE; }
[ "public", "static", "NumberMath", "getMath", "(", "Number", "left", ",", "Number", "right", ")", "{", "if", "(", "isFloatingPoint", "(", "left", ")", "||", "isFloatingPoint", "(", "right", ")", ")", "{", "return", "FloatingPointMath", ".", "INSTANCE", ";", ...
Determine which NumberMath instance to use, given the supplied operands. This method implements the type promotion rules discussed in the documentation. Note that by the time this method is called, any Byte, Character or Short operands will have been promoted to Integer. For reference, here is the promotion matrix: bD bI D F L I bD bD bD D D bD bD bI bD bI D D bI bI D D D D D D D F D D D D D D L bD bI D D L L I bD bI D D L I Note that for division, if either operand isFloatingPoint, the result will be floating. Otherwise, the result is BigDecimal
[ "Determine", "which", "NumberMath", "instance", "to", "use", "given", "the", "supplied", "operands", ".", "This", "method", "implements", "the", "type", "promotion", "rules", "discussed", "in", "the", "documentation", ".", "Note", "that", "by", "the", "time", ...
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/runtime/typehandling/NumberMath.java#L190-L204
jmxtrans/jmxtrans
jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/OpenTSDBGenericWriter.java
OpenTSDBGenericWriter.internalWrite
@Override public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { this.startOutput(); for (String formattedResult : messageFormatter.formatResults(results, server)) { log.debug("Sending result: {}", formattedResult); this.sendOutput(formattedResult); } this.finishOutput(); }
java
@Override public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { this.startOutput(); for (String formattedResult : messageFormatter.formatResults(results, server)) { log.debug("Sending result: {}", formattedResult); this.sendOutput(formattedResult); } this.finishOutput(); }
[ "@", "Override", "public", "void", "internalWrite", "(", "Server", "server", ",", "Query", "query", ",", "ImmutableList", "<", "Result", ">", "results", ")", "throws", "Exception", "{", "this", ".", "startOutput", "(", ")", ";", "for", "(", "String", "form...
Write the results of the query. @param server @param query - the query and its results. @param results
[ "Write", "the", "results", "of", "the", "query", "." ]
train
https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/OpenTSDBGenericWriter.java#L144-L152
casmi/casmi
src/main/java/casmi/graphics/element/Lines.java
Lines.setCornerColor
public void setCornerColor(int index, Color color) { if (!cornerGradation) { cornerGradation = true; } colors.set(index, color); }
java
public void setCornerColor(int index, Color color) { if (!cornerGradation) { cornerGradation = true; } colors.set(index, color); }
[ "public", "void", "setCornerColor", "(", "int", "index", ",", "Color", "color", ")", "{", "if", "(", "!", "cornerGradation", ")", "{", "cornerGradation", "=", "true", ";", "}", "colors", ".", "set", "(", "index", ",", "color", ")", ";", "}" ]
Sets the point's color for gradation. @param index The index number of the point. @param color The color of the point.
[ "Sets", "the", "point", "s", "color", "for", "gradation", "." ]
train
https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/element/Lines.java#L309-L314
samskivert/samskivert
src/main/java/com/samskivert/swing/LabelSausage.java
LabelSausage.layout
protected void layout (Graphics2D gfx, int iconPadding, int extraPadding) { // if we have an icon, let that dictate our size; otherwise just lay out our label all on // one line int sqwid, sqhei; if (_icon == null) { sqwid = sqhei = 0; } else { sqwid = _icon.getIconWidth(); sqhei = _icon.getIconHeight(); _label.setTargetHeight(sqhei); } // lay out our label _label.layout(gfx); Dimension lsize = _label.getSize(); // if we have no icon, make sure that the label has enough room if (_icon == null) { sqhei = lsize.height + extraPadding * 2; sqwid = extraPadding * 2; } // compute the diameter of the circle that perfectly encompasses our icon int hhei = sqhei / 2; int hwid = sqwid / 2; _dia = (int) (Math.sqrt(hwid * hwid + hhei * hhei) * 2); // compute the x and y offsets at which we'll start rendering _xoff = (_dia - sqwid) / 2; _yoff = (_dia - sqhei) / 2; // and for the label _lxoff = _dia - _xoff; _lyoff = (_dia - lsize.height) / 2; // now compute our closed and open sizes _size.height = _dia; // width is the diameter of the circle that contains the icon plus space for the label when // we're open _size.width = _dia + lsize.width + _xoff; // and if we are actually rendering the icon, we need to account for the space between it // and the label. if (_icon != null) { // and add the padding needed for the icon _size.width += _xoff + (iconPadding * 2); _xoff += iconPadding; _lxoff += iconPadding * 2; } }
java
protected void layout (Graphics2D gfx, int iconPadding, int extraPadding) { // if we have an icon, let that dictate our size; otherwise just lay out our label all on // one line int sqwid, sqhei; if (_icon == null) { sqwid = sqhei = 0; } else { sqwid = _icon.getIconWidth(); sqhei = _icon.getIconHeight(); _label.setTargetHeight(sqhei); } // lay out our label _label.layout(gfx); Dimension lsize = _label.getSize(); // if we have no icon, make sure that the label has enough room if (_icon == null) { sqhei = lsize.height + extraPadding * 2; sqwid = extraPadding * 2; } // compute the diameter of the circle that perfectly encompasses our icon int hhei = sqhei / 2; int hwid = sqwid / 2; _dia = (int) (Math.sqrt(hwid * hwid + hhei * hhei) * 2); // compute the x and y offsets at which we'll start rendering _xoff = (_dia - sqwid) / 2; _yoff = (_dia - sqhei) / 2; // and for the label _lxoff = _dia - _xoff; _lyoff = (_dia - lsize.height) / 2; // now compute our closed and open sizes _size.height = _dia; // width is the diameter of the circle that contains the icon plus space for the label when // we're open _size.width = _dia + lsize.width + _xoff; // and if we are actually rendering the icon, we need to account for the space between it // and the label. if (_icon != null) { // and add the padding needed for the icon _size.width += _xoff + (iconPadding * 2); _xoff += iconPadding; _lxoff += iconPadding * 2; } }
[ "protected", "void", "layout", "(", "Graphics2D", "gfx", ",", "int", "iconPadding", ",", "int", "extraPadding", ")", "{", "// if we have an icon, let that dictate our size; otherwise just lay out our label all on", "// one line", "int", "sqwid", ",", "sqhei", ";", "if", "...
Lays out the label sausage. It is assumed that the desired label font is already set in the label. @param iconPadding the number of pixels in the x direction to pad around the icon.
[ "Lays", "out", "the", "label", "sausage", ".", "It", "is", "assumed", "that", "the", "desired", "label", "font", "is", "already", "set", "in", "the", "label", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/LabelSausage.java#L46-L98
JM-Lab/utils-elasticsearch
src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchSearchAndCount.java
JMElasticsearchSearchAndCount.countQuery
public long countQuery(SearchRequestBuilder countRequestBuilder, long timeoutMillis) { countRequestBuilder.setSize(0); return searchQuery("countQuery", countRequestBuilder, timeoutMillis) .getHits().getTotalHits(); }
java
public long countQuery(SearchRequestBuilder countRequestBuilder, long timeoutMillis) { countRequestBuilder.setSize(0); return searchQuery("countQuery", countRequestBuilder, timeoutMillis) .getHits().getTotalHits(); }
[ "public", "long", "countQuery", "(", "SearchRequestBuilder", "countRequestBuilder", ",", "long", "timeoutMillis", ")", "{", "countRequestBuilder", ".", "setSize", "(", "0", ")", ";", "return", "searchQuery", "(", "\"countQuery\"", ",", "countRequestBuilder", ",", "t...
Count query long. @param countRequestBuilder the count request builder @param timeoutMillis the timeout millis @return the long
[ "Count", "query", "long", "." ]
train
https://github.com/JM-Lab/utils-elasticsearch/blob/6ccec90e1e51d65d2af5efbb6d7b9f9bad90e638/src/main/java/kr/jm/utils/elasticsearch/JMElasticsearchSearchAndCount.java#L771-L776
groupon/monsoon
expr/src/main/java/com/groupon/lex/metrics/timeseries/InterpolatedTSC.java
InterpolatedTSC.interpolateTSV
private TimeSeriesValue interpolateTSV(GroupName name) { final Map.Entry<DateTime, TimeSeriesValue> backTSV = findName(backward, name), forwTSV = findName(forward, name); final long backMillis = max(new Duration(backTSV.getKey(), getTimestamp()).getMillis(), 0), forwMillis = max(new Duration(getTimestamp(), forwTSV.getKey()).getMillis(), 0); final double totalMillis = forwMillis + backMillis; final double backWeight = forwMillis / totalMillis; final double forwWeight = backMillis / totalMillis; return new InterpolatedTSV(name, backTSV.getValue().getMetrics(), forwTSV.getValue().getMetrics(), backWeight, forwWeight); }
java
private TimeSeriesValue interpolateTSV(GroupName name) { final Map.Entry<DateTime, TimeSeriesValue> backTSV = findName(backward, name), forwTSV = findName(forward, name); final long backMillis = max(new Duration(backTSV.getKey(), getTimestamp()).getMillis(), 0), forwMillis = max(new Duration(getTimestamp(), forwTSV.getKey()).getMillis(), 0); final double totalMillis = forwMillis + backMillis; final double backWeight = forwMillis / totalMillis; final double forwWeight = backMillis / totalMillis; return new InterpolatedTSV(name, backTSV.getValue().getMetrics(), forwTSV.getValue().getMetrics(), backWeight, forwWeight); }
[ "private", "TimeSeriesValue", "interpolateTSV", "(", "GroupName", "name", ")", "{", "final", "Map", ".", "Entry", "<", "DateTime", ",", "TimeSeriesValue", ">", "backTSV", "=", "findName", "(", "backward", ",", "name", ")", ",", "forwTSV", "=", "findName", "(...
Interpolates a group name, based on the most recent backward and oldest forward occurence. @param name The name of the group to interpolate. @return The interpolated name of the group.
[ "Interpolates", "a", "group", "name", "based", "on", "the", "most", "recent", "backward", "and", "oldest", "forward", "occurence", "." ]
train
https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/expr/src/main/java/com/groupon/lex/metrics/timeseries/InterpolatedTSC.java#L189-L200
iig-uni-freiburg/SEWOL
src/de/uni/freiburg/iig/telematik/sewol/context/process/ProcessContext.java
ProcessContext.removeAttribute
public boolean removeAttribute(String attribute, boolean removeFromACModel, boolean notifyListeners) { if (!super.removeObject(attribute, false)) { return false; } if (acModel != null && removeFromACModel && acModel.getContext() != this) { acModel.getContext().removeObject(attribute); } // Remove data usage of removed attributes for (String activity : activities) { removeDataUsageFor(activity, attribute); } if (notifyListeners) { contextListenerSupport.notifyObjectRemoved(attribute); } return true; }
java
public boolean removeAttribute(String attribute, boolean removeFromACModel, boolean notifyListeners) { if (!super.removeObject(attribute, false)) { return false; } if (acModel != null && removeFromACModel && acModel.getContext() != this) { acModel.getContext().removeObject(attribute); } // Remove data usage of removed attributes for (String activity : activities) { removeDataUsageFor(activity, attribute); } if (notifyListeners) { contextListenerSupport.notifyObjectRemoved(attribute); } return true; }
[ "public", "boolean", "removeAttribute", "(", "String", "attribute", ",", "boolean", "removeFromACModel", ",", "boolean", "notifyListeners", ")", "{", "if", "(", "!", "super", ".", "removeObject", "(", "attribute", ",", "false", ")", ")", "{", "return", "false"...
Removes the given attribute from the context. @param attribute @param removeFromACModel @param notifyListeners @return
[ "Removes", "the", "given", "attribute", "from", "the", "context", "." ]
train
https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/src/de/uni/freiburg/iig/telematik/sewol/context/process/ProcessContext.java#L360-L377
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.findMethod
@Nullable public static MethodTree findMethod(MethodSymbol symbol, VisitorState state) { return JavacTrees.instance(state.context).getTree(symbol); }
java
@Nullable public static MethodTree findMethod(MethodSymbol symbol, VisitorState state) { return JavacTrees.instance(state.context).getTree(symbol); }
[ "@", "Nullable", "public", "static", "MethodTree", "findMethod", "(", "MethodSymbol", "symbol", ",", "VisitorState", "state", ")", "{", "return", "JavacTrees", ".", "instance", "(", "state", ".", "context", ")", ".", "getTree", "(", "symbol", ")", ";", "}" ]
Returns the method tree that matches the given symbol within the compilation unit, or null if none was found.
[ "Returns", "the", "method", "tree", "that", "matches", "the", "given", "symbol", "within", "the", "compilation", "unit", "or", "null", "if", "none", "was", "found", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L539-L542
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.saveRewriteAliases
public void saveRewriteAliases(CmsRequestContext requestContext, String siteRoot, List<CmsRewriteAlias> newAliases) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(requestContext); try { // checkOfflineProject(dbc); // checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.saveRewriteAliases(dbc, siteRoot, newAliases); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); } finally { dbc.clear(); } }
java
public void saveRewriteAliases(CmsRequestContext requestContext, String siteRoot, List<CmsRewriteAlias> newAliases) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(requestContext); try { // checkOfflineProject(dbc); // checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.saveRewriteAliases(dbc, siteRoot, newAliases); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); } finally { dbc.clear(); } }
[ "public", "void", "saveRewriteAliases", "(", "CmsRequestContext", "requestContext", ",", "String", "siteRoot", ",", "List", "<", "CmsRewriteAlias", ">", "newAliases", ")", "throws", "CmsException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbCont...
Replaces the rewrite aliases for a given site root.<p> @param requestContext the current request context @param siteRoot the site root for which the rewrite aliases should be replaced @param newAliases the new list of aliases for the given site root @throws CmsException if something goes wrong
[ "Replaces", "the", "rewrite", "aliases", "for", "a", "given", "site", "root", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L5902-L5915
OpenLiberty/open-liberty
dev/com.ibm.ws.httpservice/src/com/ibm/ws/httpsvc/session/internal/SessionInfo.java
SessionInfo.stripURL
public static String stripURL(String url, SessionInfo info) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Removing any session id from [" + url + "]"); } String target = info.getSessionConfig().getURLRewritingMarker(); URLParser parser = new URLParser(url, target); if (-1 != parser.idMarker) { // the parser found an id marker, see if we need to include // any trailing fragment or query data StringBuilder sb = new StringBuilder(url.substring(0, parser.idMarker)); if (-1 != parser.fragmentMarker) { sb.append(url.substring(parser.fragmentMarker)); } else if (-1 != parser.queryMarker) { sb.append(url.substring(parser.queryMarker)); } return sb.toString(); } return url; }
java
public static String stripURL(String url, SessionInfo info) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Removing any session id from [" + url + "]"); } String target = info.getSessionConfig().getURLRewritingMarker(); URLParser parser = new URLParser(url, target); if (-1 != parser.idMarker) { // the parser found an id marker, see if we need to include // any trailing fragment or query data StringBuilder sb = new StringBuilder(url.substring(0, parser.idMarker)); if (-1 != parser.fragmentMarker) { sb.append(url.substring(parser.fragmentMarker)); } else if (-1 != parser.queryMarker) { sb.append(url.substring(parser.queryMarker)); } return sb.toString(); } return url; }
[ "public", "static", "String", "stripURL", "(", "String", "url", ",", "SessionInfo", "info", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc",...
Strip out any session id information from the input URL. @param url @param info @return String
[ "Strip", "out", "any", "session", "id", "information", "from", "the", "input", "URL", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.httpservice/src/com/ibm/ws/httpsvc/session/internal/SessionInfo.java#L171-L189
looly/hutool
hutool-core/src/main/java/cn/hutool/core/bean/DynaBean.java
DynaBean.set
@SuppressWarnings({ "unchecked", "rawtypes" }) public void set(String fieldName, Object value) throws BeanException{ if(Map.class.isAssignableFrom(beanClass)){ ((Map)bean).put(fieldName, value); return; }else{ try { final Method setter = BeanUtil.getBeanDesc(beanClass).getSetter(fieldName); if(null == setter){ throw new BeanException("No set method for {}", fieldName); } setter.invoke(this.bean, value); } catch (Exception e) { throw new BeanException(e); } } }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public void set(String fieldName, Object value) throws BeanException{ if(Map.class.isAssignableFrom(beanClass)){ ((Map)bean).put(fieldName, value); return; }else{ try { final Method setter = BeanUtil.getBeanDesc(beanClass).getSetter(fieldName); if(null == setter){ throw new BeanException("No set method for {}", fieldName); } setter.invoke(this.bean, value); } catch (Exception e) { throw new BeanException(e); } } }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "public", "void", "set", "(", "String", "fieldName", ",", "Object", "value", ")", "throws", "BeanException", "{", "if", "(", "Map", ".", "class", ".", "isAssignableFrom", "(",...
设置字段值 @param fieldName 字段名 @param value 字段值 @throws BeanException 反射获取属性值或字段值导致的异常
[ "设置字段值" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/bean/DynaBean.java#L113-L129
knowm/XChart
xchart/src/main/java/org/knowm/xchart/PieChart.java
PieChart.updatePieSeries
public PieSeries updatePieSeries(String seriesName, Number value) { Map<String, PieSeries> seriesMap = getSeriesMap(); PieSeries series = seriesMap.get(seriesName); if (series == null) { throw new IllegalArgumentException("Series name >" + seriesName + "< not found!!!"); } series.replaceData(value); return series; }
java
public PieSeries updatePieSeries(String seriesName, Number value) { Map<String, PieSeries> seriesMap = getSeriesMap(); PieSeries series = seriesMap.get(seriesName); if (series == null) { throw new IllegalArgumentException("Series name >" + seriesName + "< not found!!!"); } series.replaceData(value); return series; }
[ "public", "PieSeries", "updatePieSeries", "(", "String", "seriesName", ",", "Number", "value", ")", "{", "Map", "<", "String", ",", "PieSeries", ">", "seriesMap", "=", "getSeriesMap", "(", ")", ";", "PieSeries", "series", "=", "seriesMap", ".", "get", "(", ...
Update a series by updating the pie slide value @param seriesName @param value @return
[ "Update", "a", "series", "by", "updating", "the", "pie", "slide", "value" ]
train
https://github.com/knowm/XChart/blob/677a105753a855edf24782fab1bf1f5aec3e642b/xchart/src/main/java/org/knowm/xchart/PieChart.java#L96-L106