repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java
GeometryUtilities.getTriangleWindingRule
public static int getTriangleWindingRule( Coordinate A, Coordinate B, Coordinate C ) { """ Get the winding rule of a triangle by their coordinates (given in digitized order). @param A coordinate 1. @param B coordinate 2. @param C coordinate 3. @return -1 if the digitalization is clock wise, else 1. """ double[] rBA = {B.x - A.x, B.y - A.y, B.z - A.z}; double[] rCA = {C.x - A.x, C.y - A.y, C.z - A.z}; double[] crossProduct = {// /* */rBA[1] * rCA[2] - rBA[2] * rCA[1], // -1 * (rBA[0] * rCA[2] - rBA[2] * rCA[0]), // rBA[0] * rCA[1] - rBA[1] * rCA[0] // }; return crossProduct[2] > 0 ? 1 : -1; }
java
public static int getTriangleWindingRule( Coordinate A, Coordinate B, Coordinate C ) { double[] rBA = {B.x - A.x, B.y - A.y, B.z - A.z}; double[] rCA = {C.x - A.x, C.y - A.y, C.z - A.z}; double[] crossProduct = {// /* */rBA[1] * rCA[2] - rBA[2] * rCA[1], // -1 * (rBA[0] * rCA[2] - rBA[2] * rCA[0]), // rBA[0] * rCA[1] - rBA[1] * rCA[0] // }; return crossProduct[2] > 0 ? 1 : -1; }
[ "public", "static", "int", "getTriangleWindingRule", "(", "Coordinate", "A", ",", "Coordinate", "B", ",", "Coordinate", "C", ")", "{", "double", "[", "]", "rBA", "=", "{", "B", ".", "x", "-", "A", ".", "x", ",", "B", ".", "y", "-", "A", ".", "y", ",", "B", ".", "z", "-", "A", ".", "z", "}", ";", "double", "[", "]", "rCA", "=", "{", "C", ".", "x", "-", "A", ".", "x", ",", "C", ".", "y", "-", "A", ".", "y", ",", "C", ".", "z", "-", "A", ".", "z", "}", ";", "double", "[", "]", "crossProduct", "=", "{", "//", "/* */", "rBA", "[", "1", "]", "*", "rCA", "[", "2", "]", "-", "rBA", "[", "2", "]", "*", "rCA", "[", "1", "]", ",", "//", "-", "1", "*", "(", "rBA", "[", "0", "]", "*", "rCA", "[", "2", "]", "-", "rBA", "[", "2", "]", "*", "rCA", "[", "0", "]", ")", ",", "//", "rBA", "[", "0", "]", "*", "rCA", "[", "1", "]", "-", "rBA", "[", "1", "]", "*", "rCA", "[", "0", "]", "//", "}", ";", "return", "crossProduct", "[", "2", "]", ">", "0", "?", "1", ":", "-", "1", ";", "}" ]
Get the winding rule of a triangle by their coordinates (given in digitized order). @param A coordinate 1. @param B coordinate 2. @param C coordinate 3. @return -1 if the digitalization is clock wise, else 1.
[ "Get", "the", "winding", "rule", "of", "a", "triangle", "by", "their", "coordinates", "(", "given", "in", "digitized", "order", ")", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java#L870-L881
demidenko05/beigesoft-bcommon
src/main/java/org/beigesoft/holder/HolderRapiGetters.java
HolderRapiGetters.getFor
@Override public final Method getFor(final Class<?> pClass, final String pFieldName) { """ <p>Get thing for given class and thing name.</p> @param pClass a Class @param pFieldName Thing Name @return a thing """ Map<String, Method> methMap = this.rapiMethodsMap.get(pClass); if (methMap == null) { // There is no way to get from Map partially initialized bean // in this double-checked locking implementation // cause putting to the Map fully initialized bean synchronized (this.rapiMethodsMap) { methMap = this.rapiMethodsMap.get(pClass); if (methMap == null) { methMap = new HashMap<String, Method>(); Method[] methods = getUtlReflection().retrieveMethods(pClass); for (Method method : methods) { if (method.getName().startsWith("get")) { String fldNm = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); methMap.put(fldNm, method); } } //assigning fully initialized object: this.rapiMethodsMap.put(pClass, methMap); } } } return methMap.get(pFieldName); }
java
@Override public final Method getFor(final Class<?> pClass, final String pFieldName) { Map<String, Method> methMap = this.rapiMethodsMap.get(pClass); if (methMap == null) { // There is no way to get from Map partially initialized bean // in this double-checked locking implementation // cause putting to the Map fully initialized bean synchronized (this.rapiMethodsMap) { methMap = this.rapiMethodsMap.get(pClass); if (methMap == null) { methMap = new HashMap<String, Method>(); Method[] methods = getUtlReflection().retrieveMethods(pClass); for (Method method : methods) { if (method.getName().startsWith("get")) { String fldNm = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); methMap.put(fldNm, method); } } //assigning fully initialized object: this.rapiMethodsMap.put(pClass, methMap); } } } return methMap.get(pFieldName); }
[ "@", "Override", "public", "final", "Method", "getFor", "(", "final", "Class", "<", "?", ">", "pClass", ",", "final", "String", "pFieldName", ")", "{", "Map", "<", "String", ",", "Method", ">", "methMap", "=", "this", ".", "rapiMethodsMap", ".", "get", "(", "pClass", ")", ";", "if", "(", "methMap", "==", "null", ")", "{", "// There is no way to get from Map partially initialized bean", "// in this double-checked locking implementation", "// cause putting to the Map fully initialized bean", "synchronized", "(", "this", ".", "rapiMethodsMap", ")", "{", "methMap", "=", "this", ".", "rapiMethodsMap", ".", "get", "(", "pClass", ")", ";", "if", "(", "methMap", "==", "null", ")", "{", "methMap", "=", "new", "HashMap", "<", "String", ",", "Method", ">", "(", ")", ";", "Method", "[", "]", "methods", "=", "getUtlReflection", "(", ")", ".", "retrieveMethods", "(", "pClass", ")", ";", "for", "(", "Method", "method", ":", "methods", ")", "{", "if", "(", "method", ".", "getName", "(", ")", ".", "startsWith", "(", "\"get\"", ")", ")", "{", "String", "fldNm", "=", "method", ".", "getName", "(", ")", ".", "substring", "(", "3", ",", "4", ")", ".", "toLowerCase", "(", ")", "+", "method", ".", "getName", "(", ")", ".", "substring", "(", "4", ")", ";", "methMap", ".", "put", "(", "fldNm", ",", "method", ")", ";", "}", "}", "//assigning fully initialized object:", "this", ".", "rapiMethodsMap", ".", "put", "(", "pClass", ",", "methMap", ")", ";", "}", "}", "}", "return", "methMap", ".", "get", "(", "pFieldName", ")", ";", "}" ]
<p>Get thing for given class and thing name.</p> @param pClass a Class @param pFieldName Thing Name @return a thing
[ "<p", ">", "Get", "thing", "for", "given", "class", "and", "thing", "name", ".", "<", "/", "p", ">" ]
train
https://github.com/demidenko05/beigesoft-bcommon/blob/bb446822b4fc9b5a6a8cd3cc98d0b3d83d718daf/src/main/java/org/beigesoft/holder/HolderRapiGetters.java#L46-L71
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/config/Config.java
Config.setFlakeIdGeneratorConfigs
public Config setFlakeIdGeneratorConfigs(Map<String, FlakeIdGeneratorConfig> map) { """ Sets the map of {@link FlakeIdGenerator} configurations, mapped by config name. The config name may be a pattern with which the configuration will be obtained in the future. @param map the FlakeIdGenerator configuration map to set @return this config instance """ flakeIdGeneratorConfigMap.clear(); flakeIdGeneratorConfigMap.putAll(map); for (Entry<String, FlakeIdGeneratorConfig> entry : map.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
java
public Config setFlakeIdGeneratorConfigs(Map<String, FlakeIdGeneratorConfig> map) { flakeIdGeneratorConfigMap.clear(); flakeIdGeneratorConfigMap.putAll(map); for (Entry<String, FlakeIdGeneratorConfig> entry : map.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
[ "public", "Config", "setFlakeIdGeneratorConfigs", "(", "Map", "<", "String", ",", "FlakeIdGeneratorConfig", ">", "map", ")", "{", "flakeIdGeneratorConfigMap", ".", "clear", "(", ")", ";", "flakeIdGeneratorConfigMap", ".", "putAll", "(", "map", ")", ";", "for", "(", "Entry", "<", "String", ",", "FlakeIdGeneratorConfig", ">", "entry", ":", "map", ".", "entrySet", "(", ")", ")", "{", "entry", ".", "getValue", "(", ")", ".", "setName", "(", "entry", ".", "getKey", "(", ")", ")", ";", "}", "return", "this", ";", "}" ]
Sets the map of {@link FlakeIdGenerator} configurations, mapped by config name. The config name may be a pattern with which the configuration will be obtained in the future. @param map the FlakeIdGenerator configuration map to set @return this config instance
[ "Sets", "the", "map", "of", "{", "@link", "FlakeIdGenerator", "}", "configurations", "mapped", "by", "config", "name", ".", "The", "config", "name", "may", "be", "a", "pattern", "with", "which", "the", "configuration", "will", "be", "obtained", "in", "the", "future", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L3083-L3090
xmlet/XsdAsmFaster
src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java
XsdAsmInterfaces.createChoiceInterface
private List<InterfaceInfo> createChoiceInterface(List<XsdGroup> groupElements, List<XsdElement> directElements, String interfaceName, String className, String groupName, int interfaceIndex, String apiName) { """ Generates an interface based on a {@link XsdChoice} element. @param groupElements The contained groupElements. @param directElements The direct elements of the {@link XsdChoice} element. @param interfaceName The choice interface name. @param className The name of the class that contains the {@link XsdChoice} element. @param interfaceIndex The current interface index. @param apiName The name of the generated fluent interface. @param groupName The name of the group in which this {@link XsdChoice} element is contained, if any. @return A {@link List} of {@link InterfaceInfo} objects containing relevant interface information. """ List<InterfaceInfo> interfaceInfoList = new ArrayList<>(); List<String> extendedInterfaces = new ArrayList<>(); for (XsdGroup groupElement : groupElements) { InterfaceInfo interfaceInfo = iterativeCreation(groupElement, className, interfaceIndex + 1, apiName, groupName).get(0); interfaceIndex = interfaceInfo.getInterfaceIndex(); extendedInterfaces.add(interfaceInfo.getInterfaceName()); interfaceInfoList.add(interfaceInfo); } Set<String> ambiguousMethods = getAmbiguousMethods(interfaceInfoList); if (ambiguousMethods.isEmpty() && directElements.isEmpty()){ return interfaceInfoList; } String[] extendedInterfacesArr = listToArray(extendedInterfaces, TEXT_GROUP); ClassWriter classWriter = generateClass(interfaceName, JAVA_OBJECT, extendedInterfacesArr, getInterfaceSignature(extendedInterfacesArr, apiName), ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, apiName); String interfaceType = getFullClassTypeName(interfaceName, apiName); directElements.forEach(child -> { generateMethodsForElement(classWriter, child, interfaceType, apiName); createElement(child, apiName); }); ambiguousMethods.forEach(ambiguousMethodName -> generateMethodsForElement(classWriter, ambiguousMethodName, interfaceType, apiName, new String[]{"Ljava/lang/Override;"}) ); writeClassToFile(interfaceName, classWriter, apiName); List<InterfaceInfo> choiceInterface = new ArrayList<>(); choiceInterface.add(new InterfaceInfo(interfaceName, interfaceIndex, directElements.stream().map(XsdElement::getName).collect(Collectors.toList()), interfaceInfoList)); return choiceInterface; }
java
private List<InterfaceInfo> createChoiceInterface(List<XsdGroup> groupElements, List<XsdElement> directElements, String interfaceName, String className, String groupName, int interfaceIndex, String apiName) { List<InterfaceInfo> interfaceInfoList = new ArrayList<>(); List<String> extendedInterfaces = new ArrayList<>(); for (XsdGroup groupElement : groupElements) { InterfaceInfo interfaceInfo = iterativeCreation(groupElement, className, interfaceIndex + 1, apiName, groupName).get(0); interfaceIndex = interfaceInfo.getInterfaceIndex(); extendedInterfaces.add(interfaceInfo.getInterfaceName()); interfaceInfoList.add(interfaceInfo); } Set<String> ambiguousMethods = getAmbiguousMethods(interfaceInfoList); if (ambiguousMethods.isEmpty() && directElements.isEmpty()){ return interfaceInfoList; } String[] extendedInterfacesArr = listToArray(extendedInterfaces, TEXT_GROUP); ClassWriter classWriter = generateClass(interfaceName, JAVA_OBJECT, extendedInterfacesArr, getInterfaceSignature(extendedInterfacesArr, apiName), ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, apiName); String interfaceType = getFullClassTypeName(interfaceName, apiName); directElements.forEach(child -> { generateMethodsForElement(classWriter, child, interfaceType, apiName); createElement(child, apiName); }); ambiguousMethods.forEach(ambiguousMethodName -> generateMethodsForElement(classWriter, ambiguousMethodName, interfaceType, apiName, new String[]{"Ljava/lang/Override;"}) ); writeClassToFile(interfaceName, classWriter, apiName); List<InterfaceInfo> choiceInterface = new ArrayList<>(); choiceInterface.add(new InterfaceInfo(interfaceName, interfaceIndex, directElements.stream().map(XsdElement::getName).collect(Collectors.toList()), interfaceInfoList)); return choiceInterface; }
[ "private", "List", "<", "InterfaceInfo", ">", "createChoiceInterface", "(", "List", "<", "XsdGroup", ">", "groupElements", ",", "List", "<", "XsdElement", ">", "directElements", ",", "String", "interfaceName", ",", "String", "className", ",", "String", "groupName", ",", "int", "interfaceIndex", ",", "String", "apiName", ")", "{", "List", "<", "InterfaceInfo", ">", "interfaceInfoList", "=", "new", "ArrayList", "<>", "(", ")", ";", "List", "<", "String", ">", "extendedInterfaces", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "XsdGroup", "groupElement", ":", "groupElements", ")", "{", "InterfaceInfo", "interfaceInfo", "=", "iterativeCreation", "(", "groupElement", ",", "className", ",", "interfaceIndex", "+", "1", ",", "apiName", ",", "groupName", ")", ".", "get", "(", "0", ")", ";", "interfaceIndex", "=", "interfaceInfo", ".", "getInterfaceIndex", "(", ")", ";", "extendedInterfaces", ".", "add", "(", "interfaceInfo", ".", "getInterfaceName", "(", ")", ")", ";", "interfaceInfoList", ".", "add", "(", "interfaceInfo", ")", ";", "}", "Set", "<", "String", ">", "ambiguousMethods", "=", "getAmbiguousMethods", "(", "interfaceInfoList", ")", ";", "if", "(", "ambiguousMethods", ".", "isEmpty", "(", ")", "&&", "directElements", ".", "isEmpty", "(", ")", ")", "{", "return", "interfaceInfoList", ";", "}", "String", "[", "]", "extendedInterfacesArr", "=", "listToArray", "(", "extendedInterfaces", ",", "TEXT_GROUP", ")", ";", "ClassWriter", "classWriter", "=", "generateClass", "(", "interfaceName", ",", "JAVA_OBJECT", ",", "extendedInterfacesArr", ",", "getInterfaceSignature", "(", "extendedInterfacesArr", ",", "apiName", ")", ",", "ACC_PUBLIC", "+", "ACC_ABSTRACT", "+", "ACC_INTERFACE", ",", "apiName", ")", ";", "String", "interfaceType", "=", "getFullClassTypeName", "(", "interfaceName", ",", "apiName", ")", ";", "directElements", ".", "forEach", "(", "child", "->", "{", "generateMethodsForElement", "(", "classWriter", ",", "child", ",", "interfaceType", ",", "apiName", ")", ";", "createElement", "(", "child", ",", "apiName", ")", ";", "}", ")", ";", "ambiguousMethods", ".", "forEach", "(", "ambiguousMethodName", "->", "generateMethodsForElement", "(", "classWriter", ",", "ambiguousMethodName", ",", "interfaceType", ",", "apiName", ",", "new", "String", "[", "]", "{", "\"Ljava/lang/Override;\"", "}", ")", ")", ";", "writeClassToFile", "(", "interfaceName", ",", "classWriter", ",", "apiName", ")", ";", "List", "<", "InterfaceInfo", ">", "choiceInterface", "=", "new", "ArrayList", "<>", "(", ")", ";", "choiceInterface", ".", "add", "(", "new", "InterfaceInfo", "(", "interfaceName", ",", "interfaceIndex", ",", "directElements", ".", "stream", "(", ")", ".", "map", "(", "XsdElement", "::", "getName", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ",", "interfaceInfoList", ")", ")", ";", "return", "choiceInterface", ";", "}" ]
Generates an interface based on a {@link XsdChoice} element. @param groupElements The contained groupElements. @param directElements The direct elements of the {@link XsdChoice} element. @param interfaceName The choice interface name. @param className The name of the class that contains the {@link XsdChoice} element. @param interfaceIndex The current interface index. @param apiName The name of the generated fluent interface. @param groupName The name of the group in which this {@link XsdChoice} element is contained, if any. @return A {@link List} of {@link InterfaceInfo} objects containing relevant interface information.
[ "Generates", "an", "interface", "based", "on", "a", "{" ]
train
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java#L693-L733
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java
ZipUtil.unzip
public static File unzip(String zipFilePath, String outFileDir, Charset charset) throws UtilException { """ 解压 @param zipFilePath 压缩文件的路径 @param outFileDir 解压到的目录 @param charset 编码 @return 解压的目录 @throws UtilException IO异常 """ return unzip(FileUtil.file(zipFilePath), FileUtil.mkdir(outFileDir), charset); }
java
public static File unzip(String zipFilePath, String outFileDir, Charset charset) throws UtilException { return unzip(FileUtil.file(zipFilePath), FileUtil.mkdir(outFileDir), charset); }
[ "public", "static", "File", "unzip", "(", "String", "zipFilePath", ",", "String", "outFileDir", ",", "Charset", "charset", ")", "throws", "UtilException", "{", "return", "unzip", "(", "FileUtil", ".", "file", "(", "zipFilePath", ")", ",", "FileUtil", ".", "mkdir", "(", "outFileDir", ")", ",", "charset", ")", ";", "}" ]
解压 @param zipFilePath 压缩文件的路径 @param outFileDir 解压到的目录 @param charset 编码 @return 解压的目录 @throws UtilException IO异常
[ "解压" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ZipUtil.java#L358-L360
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/locale/LocaleFormatter.java
LocaleFormatter.getFormatted
@Nonnull public static String getFormatted (final int nValue, @Nonnull final Locale aDisplayLocale) { """ Format the passed value according to the rules specified by the given locale. All calls to {@link Integer#toString(int)} that are displayed to the user should instead use this method. @param nValue The value to be formatted. @param aDisplayLocale The locale to be used. May not be <code>null</code>. @return The formatted string. """ ValueEnforcer.notNull (aDisplayLocale, "DisplayLocale"); return NumberFormat.getIntegerInstance (aDisplayLocale).format (nValue); }
java
@Nonnull public static String getFormatted (final int nValue, @Nonnull final Locale aDisplayLocale) { ValueEnforcer.notNull (aDisplayLocale, "DisplayLocale"); return NumberFormat.getIntegerInstance (aDisplayLocale).format (nValue); }
[ "@", "Nonnull", "public", "static", "String", "getFormatted", "(", "final", "int", "nValue", ",", "@", "Nonnull", "final", "Locale", "aDisplayLocale", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aDisplayLocale", ",", "\"DisplayLocale\"", ")", ";", "return", "NumberFormat", ".", "getIntegerInstance", "(", "aDisplayLocale", ")", ".", "format", "(", "nValue", ")", ";", "}" ]
Format the passed value according to the rules specified by the given locale. All calls to {@link Integer#toString(int)} that are displayed to the user should instead use this method. @param nValue The value to be formatted. @param aDisplayLocale The locale to be used. May not be <code>null</code>. @return The formatted string.
[ "Format", "the", "passed", "value", "according", "to", "the", "rules", "specified", "by", "the", "given", "locale", ".", "All", "calls", "to", "{", "@link", "Integer#toString", "(", "int", ")", "}", "that", "are", "displayed", "to", "the", "user", "should", "instead", "use", "this", "method", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/locale/LocaleFormatter.java#L75-L81
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/util/Environment.java
Environment.setProperty
public void setProperty(String strProperty, String strValue) { """ Set this property. NOTE: also looks in the default application's properties. @param strProperty The property key. @return The property value. """ if (strValue != null) m_properties.put(strProperty, strValue); else m_properties.remove(strProperty); }
java
public void setProperty(String strProperty, String strValue) { if (strValue != null) m_properties.put(strProperty, strValue); else m_properties.remove(strProperty); }
[ "public", "void", "setProperty", "(", "String", "strProperty", ",", "String", "strValue", ")", "{", "if", "(", "strValue", "!=", "null", ")", "m_properties", ".", "put", "(", "strProperty", ",", "strValue", ")", ";", "else", "m_properties", ".", "remove", "(", "strProperty", ")", ";", "}" ]
Set this property. NOTE: also looks in the default application's properties. @param strProperty The property key. @return The property value.
[ "Set", "this", "property", ".", "NOTE", ":", "also", "looks", "in", "the", "default", "application", "s", "properties", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/util/Environment.java#L235-L241
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/application/config/support/DefaultApplicationObjectConfigurer.java
DefaultApplicationObjectConfigurer.configureTitle
protected void configureTitle(TitleConfigurable configurable, String objectName) { """ Sets the title of the given object. The title is loaded from this instance's {@link MessageSource} using a message code in the format <pre> &lt;objectName&gt;.title </pre> @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null. """ Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); String title = loadMessage(objectName + "." + TITLE_KEY); if (StringUtils.hasText(title)) { configurable.setTitle(title); } }
java
protected void configureTitle(TitleConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); String title = loadMessage(objectName + "." + TITLE_KEY); if (StringUtils.hasText(title)) { configurable.setTitle(title); } }
[ "protected", "void", "configureTitle", "(", "TitleConfigurable", "configurable", ",", "String", "objectName", ")", "{", "Assert", ".", "notNull", "(", "configurable", ",", "\"configurable\"", ")", ";", "Assert", ".", "notNull", "(", "objectName", ",", "\"objectName\"", ")", ";", "String", "title", "=", "loadMessage", "(", "objectName", "+", "\".\"", "+", "TITLE_KEY", ")", ";", "if", "(", "StringUtils", ".", "hasText", "(", "title", ")", ")", "{", "configurable", ".", "setTitle", "(", "title", ")", ";", "}", "}" ]
Sets the title of the given object. The title is loaded from this instance's {@link MessageSource} using a message code in the format <pre> &lt;objectName&gt;.title </pre> @param configurable The object to be configured. Must not be null. @param objectName The name of the configurable object, unique within the application. Must not be null. @throws IllegalArgumentException if either argument is null.
[ "Sets", "the", "title", "of", "the", "given", "object", ".", "The", "title", "is", "loaded", "from", "this", "instance", "s", "{", "@link", "MessageSource", "}", "using", "a", "message", "code", "in", "the", "format" ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/application/config/support/DefaultApplicationObjectConfigurer.java#L346-L355
alkacon/opencms-core
src/org/opencms/file/CmsObject.java
CmsObject.readResource
public CmsResource readResource(String resourcename, CmsResourceFilter filter) throws CmsException { """ Reads a resource from the VFS, using the specified resource filter.<p> A resource may be of type <code>{@link CmsFile}</code> or <code>{@link CmsFolder}</code>. In case of a file, the resource will not contain the binary file content. Since reading the binary content is a cost-expensive database operation, it's recommended to work with resources if possible, and only read the file content when absolutely required. To "upgrade" a resource to a file, use <code>{@link #readFile(CmsResource)}</code>.<p> The specified filter controls what kind of resources should be "found" during the read operation. This will depend on the application. For example, using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> will ignore the date release / date expired information of the resource.<p> @param resourcename the name of the resource to read (full current site relative path) @param filter the resource filter to use while reading @return the resource that was read @throws CmsException if the resource could not be read for any reason @see #readFile(String, CmsResourceFilter) @see #readFolder(String, CmsResourceFilter) """ return m_securityManager.readResource(m_context, addSiteRoot(resourcename), filter); }
java
public CmsResource readResource(String resourcename, CmsResourceFilter filter) throws CmsException { return m_securityManager.readResource(m_context, addSiteRoot(resourcename), filter); }
[ "public", "CmsResource", "readResource", "(", "String", "resourcename", ",", "CmsResourceFilter", "filter", ")", "throws", "CmsException", "{", "return", "m_securityManager", ".", "readResource", "(", "m_context", ",", "addSiteRoot", "(", "resourcename", ")", ",", "filter", ")", ";", "}" ]
Reads a resource from the VFS, using the specified resource filter.<p> A resource may be of type <code>{@link CmsFile}</code> or <code>{@link CmsFolder}</code>. In case of a file, the resource will not contain the binary file content. Since reading the binary content is a cost-expensive database operation, it's recommended to work with resources if possible, and only read the file content when absolutely required. To "upgrade" a resource to a file, use <code>{@link #readFile(CmsResource)}</code>.<p> The specified filter controls what kind of resources should be "found" during the read operation. This will depend on the application. For example, using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> will ignore the date release / date expired information of the resource.<p> @param resourcename the name of the resource to read (full current site relative path) @param filter the resource filter to use while reading @return the resource that was read @throws CmsException if the resource could not be read for any reason @see #readFile(String, CmsResourceFilter) @see #readFolder(String, CmsResourceFilter)
[ "Reads", "a", "resource", "from", "the", "VFS", "using", "the", "specified", "resource", "filter", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L3207-L3210
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/EntityManagerFactory.java
EntityManagerFactory.createEntityManager
public EntityManager createEntityManager(String projectId, String jsonCredentialsFile, String namespace) { """ Creates and return a new {@link EntityManager} using the provided JSON formatted credentials. @param projectId the project ID @param jsonCredentialsFile the JSON formatted credentials file for the target Cloud project. @param namespace the namespace (for multi-tenant datastore) to use. If <code>null</code>, default namespace is used. @return a new {@link EntityManager} """ return createEntityManager(projectId, new File(jsonCredentialsFile), namespace); }
java
public EntityManager createEntityManager(String projectId, String jsonCredentialsFile, String namespace) { return createEntityManager(projectId, new File(jsonCredentialsFile), namespace); }
[ "public", "EntityManager", "createEntityManager", "(", "String", "projectId", ",", "String", "jsonCredentialsFile", ",", "String", "namespace", ")", "{", "return", "createEntityManager", "(", "projectId", ",", "new", "File", "(", "jsonCredentialsFile", ")", ",", "namespace", ")", ";", "}" ]
Creates and return a new {@link EntityManager} using the provided JSON formatted credentials. @param projectId the project ID @param jsonCredentialsFile the JSON formatted credentials file for the target Cloud project. @param namespace the namespace (for multi-tenant datastore) to use. If <code>null</code>, default namespace is used. @return a new {@link EntityManager}
[ "Creates", "and", "return", "a", "new", "{", "@link", "EntityManager", "}", "using", "the", "provided", "JSON", "formatted", "credentials", "." ]
train
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/EntityManagerFactory.java#L133-L136
cdk/cdk
legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java
GeometryTools.getClosestBond
public static IBond getClosestBond(double xPosition, double yPosition, IAtomContainer atomCon) { """ Returns the bond of the given molecule that is closest to the given coordinates. See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets @param xPosition The x coordinate @param yPosition The y coordinate @param atomCon The molecule that is searched for the closest bond @return The bond that is closest to the given coordinates """ Point2d bondCenter; IBond closestBond = null; double smallestMouseDistance = -1; double mouseDistance; Iterator<IBond> bonds = atomCon.bonds().iterator(); while (bonds.hasNext()) { IBond currentBond = (IBond) bonds.next(); bondCenter = get2DCenter(currentBond.atoms()); mouseDistance = Math.sqrt(Math.pow(bondCenter.x - xPosition, 2) + Math.pow(bondCenter.y - yPosition, 2)); if (mouseDistance < smallestMouseDistance || smallestMouseDistance == -1) { smallestMouseDistance = mouseDistance; closestBond = currentBond; } } return closestBond; }
java
public static IBond getClosestBond(double xPosition, double yPosition, IAtomContainer atomCon) { Point2d bondCenter; IBond closestBond = null; double smallestMouseDistance = -1; double mouseDistance; Iterator<IBond> bonds = atomCon.bonds().iterator(); while (bonds.hasNext()) { IBond currentBond = (IBond) bonds.next(); bondCenter = get2DCenter(currentBond.atoms()); mouseDistance = Math.sqrt(Math.pow(bondCenter.x - xPosition, 2) + Math.pow(bondCenter.y - yPosition, 2)); if (mouseDistance < smallestMouseDistance || smallestMouseDistance == -1) { smallestMouseDistance = mouseDistance; closestBond = currentBond; } } return closestBond; }
[ "public", "static", "IBond", "getClosestBond", "(", "double", "xPosition", ",", "double", "yPosition", ",", "IAtomContainer", "atomCon", ")", "{", "Point2d", "bondCenter", ";", "IBond", "closestBond", "=", "null", ";", "double", "smallestMouseDistance", "=", "-", "1", ";", "double", "mouseDistance", ";", "Iterator", "<", "IBond", ">", "bonds", "=", "atomCon", ".", "bonds", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "bonds", ".", "hasNext", "(", ")", ")", "{", "IBond", "currentBond", "=", "(", "IBond", ")", "bonds", ".", "next", "(", ")", ";", "bondCenter", "=", "get2DCenter", "(", "currentBond", ".", "atoms", "(", ")", ")", ";", "mouseDistance", "=", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "bondCenter", ".", "x", "-", "xPosition", ",", "2", ")", "+", "Math", ".", "pow", "(", "bondCenter", ".", "y", "-", "yPosition", ",", "2", ")", ")", ";", "if", "(", "mouseDistance", "<", "smallestMouseDistance", "||", "smallestMouseDistance", "==", "-", "1", ")", "{", "smallestMouseDistance", "=", "mouseDistance", ";", "closestBond", "=", "currentBond", ";", "}", "}", "return", "closestBond", ";", "}" ]
Returns the bond of the given molecule that is closest to the given coordinates. See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets @param xPosition The x coordinate @param yPosition The y coordinate @param atomCon The molecule that is searched for the closest bond @return The bond that is closest to the given coordinates
[ "Returns", "the", "bond", "of", "the", "given", "molecule", "that", "is", "closest", "to", "the", "given", "coordinates", ".", "See", "comment", "for", "center", "(", "IAtomContainer", "atomCon", "Dimension", "areaDim", "HashMap", "renderingCoordinates", ")", "for", "details", "on", "coordinate", "sets" ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/geometry/GeometryTools.java#L828-L845
hankcs/HanLP
src/main/java/com/hankcs/hanlp/mining/word2vec/AbstractVectorModel.java
AbstractVectorModel.nearest
public List<Map.Entry<K, Float>> nearest(K key) { """ 查询与词语最相似的词语 @param key 词语 @return 键值对列表, 键是相似词语, 值是相似度, 按相似度降序排列 """ return nearest(key, 10); }
java
public List<Map.Entry<K, Float>> nearest(K key) { return nearest(key, 10); }
[ "public", "List", "<", "Map", ".", "Entry", "<", "K", ",", "Float", ">", ">", "nearest", "(", "K", "key", ")", "{", "return", "nearest", "(", "key", ",", "10", ")", ";", "}" ]
查询与词语最相似的词语 @param key 词语 @return 键值对列表, 键是相似词语, 值是相似度, 按相似度降序排列
[ "查询与词语最相似的词语" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/mining/word2vec/AbstractVectorModel.java#L160-L163
zanata/openprops
orig/Properties.java
Properties.storeToXML
public synchronized void storeToXML(OutputStream os, String comment) throws IOException { """ Emits an XML document representing all of the properties contained in this table. <p> An invocation of this method of the form <tt>props.storeToXML(os, comment)</tt> behaves in exactly the same way as the invocation <tt>props.storeToXML(os, comment, "UTF-8");</tt>. @param os the output stream on which to emit the XML document. @param comment a description of the property list, or <code>null</code> if no comment is desired. @throws IOException if writing to the specified output stream results in an <tt>IOException</tt>. @throws NullPointerException if <code>os</code> is null. @throws ClassCastException if this <code>Properties</code> object contains any keys or values that are not <code>Strings</code>. @see #loadFromXML(InputStream) @since 1.5 """ if (os == null) throw new NullPointerException(); storeToXML(os, comment, "UTF-8"); }
java
public synchronized void storeToXML(OutputStream os, String comment) throws IOException { if (os == null) throw new NullPointerException(); storeToXML(os, comment, "UTF-8"); }
[ "public", "synchronized", "void", "storeToXML", "(", "OutputStream", "os", ",", "String", "comment", ")", "throws", "IOException", "{", "if", "(", "os", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "storeToXML", "(", "os", ",", "comment", ",", "\"UTF-8\"", ")", ";", "}" ]
Emits an XML document representing all of the properties contained in this table. <p> An invocation of this method of the form <tt>props.storeToXML(os, comment)</tt> behaves in exactly the same way as the invocation <tt>props.storeToXML(os, comment, "UTF-8");</tt>. @param os the output stream on which to emit the XML document. @param comment a description of the property list, or <code>null</code> if no comment is desired. @throws IOException if writing to the specified output stream results in an <tt>IOException</tt>. @throws NullPointerException if <code>os</code> is null. @throws ClassCastException if this <code>Properties</code> object contains any keys or values that are not <code>Strings</code>. @see #loadFromXML(InputStream) @since 1.5
[ "Emits", "an", "XML", "document", "representing", "all", "of", "the", "properties", "contained", "in", "this", "table", "." ]
train
https://github.com/zanata/openprops/blob/46510e610a765e4a91b302fc0d6a2123ed589603/orig/Properties.java#L893-L899
codegist/crest
core/src/main/java/org/codegist/crest/CRestBuilder.java
CRestBuilder.basicAuth
public CRestBuilder basicAuth(String username, String password) { """ <p>Configures the resulting <b>CRest</b> instance to authenticate all requests using Basic Auth</p> @param username user name to authenticate the requests with @param password password to authenticate the requests with @return current builder """ this.auth = "basic"; this.username = username; this.password = password; return this; }
java
public CRestBuilder basicAuth(String username, String password) { this.auth = "basic"; this.username = username; this.password = password; return this; }
[ "public", "CRestBuilder", "basicAuth", "(", "String", "username", ",", "String", "password", ")", "{", "this", ".", "auth", "=", "\"basic\"", ";", "this", ".", "username", "=", "username", ";", "this", ".", "password", "=", "password", ";", "return", "this", ";", "}" ]
<p>Configures the resulting <b>CRest</b> instance to authenticate all requests using Basic Auth</p> @param username user name to authenticate the requests with @param password password to authenticate the requests with @return current builder
[ "<p", ">", "Configures", "the", "resulting", "<b", ">", "CRest<", "/", "b", ">", "instance", "to", "authenticate", "all", "requests", "using", "Basic", "Auth<", "/", "p", ">" ]
train
https://github.com/codegist/crest/blob/e99ba7728b27d2ddb2c247261350f1b6fa7a6698/core/src/main/java/org/codegist/crest/CRestBuilder.java#L662-L667
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/style/StyleUtilities.java
StyleUtilities.changeRotation
public static void changeRotation( Rule rule, int newRotation ) { """ Changes the rotation value inside a rule. @param rule the {@link Rule}. @param newRotation the new rotation value in degrees. """ PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule); Graphic graphic = SLD.graphic(pointSymbolizer); graphic.setRotation(ff.literal(newRotation)); // Mark oldMark = SLDs.mark(pointSymbolizer); // oldMark.setSize(ff.literal(newRotation)); }
java
public static void changeRotation( Rule rule, int newRotation ) { PointSymbolizer pointSymbolizer = StyleUtilities.pointSymbolizerFromRule(rule); Graphic graphic = SLD.graphic(pointSymbolizer); graphic.setRotation(ff.literal(newRotation)); // Mark oldMark = SLDs.mark(pointSymbolizer); // oldMark.setSize(ff.literal(newRotation)); }
[ "public", "static", "void", "changeRotation", "(", "Rule", "rule", ",", "int", "newRotation", ")", "{", "PointSymbolizer", "pointSymbolizer", "=", "StyleUtilities", ".", "pointSymbolizerFromRule", "(", "rule", ")", ";", "Graphic", "graphic", "=", "SLD", ".", "graphic", "(", "pointSymbolizer", ")", ";", "graphic", ".", "setRotation", "(", "ff", ".", "literal", "(", "newRotation", ")", ")", ";", "// Mark oldMark = SLDs.mark(pointSymbolizer);", "// oldMark.setSize(ff.literal(newRotation));", "}" ]
Changes the rotation value inside a rule. @param rule the {@link Rule}. @param newRotation the new rotation value in degrees.
[ "Changes", "the", "rotation", "value", "inside", "a", "rule", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/style/StyleUtilities.java#L681-L687
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonWriteDriver.java
GeoJsonWriteDriver.write
private void write(LineString geom, JsonGenerator gen) throws IOException { """ Coordinates of LineString are an array of positions : { "type": "LineString", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] } @param geom @param gen @throws IOException """ gen.writeStringField("type", "LineString"); gen.writeFieldName("coordinates"); writeCoordinates(geom.getCoordinates(), gen); }
java
private void write(LineString geom, JsonGenerator gen) throws IOException { gen.writeStringField("type", "LineString"); gen.writeFieldName("coordinates"); writeCoordinates(geom.getCoordinates(), gen); }
[ "private", "void", "write", "(", "LineString", "geom", ",", "JsonGenerator", "gen", ")", "throws", "IOException", "{", "gen", ".", "writeStringField", "(", "\"type\"", ",", "\"LineString\"", ")", ";", "gen", ".", "writeFieldName", "(", "\"coordinates\"", ")", ";", "writeCoordinates", "(", "geom", ".", "getCoordinates", "(", ")", ",", "gen", ")", ";", "}" ]
Coordinates of LineString are an array of positions : { "type": "LineString", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] } @param geom @param gen @throws IOException
[ "Coordinates", "of", "LineString", "are", "an", "array", "of", "positions", ":" ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/geojson/GeoJsonWriteDriver.java#L397-L401
wcm-io/wcm-io-wcm
commons/src/main/java/io/wcm/wcm/commons/util/Template.java
Template.is
public static boolean is(@NotNull Page page, @NotNull String @NotNull... templatePaths) { """ Checks if the given page uses a specific template. @param page AEM page @param templatePaths Template path(s) @return true if the page uses the template """ if (page == null || templatePaths == null || templatePaths.length == 0) { return false; } String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class); for (String givenTemplatePath : templatePaths) { if (StringUtils.equals(templatePath, givenTemplatePath)) { return true; } } return false; }
java
public static boolean is(@NotNull Page page, @NotNull String @NotNull... templatePaths) { if (page == null || templatePaths == null || templatePaths.length == 0) { return false; } String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class); for (String givenTemplatePath : templatePaths) { if (StringUtils.equals(templatePath, givenTemplatePath)) { return true; } } return false; }
[ "public", "static", "boolean", "is", "(", "@", "NotNull", "Page", "page", ",", "@", "NotNull", "String", "@", "NotNull", ".", ".", ".", "templatePaths", ")", "{", "if", "(", "page", "==", "null", "||", "templatePaths", "==", "null", "||", "templatePaths", ".", "length", "==", "0", ")", "{", "return", "false", ";", "}", "String", "templatePath", "=", "page", ".", "getProperties", "(", ")", ".", "get", "(", "NameConstants", ".", "PN_TEMPLATE", ",", "String", ".", "class", ")", ";", "for", "(", "String", "givenTemplatePath", ":", "templatePaths", ")", "{", "if", "(", "StringUtils", ".", "equals", "(", "templatePath", ",", "givenTemplatePath", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if the given page uses a specific template. @param page AEM page @param templatePaths Template path(s) @return true if the page uses the template
[ "Checks", "if", "the", "given", "page", "uses", "a", "specific", "template", "." ]
train
https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/commons/src/main/java/io/wcm/wcm/commons/util/Template.java#L98-L109
powermock/powermock
powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/PowerMockito.java
PowerMockito.mockStatic
public static synchronized void mockStatic(Class<?> type, Class<?>... types) { """ Enable static mocking for all methods of a class. @param type the class to enable static mocking """ DefaultMockCreator.mock(type, true, false, null, null, (Method[]) null); if (types != null && types.length > 0) { for (Class<?> aClass : types) { DefaultMockCreator.mock(aClass, true, false, null, null, (Method[]) null); } } }
java
public static synchronized void mockStatic(Class<?> type, Class<?>... types) { DefaultMockCreator.mock(type, true, false, null, null, (Method[]) null); if (types != null && types.length > 0) { for (Class<?> aClass : types) { DefaultMockCreator.mock(aClass, true, false, null, null, (Method[]) null); } } }
[ "public", "static", "synchronized", "void", "mockStatic", "(", "Class", "<", "?", ">", "type", ",", "Class", "<", "?", ">", "...", "types", ")", "{", "DefaultMockCreator", ".", "mock", "(", "type", ",", "true", ",", "false", ",", "null", ",", "null", ",", "(", "Method", "[", "]", ")", "null", ")", ";", "if", "(", "types", "!=", "null", "&&", "types", ".", "length", ">", "0", ")", "{", "for", "(", "Class", "<", "?", ">", "aClass", ":", "types", ")", "{", "DefaultMockCreator", ".", "mock", "(", "aClass", ",", "true", ",", "false", ",", "null", ",", "null", ",", "(", "Method", "[", "]", ")", "null", ")", ";", "}", "}", "}" ]
Enable static mocking for all methods of a class. @param type the class to enable static mocking
[ "Enable", "static", "mocking", "for", "all", "methods", "of", "a", "class", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/PowerMockito.java#L61-L68
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.service.location/src/com/ibm/ws/kernel/service/location/internal/LocalFileResource.java
LocalFileResource.newResource
public static LocalFileResource newResource(String normalizedPath, String repositoryPath) { """ Create a new local resource @param normalizedPath Normalized file path for this resource; can not be null. @param repositoryPath An abstraction of the file location; may be null. """ return new LocalFileResource(normalizedPath, repositoryPath, null); }
java
public static LocalFileResource newResource(String normalizedPath, String repositoryPath) { return new LocalFileResource(normalizedPath, repositoryPath, null); }
[ "public", "static", "LocalFileResource", "newResource", "(", "String", "normalizedPath", ",", "String", "repositoryPath", ")", "{", "return", "new", "LocalFileResource", "(", "normalizedPath", ",", "repositoryPath", ",", "null", ")", ";", "}" ]
Create a new local resource @param normalizedPath Normalized file path for this resource; can not be null. @param repositoryPath An abstraction of the file location; may be null.
[ "Create", "a", "new", "local", "resource" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.service.location/src/com/ibm/ws/kernel/service/location/internal/LocalFileResource.java#L82-L84
astrapi69/jaulp-wicket
jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/link/LinkUtils.java
LinkUtils.newExternalLink
public static ExternalLink newExternalLink(final String linkId, final String url, final String labelId, final String resourceModelKey, final Object[] parameters, final String defaultValue, final Component component) { """ Creates an external link from the given parameters. @param linkId the link id @param url the external url @param labelId the label id @param resourceModelKey the resource model key @param parameters the parameters for the resource key @param defaultValue a default value @param component the component @return the external link """ return newExternalLink(linkId, url, labelId, ResourceBundleKey.builder() .key(resourceModelKey).parameters(parameters).defaultValue(defaultValue).build(), component); }
java
public static ExternalLink newExternalLink(final String linkId, final String url, final String labelId, final String resourceModelKey, final Object[] parameters, final String defaultValue, final Component component) { return newExternalLink(linkId, url, labelId, ResourceBundleKey.builder() .key(resourceModelKey).parameters(parameters).defaultValue(defaultValue).build(), component); }
[ "public", "static", "ExternalLink", "newExternalLink", "(", "final", "String", "linkId", ",", "final", "String", "url", ",", "final", "String", "labelId", ",", "final", "String", "resourceModelKey", ",", "final", "Object", "[", "]", "parameters", ",", "final", "String", "defaultValue", ",", "final", "Component", "component", ")", "{", "return", "newExternalLink", "(", "linkId", ",", "url", ",", "labelId", ",", "ResourceBundleKey", ".", "builder", "(", ")", ".", "key", "(", "resourceModelKey", ")", ".", "parameters", "(", "parameters", ")", ".", "defaultValue", "(", "defaultValue", ")", ".", "build", "(", ")", ",", "component", ")", ";", "}" ]
Creates an external link from the given parameters. @param linkId the link id @param url the external url @param labelId the label id @param resourceModelKey the resource model key @param parameters the parameters for the resource key @param defaultValue a default value @param component the component @return the external link
[ "Creates", "an", "external", "link", "from", "the", "given", "parameters", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/link/LinkUtils.java#L203-L210
grpc/grpc-java
core/src/main/java/io/grpc/util/RoundRobinLoadBalancer.java
RoundRobinLoadBalancer.updateBalancingState
@SuppressWarnings("ReferenceEquality") private void updateBalancingState() { """ Updates picker with the list of active subchannels (state == READY). """ List<Subchannel> activeList = filterNonFailingSubchannels(getSubchannels()); if (activeList.isEmpty()) { // No READY subchannels, determine aggregate state and error status boolean isConnecting = false; Status aggStatus = EMPTY_OK; for (Subchannel subchannel : getSubchannels()) { ConnectivityStateInfo stateInfo = getSubchannelStateInfoRef(subchannel).value; // This subchannel IDLE is not because of channel IDLE_TIMEOUT, // in which case LB is already shutdown. // RRLB will request connection immediately on subchannel IDLE. if (stateInfo.getState() == CONNECTING || stateInfo.getState() == IDLE) { isConnecting = true; } if (aggStatus == EMPTY_OK || !aggStatus.isOk()) { aggStatus = stateInfo.getStatus(); } } updateBalancingState(isConnecting ? CONNECTING : TRANSIENT_FAILURE, // If all subchannels are TRANSIENT_FAILURE, return the Status associated with // an arbitrary subchannel, otherwise return OK. new EmptyPicker(aggStatus)); } else { // initialize the Picker to a random start index to ensure that a high frequency of Picker // churn does not skew subchannel selection. int startIndex = random.nextInt(activeList.size()); updateBalancingState(READY, new ReadyPicker(activeList, startIndex, stickinessState)); } }
java
@SuppressWarnings("ReferenceEquality") private void updateBalancingState() { List<Subchannel> activeList = filterNonFailingSubchannels(getSubchannels()); if (activeList.isEmpty()) { // No READY subchannels, determine aggregate state and error status boolean isConnecting = false; Status aggStatus = EMPTY_OK; for (Subchannel subchannel : getSubchannels()) { ConnectivityStateInfo stateInfo = getSubchannelStateInfoRef(subchannel).value; // This subchannel IDLE is not because of channel IDLE_TIMEOUT, // in which case LB is already shutdown. // RRLB will request connection immediately on subchannel IDLE. if (stateInfo.getState() == CONNECTING || stateInfo.getState() == IDLE) { isConnecting = true; } if (aggStatus == EMPTY_OK || !aggStatus.isOk()) { aggStatus = stateInfo.getStatus(); } } updateBalancingState(isConnecting ? CONNECTING : TRANSIENT_FAILURE, // If all subchannels are TRANSIENT_FAILURE, return the Status associated with // an arbitrary subchannel, otherwise return OK. new EmptyPicker(aggStatus)); } else { // initialize the Picker to a random start index to ensure that a high frequency of Picker // churn does not skew subchannel selection. int startIndex = random.nextInt(activeList.size()); updateBalancingState(READY, new ReadyPicker(activeList, startIndex, stickinessState)); } }
[ "@", "SuppressWarnings", "(", "\"ReferenceEquality\"", ")", "private", "void", "updateBalancingState", "(", ")", "{", "List", "<", "Subchannel", ">", "activeList", "=", "filterNonFailingSubchannels", "(", "getSubchannels", "(", ")", ")", ";", "if", "(", "activeList", ".", "isEmpty", "(", ")", ")", "{", "// No READY subchannels, determine aggregate state and error status", "boolean", "isConnecting", "=", "false", ";", "Status", "aggStatus", "=", "EMPTY_OK", ";", "for", "(", "Subchannel", "subchannel", ":", "getSubchannels", "(", ")", ")", "{", "ConnectivityStateInfo", "stateInfo", "=", "getSubchannelStateInfoRef", "(", "subchannel", ")", ".", "value", ";", "// This subchannel IDLE is not because of channel IDLE_TIMEOUT,", "// in which case LB is already shutdown.", "// RRLB will request connection immediately on subchannel IDLE.", "if", "(", "stateInfo", ".", "getState", "(", ")", "==", "CONNECTING", "||", "stateInfo", ".", "getState", "(", ")", "==", "IDLE", ")", "{", "isConnecting", "=", "true", ";", "}", "if", "(", "aggStatus", "==", "EMPTY_OK", "||", "!", "aggStatus", ".", "isOk", "(", ")", ")", "{", "aggStatus", "=", "stateInfo", ".", "getStatus", "(", ")", ";", "}", "}", "updateBalancingState", "(", "isConnecting", "?", "CONNECTING", ":", "TRANSIENT_FAILURE", ",", "// If all subchannels are TRANSIENT_FAILURE, return the Status associated with", "// an arbitrary subchannel, otherwise return OK.", "new", "EmptyPicker", "(", "aggStatus", ")", ")", ";", "}", "else", "{", "// initialize the Picker to a random start index to ensure that a high frequency of Picker", "// churn does not skew subchannel selection.", "int", "startIndex", "=", "random", ".", "nextInt", "(", "activeList", ".", "size", "(", ")", ")", ";", "updateBalancingState", "(", "READY", ",", "new", "ReadyPicker", "(", "activeList", ",", "startIndex", ",", "stickinessState", ")", ")", ";", "}", "}" ]
Updates picker with the list of active subchannels (state == READY).
[ "Updates", "picker", "with", "the", "list", "of", "active", "subchannels", "(", "state", "==", "READY", ")", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/core/src/main/java/io/grpc/util/RoundRobinLoadBalancer.java#L201-L230
landawn/AbacusUtil
src/com/landawn/abacus/util/DateUtil.java
DateUtil.addDays
public static <T extends java.util.Date> T addDays(final T date, final int amount) { """ Adds a number of days to a date returning a new object. The original {@code Date} is unchanged. @param date the date, not null @param amount the amount to add, may be negative @return the new {@code Date} with the amount added @throws IllegalArgumentException if the date is null """ return roll(date, amount, CalendarUnit.DAY); }
java
public static <T extends java.util.Date> T addDays(final T date, final int amount) { return roll(date, amount, CalendarUnit.DAY); }
[ "public", "static", "<", "T", "extends", "java", ".", "util", ".", "Date", ">", "T", "addDays", "(", "final", "T", "date", ",", "final", "int", "amount", ")", "{", "return", "roll", "(", "date", ",", "amount", ",", "CalendarUnit", ".", "DAY", ")", ";", "}" ]
Adds a number of days to a date returning a new object. The original {@code Date} is unchanged. @param date the date, not null @param amount the amount to add, may be negative @return the new {@code Date} with the amount added @throws IllegalArgumentException if the date is null
[ "Adds", "a", "number", "of", "days", "to", "a", "date", "returning", "a", "new", "object", ".", "The", "original", "{", "@code", "Date", "}", "is", "unchanged", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/DateUtil.java#L993-L995
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WSelectToggleRenderer.java
WSelectToggleRenderer.doRender
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { """ Paints the given WSelectToggle. @param component the WSelectToggle to paint. @param renderContext the RenderContext to paint to. """ WSelectToggle toggle = (WSelectToggle) component; XmlStringBuilder xml = renderContext.getWriter(); xml.appendTagOpen("ui:selecttoggle"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); State state = toggle.getState(); if (State.ALL.equals(state)) { xml.appendAttribute("selected", "all"); } else if (State.NONE.equals(state)) { xml.appendAttribute("selected", "none"); } else { xml.appendAttribute("selected", "some"); } xml.appendOptionalAttribute("disabled", toggle.isDisabled(), "true"); xml.appendAttribute("target", toggle.getTarget().getId()); xml.appendAttribute("renderAs", toggle.isRenderAsText() ? "text" : "control"); xml.appendOptionalAttribute("roundTrip", !toggle.isClientSide(), "true"); xml.appendEnd(); }
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WSelectToggle toggle = (WSelectToggle) component; XmlStringBuilder xml = renderContext.getWriter(); xml.appendTagOpen("ui:selecttoggle"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", component.getHtmlClass()); xml.appendOptionalAttribute("track", component.isTracking(), "true"); State state = toggle.getState(); if (State.ALL.equals(state)) { xml.appendAttribute("selected", "all"); } else if (State.NONE.equals(state)) { xml.appendAttribute("selected", "none"); } else { xml.appendAttribute("selected", "some"); } xml.appendOptionalAttribute("disabled", toggle.isDisabled(), "true"); xml.appendAttribute("target", toggle.getTarget().getId()); xml.appendAttribute("renderAs", toggle.isRenderAsText() ? "text" : "control"); xml.appendOptionalAttribute("roundTrip", !toggle.isClientSide(), "true"); xml.appendEnd(); }
[ "@", "Override", "public", "void", "doRender", "(", "final", "WComponent", "component", ",", "final", "WebXmlRenderContext", "renderContext", ")", "{", "WSelectToggle", "toggle", "=", "(", "WSelectToggle", ")", "component", ";", "XmlStringBuilder", "xml", "=", "renderContext", ".", "getWriter", "(", ")", ";", "xml", ".", "appendTagOpen", "(", "\"ui:selecttoggle\"", ")", ";", "xml", ".", "appendAttribute", "(", "\"id\"", ",", "component", ".", "getId", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"class\"", ",", "component", ".", "getHtmlClass", "(", ")", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"track\"", ",", "component", ".", "isTracking", "(", ")", ",", "\"true\"", ")", ";", "State", "state", "=", "toggle", ".", "getState", "(", ")", ";", "if", "(", "State", ".", "ALL", ".", "equals", "(", "state", ")", ")", "{", "xml", ".", "appendAttribute", "(", "\"selected\"", ",", "\"all\"", ")", ";", "}", "else", "if", "(", "State", ".", "NONE", ".", "equals", "(", "state", ")", ")", "{", "xml", ".", "appendAttribute", "(", "\"selected\"", ",", "\"none\"", ")", ";", "}", "else", "{", "xml", ".", "appendAttribute", "(", "\"selected\"", ",", "\"some\"", ")", ";", "}", "xml", ".", "appendOptionalAttribute", "(", "\"disabled\"", ",", "toggle", ".", "isDisabled", "(", ")", ",", "\"true\"", ")", ";", "xml", ".", "appendAttribute", "(", "\"target\"", ",", "toggle", ".", "getTarget", "(", ")", ".", "getId", "(", ")", ")", ";", "xml", ".", "appendAttribute", "(", "\"renderAs\"", ",", "toggle", ".", "isRenderAsText", "(", ")", "?", "\"text\"", ":", "\"control\"", ")", ";", "xml", ".", "appendOptionalAttribute", "(", "\"roundTrip\"", ",", "!", "toggle", ".", "isClientSide", "(", ")", ",", "\"true\"", ")", ";", "xml", ".", "appendEnd", "(", ")", ";", "}" ]
Paints the given WSelectToggle. @param component the WSelectToggle to paint. @param renderContext the RenderContext to paint to.
[ "Paints", "the", "given", "WSelectToggle", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WSelectToggleRenderer.java#L23-L48
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionsImpl.java
PredictionsImpl.predictImageWithNoStoreWithServiceResponseAsync
public Observable<ServiceResponse<ImagePrediction>> predictImageWithNoStoreWithServiceResponseAsync(UUID projectId, byte[] imageData, PredictImageWithNoStoreOptionalParameter predictImageWithNoStoreOptionalParameter) { """ Predict an image without saving the result. @param projectId The project id @param imageData the InputStream value @param predictImageWithNoStoreOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ImagePrediction object """ if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (imageData == null) { throw new IllegalArgumentException("Parameter imageData is required and cannot be null."); } if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } final UUID iterationId = predictImageWithNoStoreOptionalParameter != null ? predictImageWithNoStoreOptionalParameter.iterationId() : null; final String application = predictImageWithNoStoreOptionalParameter != null ? predictImageWithNoStoreOptionalParameter.application() : null; return predictImageWithNoStoreWithServiceResponseAsync(projectId, imageData, iterationId, application); }
java
public Observable<ServiceResponse<ImagePrediction>> predictImageWithNoStoreWithServiceResponseAsync(UUID projectId, byte[] imageData, PredictImageWithNoStoreOptionalParameter predictImageWithNoStoreOptionalParameter) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (imageData == null) { throw new IllegalArgumentException("Parameter imageData is required and cannot be null."); } if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } final UUID iterationId = predictImageWithNoStoreOptionalParameter != null ? predictImageWithNoStoreOptionalParameter.iterationId() : null; final String application = predictImageWithNoStoreOptionalParameter != null ? predictImageWithNoStoreOptionalParameter.application() : null; return predictImageWithNoStoreWithServiceResponseAsync(projectId, imageData, iterationId, application); }
[ "public", "Observable", "<", "ServiceResponse", "<", "ImagePrediction", ">", ">", "predictImageWithNoStoreWithServiceResponseAsync", "(", "UUID", "projectId", ",", "byte", "[", "]", "imageData", ",", "PredictImageWithNoStoreOptionalParameter", "predictImageWithNoStoreOptionalParameter", ")", "{", "if", "(", "projectId", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter projectId is required and cannot be null.\"", ")", ";", "}", "if", "(", "imageData", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter imageData is required and cannot be null.\"", ")", ";", "}", "if", "(", "this", ".", "client", ".", "apiKey", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Parameter this.client.apiKey() is required and cannot be null.\"", ")", ";", "}", "final", "UUID", "iterationId", "=", "predictImageWithNoStoreOptionalParameter", "!=", "null", "?", "predictImageWithNoStoreOptionalParameter", ".", "iterationId", "(", ")", ":", "null", ";", "final", "String", "application", "=", "predictImageWithNoStoreOptionalParameter", "!=", "null", "?", "predictImageWithNoStoreOptionalParameter", ".", "application", "(", ")", ":", "null", ";", "return", "predictImageWithNoStoreWithServiceResponseAsync", "(", "projectId", ",", "imageData", ",", "iterationId", ",", "application", ")", ";", "}" ]
Predict an image without saving the result. @param projectId The project id @param imageData the InputStream value @param predictImageWithNoStoreOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ImagePrediction object
[ "Predict", "an", "image", "without", "saving", "the", "result", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionsImpl.java#L142-L156
sdl/odata
odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomWriter.java
AtomWriter.writeBodyFeed
public void writeBodyFeed(List<?> entities) throws ODataRenderException { """ Write feed body. @param entities The list of entities to fill in the XML stream. It can not {@code null}. @throws ODataRenderException In case it is not possible to write to the XML stream. """ checkNotNull(entities); try { for (Object entity : entities) { writeEntry(entity, true); } } catch (XMLStreamException | IllegalAccessException | NoSuchFieldException | ODataEdmException e) { LOG.error("Not possible to marshall feed stream XML"); throw new ODataRenderException("Not possible to marshall feed stream XML: ", e); } }
java
public void writeBodyFeed(List<?> entities) throws ODataRenderException { checkNotNull(entities); try { for (Object entity : entities) { writeEntry(entity, true); } } catch (XMLStreamException | IllegalAccessException | NoSuchFieldException | ODataEdmException e) { LOG.error("Not possible to marshall feed stream XML"); throw new ODataRenderException("Not possible to marshall feed stream XML: ", e); } }
[ "public", "void", "writeBodyFeed", "(", "List", "<", "?", ">", "entities", ")", "throws", "ODataRenderException", "{", "checkNotNull", "(", "entities", ")", ";", "try", "{", "for", "(", "Object", "entity", ":", "entities", ")", "{", "writeEntry", "(", "entity", ",", "true", ")", ";", "}", "}", "catch", "(", "XMLStreamException", "|", "IllegalAccessException", "|", "NoSuchFieldException", "|", "ODataEdmException", "e", ")", "{", "LOG", ".", "error", "(", "\"Not possible to marshall feed stream XML\"", ")", ";", "throw", "new", "ODataRenderException", "(", "\"Not possible to marshall feed stream XML: \"", ",", "e", ")", ";", "}", "}" ]
Write feed body. @param entities The list of entities to fill in the XML stream. It can not {@code null}. @throws ODataRenderException In case it is not possible to write to the XML stream.
[ "Write", "feed", "body", "." ]
train
https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomWriter.java#L249-L259
phax/ph-commons
ph-collection/src/main/java/com/helger/collection/map/MapHelper.java
MapHelper.arraySize
@Nonnegative public static int arraySize (final int nExpected, final float fLoadFactor) { """ Returns the least power of two smaller than or equal to 2<sup>30</sup> and larger than or equal to <code>Math.ceil( expected / f )</code>. @param nExpected the expected number of elements in a hash table. @param fLoadFactor the load factor. @return the minimum possible size for a backing array. @throws IllegalArgumentException if the necessary size is larger than 2<sup>30</sup>. """ final long s = Math.max (2, nextPowerOfTwo ((long) Math.ceil (nExpected / fLoadFactor))); if (s > (1 << 30)) throw new IllegalArgumentException ("Too large (" + nExpected + " expected elements with load factor " + fLoadFactor + ")"); return (int) s; }
java
@Nonnegative public static int arraySize (final int nExpected, final float fLoadFactor) { final long s = Math.max (2, nextPowerOfTwo ((long) Math.ceil (nExpected / fLoadFactor))); if (s > (1 << 30)) throw new IllegalArgumentException ("Too large (" + nExpected + " expected elements with load factor " + fLoadFactor + ")"); return (int) s; }
[ "@", "Nonnegative", "public", "static", "int", "arraySize", "(", "final", "int", "nExpected", ",", "final", "float", "fLoadFactor", ")", "{", "final", "long", "s", "=", "Math", ".", "max", "(", "2", ",", "nextPowerOfTwo", "(", "(", "long", ")", "Math", ".", "ceil", "(", "nExpected", "/", "fLoadFactor", ")", ")", ")", ";", "if", "(", "s", ">", "(", "1", "<<", "30", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Too large (\"", "+", "nExpected", "+", "\" expected elements with load factor \"", "+", "fLoadFactor", "+", "\")\"", ")", ";", "return", "(", "int", ")", "s", ";", "}" ]
Returns the least power of two smaller than or equal to 2<sup>30</sup> and larger than or equal to <code>Math.ceil( expected / f )</code>. @param nExpected the expected number of elements in a hash table. @param fLoadFactor the load factor. @return the minimum possible size for a backing array. @throws IllegalArgumentException if the necessary size is larger than 2<sup>30</sup>.
[ "Returns", "the", "least", "power", "of", "two", "smaller", "than", "or", "equal", "to", "2<sup", ">", "30<", "/", "sup", ">", "and", "larger", "than", "or", "equal", "to", "<code", ">", "Math", ".", "ceil", "(", "expected", "/", "f", ")", "<", "/", "code", ">", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-collection/src/main/java/com/helger/collection/map/MapHelper.java#L69-L80
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/util/MetaDataUtils.java
MetaDataUtils.serializeMetaData
public static String serializeMetaData(Map<String, List<String>> metaData) { """ Serializes a Map of String name/value pairs into the meta-data XML format. @param metaData the Map of meta-data as Map&lt;String,List&lt;String&gt;&gt; @return the meta-data values in XML form. """ StringBuilder buf = new StringBuilder(); if (metaData != null && metaData.size() > 0) { buf.append("<metadata xmlns=\"http://jivesoftware.com/protocol/workgroup\">"); for (String key : metaData.keySet()) { List<String> value = metaData.get(key); for (String v : value) { buf.append("<value name=\"").append(key).append("\">"); buf.append(StringUtils.escapeForXmlText(v)); buf.append("</value>"); } } buf.append("</metadata>"); } return buf.toString(); }
java
public static String serializeMetaData(Map<String, List<String>> metaData) { StringBuilder buf = new StringBuilder(); if (metaData != null && metaData.size() > 0) { buf.append("<metadata xmlns=\"http://jivesoftware.com/protocol/workgroup\">"); for (String key : metaData.keySet()) { List<String> value = metaData.get(key); for (String v : value) { buf.append("<value name=\"").append(key).append("\">"); buf.append(StringUtils.escapeForXmlText(v)); buf.append("</value>"); } } buf.append("</metadata>"); } return buf.toString(); }
[ "public", "static", "String", "serializeMetaData", "(", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "metaData", ")", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "metaData", "!=", "null", "&&", "metaData", ".", "size", "(", ")", ">", "0", ")", "{", "buf", ".", "append", "(", "\"<metadata xmlns=\\\"http://jivesoftware.com/protocol/workgroup\\\">\"", ")", ";", "for", "(", "String", "key", ":", "metaData", ".", "keySet", "(", ")", ")", "{", "List", "<", "String", ">", "value", "=", "metaData", ".", "get", "(", "key", ")", ";", "for", "(", "String", "v", ":", "value", ")", "{", "buf", ".", "append", "(", "\"<value name=\\\"\"", ")", ".", "append", "(", "key", ")", ".", "append", "(", "\"\\\">\"", ")", ";", "buf", ".", "append", "(", "StringUtils", ".", "escapeForXmlText", "(", "v", ")", ")", ";", "buf", ".", "append", "(", "\"</value>\"", ")", ";", "}", "}", "buf", ".", "append", "(", "\"</metadata>\"", ")", ";", "}", "return", "buf", ".", "toString", "(", ")", ";", "}" ]
Serializes a Map of String name/value pairs into the meta-data XML format. @param metaData the Map of meta-data as Map&lt;String,List&lt;String&gt;&gt; @return the meta-data values in XML form.
[ "Serializes", "a", "Map", "of", "String", "name", "/", "value", "pairs", "into", "the", "meta", "-", "data", "XML", "format", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/util/MetaDataUtils.java#L90-L105
jenetics/jenetics
jenetics/src/main/java/io/jenetics/engine/Limits.java
Limits.eps
private static double eps(final double s, final double l) { """ Calculate the relative mean difference between short and long filter. """ final double div = max(abs(s), abs(l)); return abs(s - l)/(div <= 10E-20 ? 1.0 : div); }
java
private static double eps(final double s, final double l) { final double div = max(abs(s), abs(l)); return abs(s - l)/(div <= 10E-20 ? 1.0 : div); }
[ "private", "static", "double", "eps", "(", "final", "double", "s", ",", "final", "double", "l", ")", "{", "final", "double", "div", "=", "max", "(", "abs", "(", "s", ")", ",", "abs", "(", "l", ")", ")", ";", "return", "abs", "(", "s", "-", "l", ")", "/", "(", "div", "<=", "10E-20", "?", "1.0", ":", "div", ")", ";", "}" ]
Calculate the relative mean difference between short and long filter.
[ "Calculate", "the", "relative", "mean", "difference", "between", "short", "and", "long", "filter", "." ]
train
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/engine/Limits.java#L319-L322
Talend/tesb-rt-se
locator/src/main/java/org/talend/esb/servicelocator/cxf/internal/CXFEndpointProvider.java
CXFEndpointProvider.createEPR
private static EndpointReferenceType createEPR(String address, SLProperties props) { """ Creates an endpoint reference from a given adress. @param address @param props @return """ EndpointReferenceType epr = WSAEndpointReferenceUtils.getEndpointReference(address); if (props != null) { addProperties(epr, props); } return epr; }
java
private static EndpointReferenceType createEPR(String address, SLProperties props) { EndpointReferenceType epr = WSAEndpointReferenceUtils.getEndpointReference(address); if (props != null) { addProperties(epr, props); } return epr; }
[ "private", "static", "EndpointReferenceType", "createEPR", "(", "String", "address", ",", "SLProperties", "props", ")", "{", "EndpointReferenceType", "epr", "=", "WSAEndpointReferenceUtils", ".", "getEndpointReference", "(", "address", ")", ";", "if", "(", "props", "!=", "null", ")", "{", "addProperties", "(", "epr", ",", "props", ")", ";", "}", "return", "epr", ";", "}" ]
Creates an endpoint reference from a given adress. @param address @param props @return
[ "Creates", "an", "endpoint", "reference", "from", "a", "given", "adress", "." ]
train
https://github.com/Talend/tesb-rt-se/blob/0a151a6d91ffff65ac4b5ee0c5b2c882ac28d886/locator/src/main/java/org/talend/esb/servicelocator/cxf/internal/CXFEndpointProvider.java#L279-L285
groupon/odo
proxylib/src/main/java/com/groupon/odo/proxylib/BackupService.java
BackupService.getConfigAndProfileData
public ConfigAndProfileBackup getConfigAndProfileData(int profileID, String clientUUID) throws Exception { """ Get the single profile backup (active overrides and active server group) for a client and the full odo backup @param profileID Id of profile to get configuration for @param clientUUID Client Id to export configuration @return Odo backup and client backup @throws Exception exception """ SingleProfileBackup singleProfileBackup = getProfileBackupData(profileID, clientUUID); Backup backup = getBackupData(); ConfigAndProfileBackup configAndProfileBackup = new ConfigAndProfileBackup(); configAndProfileBackup.setOdoBackup(backup); configAndProfileBackup.setProfileBackup(singleProfileBackup); return configAndProfileBackup; }
java
public ConfigAndProfileBackup getConfigAndProfileData(int profileID, String clientUUID) throws Exception { SingleProfileBackup singleProfileBackup = getProfileBackupData(profileID, clientUUID); Backup backup = getBackupData(); ConfigAndProfileBackup configAndProfileBackup = new ConfigAndProfileBackup(); configAndProfileBackup.setOdoBackup(backup); configAndProfileBackup.setProfileBackup(singleProfileBackup); return configAndProfileBackup; }
[ "public", "ConfigAndProfileBackup", "getConfigAndProfileData", "(", "int", "profileID", ",", "String", "clientUUID", ")", "throws", "Exception", "{", "SingleProfileBackup", "singleProfileBackup", "=", "getProfileBackupData", "(", "profileID", ",", "clientUUID", ")", ";", "Backup", "backup", "=", "getBackupData", "(", ")", ";", "ConfigAndProfileBackup", "configAndProfileBackup", "=", "new", "ConfigAndProfileBackup", "(", ")", ";", "configAndProfileBackup", ".", "setOdoBackup", "(", "backup", ")", ";", "configAndProfileBackup", ".", "setProfileBackup", "(", "singleProfileBackup", ")", ";", "return", "configAndProfileBackup", ";", "}" ]
Get the single profile backup (active overrides and active server group) for a client and the full odo backup @param profileID Id of profile to get configuration for @param clientUUID Client Id to export configuration @return Odo backup and client backup @throws Exception exception
[ "Get", "the", "single", "profile", "backup", "(", "active", "overrides", "and", "active", "server", "group", ")", "for", "a", "client", "and", "the", "full", "odo", "backup" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/BackupService.java#L171-L180
mgm-tp/jfunk
jfunk-common/src/main/java/com/mgmtp/jfunk/common/random/MathRandom.java
MathRandom.getDouble
public double getDouble(final double min, final double max) { """ Returns a random decimal number in the range of [min, max]. @param min minimum value for generated number @param max maximum value for generated number """ return min(min, max) + getDouble(abs(max - min)); }
java
public double getDouble(final double min, final double max) { return min(min, max) + getDouble(abs(max - min)); }
[ "public", "double", "getDouble", "(", "final", "double", "min", ",", "final", "double", "max", ")", "{", "return", "min", "(", "min", ",", "max", ")", "+", "getDouble", "(", "abs", "(", "max", "-", "min", ")", ")", ";", "}" ]
Returns a random decimal number in the range of [min, max]. @param min minimum value for generated number @param max maximum value for generated number
[ "Returns", "a", "random", "decimal", "number", "in", "the", "range", "of", "[", "min", "max", "]", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-common/src/main/java/com/mgmtp/jfunk/common/random/MathRandom.java#L115-L117
Chorus-bdd/Chorus
interpreter/chorus-pathscanner/src/main/java/org/chorusbdd/chorus/pathscanner/FilePathScanner.java
FilePathScanner.addFeaturesRecursively
private void addFeaturesRecursively(File directory, List<File> targetList, FileFilter fileFilter) { """ Recursively scans subdirectories, adding all feature files to the targetList. """ File[] files = directory.listFiles(); //sort the files here, since otherwise we get differences in execution order between 'nix, case sensitive //and win, case insensitive, toys 'r us Arrays.sort(files, new Comparator<File>() { public int compare(File o1, File o2) { return o1.getName().compareTo(o2.getName()); } }); for (File f : files) { if (f.isDirectory()) { addFeaturesRecursively(f, targetList, fileFilter); } else if (fileFilter.accept(f)) { targetList.add(f); } } }
java
private void addFeaturesRecursively(File directory, List<File> targetList, FileFilter fileFilter) { File[] files = directory.listFiles(); //sort the files here, since otherwise we get differences in execution order between 'nix, case sensitive //and win, case insensitive, toys 'r us Arrays.sort(files, new Comparator<File>() { public int compare(File o1, File o2) { return o1.getName().compareTo(o2.getName()); } }); for (File f : files) { if (f.isDirectory()) { addFeaturesRecursively(f, targetList, fileFilter); } else if (fileFilter.accept(f)) { targetList.add(f); } } }
[ "private", "void", "addFeaturesRecursively", "(", "File", "directory", ",", "List", "<", "File", ">", "targetList", ",", "FileFilter", "fileFilter", ")", "{", "File", "[", "]", "files", "=", "directory", ".", "listFiles", "(", ")", ";", "//sort the files here, since otherwise we get differences in execution order between 'nix, case sensitive", "//and win, case insensitive, toys 'r us", "Arrays", ".", "sort", "(", "files", ",", "new", "Comparator", "<", "File", ">", "(", ")", "{", "public", "int", "compare", "(", "File", "o1", ",", "File", "o2", ")", "{", "return", "o1", ".", "getName", "(", ")", ".", "compareTo", "(", "o2", ".", "getName", "(", ")", ")", ";", "}", "}", ")", ";", "for", "(", "File", "f", ":", "files", ")", "{", "if", "(", "f", ".", "isDirectory", "(", ")", ")", "{", "addFeaturesRecursively", "(", "f", ",", "targetList", ",", "fileFilter", ")", ";", "}", "else", "if", "(", "fileFilter", ".", "accept", "(", "f", ")", ")", "{", "targetList", ".", "add", "(", "f", ")", ";", "}", "}", "}" ]
Recursively scans subdirectories, adding all feature files to the targetList.
[ "Recursively", "scans", "subdirectories", "adding", "all", "feature", "files", "to", "the", "targetList", "." ]
train
https://github.com/Chorus-bdd/Chorus/blob/1eea7ca858876bce821bb49b43fd5b6ba1737997/interpreter/chorus-pathscanner/src/main/java/org/chorusbdd/chorus/pathscanner/FilePathScanner.java#L69-L87
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/TransportFormatAdapter.java
TransportFormatAdapter.writeJson
public static void writeJson(Serializable serializable, OutputStream output) throws IOException { """ Export JSON. @param serializable Serializable @param output OutputStream @throws IOException e """ TransportFormat.JSON.writeSerializableTo(serializable, output); }
java
public static void writeJson(Serializable serializable, OutputStream output) throws IOException { TransportFormat.JSON.writeSerializableTo(serializable, output); }
[ "public", "static", "void", "writeJson", "(", "Serializable", "serializable", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "TransportFormat", ".", "JSON", ".", "writeSerializableTo", "(", "serializable", ",", "output", ")", ";", "}" ]
Export JSON. @param serializable Serializable @param output OutputStream @throws IOException e
[ "Export", "JSON", "." ]
train
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/TransportFormatAdapter.java#L51-L54
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java
JvmTypesBuilder.setBody
public void setBody(/* @Nullable */ JvmExecutable logicalContainer, /* @Nullable */ XExpression expr) { """ Sets the given {@link JvmExecutable} as the logical container for the given {@link XExpression}. This defines the context and the scope for the given expression. Also it defines how the given JvmExecutable can be executed. For instance {@link org.eclipse.xtext.xbase.compiler.JvmModelGenerator} automatically translates any given {@link XExpression} into corresponding Java source code as the body of the given {@link JvmExecutable}. @param logicalContainer the {@link JvmExecutable} the expression is associated with. Can be <code>null</code> in which case this function does nothing. @param expr the expression. Can be <code>null</code> in which case this function does nothing. """ if (logicalContainer == null || expr == null) return; removeExistingBody(logicalContainer); associator.associateLogicalContainer(expr, logicalContainer); }
java
public void setBody(/* @Nullable */ JvmExecutable logicalContainer, /* @Nullable */ XExpression expr) { if (logicalContainer == null || expr == null) return; removeExistingBody(logicalContainer); associator.associateLogicalContainer(expr, logicalContainer); }
[ "public", "void", "setBody", "(", "/* @Nullable */", "JvmExecutable", "logicalContainer", ",", "/* @Nullable */", "XExpression", "expr", ")", "{", "if", "(", "logicalContainer", "==", "null", "||", "expr", "==", "null", ")", "return", ";", "removeExistingBody", "(", "logicalContainer", ")", ";", "associator", ".", "associateLogicalContainer", "(", "expr", ",", "logicalContainer", ")", ";", "}" ]
Sets the given {@link JvmExecutable} as the logical container for the given {@link XExpression}. This defines the context and the scope for the given expression. Also it defines how the given JvmExecutable can be executed. For instance {@link org.eclipse.xtext.xbase.compiler.JvmModelGenerator} automatically translates any given {@link XExpression} into corresponding Java source code as the body of the given {@link JvmExecutable}. @param logicalContainer the {@link JvmExecutable} the expression is associated with. Can be <code>null</code> in which case this function does nothing. @param expr the expression. Can be <code>null</code> in which case this function does nothing.
[ "Sets", "the", "given", "{", "@link", "JvmExecutable", "}", "as", "the", "logical", "container", "for", "the", "given", "{", "@link", "XExpression", "}", ".", "This", "defines", "the", "context", "and", "the", "scope", "for", "the", "given", "expression", ".", "Also", "it", "defines", "how", "the", "given", "JvmExecutable", "can", "be", "executed", ".", "For", "instance", "{", "@link", "org", ".", "eclipse", ".", "xtext", ".", "xbase", ".", "compiler", ".", "JvmModelGenerator", "}", "automatically", "translates", "any", "given", "{", "@link", "XExpression", "}", "into", "corresponding", "Java", "source", "code", "as", "the", "body", "of", "the", "given", "{", "@link", "JvmExecutable", "}", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java#L154-L159
JOML-CI/JOML
src/org/joml/Intersectiond.java
Intersectiond.intersectCircleCircle
public static boolean intersectCircleCircle(Vector2dc centerA, double radiusSquaredA, Vector2dc centerB, double radiusSquaredB, Vector3d intersectionCenterAndHL) { """ Test whether the one circle with center <code>centerA</code> and square radius <code>radiusSquaredA</code> intersects the other circle with center <code>centerB</code> and square radius <code>radiusSquaredB</code>, and store the center of the line segment of intersection in the <code>(x, y)</code> components of the supplied vector and the half-length of that line segment in the z component. <p> This method returns <code>false</code> when one circle contains the other circle. <p> Reference: <a href="http://gamedev.stackexchange.com/questions/75756/sphere-sphere-intersection-and-circle-sphere-intersection">http://gamedev.stackexchange.com</a> @param centerA the first circle's center @param radiusSquaredA the square of the first circle's radius @param centerB the second circle's center @param radiusSquaredB the square of the second circle's radius @param intersectionCenterAndHL will hold the center of the line segment of intersection in the <code>(x, y)</code> components and the half-length in the z component @return <code>true</code> iff both circles intersect; <code>false</code> otherwise """ return intersectCircleCircle(centerA.x(), centerA.y(), radiusSquaredA, centerB.x(), centerB.y(), radiusSquaredB, intersectionCenterAndHL); }
java
public static boolean intersectCircleCircle(Vector2dc centerA, double radiusSquaredA, Vector2dc centerB, double radiusSquaredB, Vector3d intersectionCenterAndHL) { return intersectCircleCircle(centerA.x(), centerA.y(), radiusSquaredA, centerB.x(), centerB.y(), radiusSquaredB, intersectionCenterAndHL); }
[ "public", "static", "boolean", "intersectCircleCircle", "(", "Vector2dc", "centerA", ",", "double", "radiusSquaredA", ",", "Vector2dc", "centerB", ",", "double", "radiusSquaredB", ",", "Vector3d", "intersectionCenterAndHL", ")", "{", "return", "intersectCircleCircle", "(", "centerA", ".", "x", "(", ")", ",", "centerA", ".", "y", "(", ")", ",", "radiusSquaredA", ",", "centerB", ".", "x", "(", ")", ",", "centerB", ".", "y", "(", ")", ",", "radiusSquaredB", ",", "intersectionCenterAndHL", ")", ";", "}" ]
Test whether the one circle with center <code>centerA</code> and square radius <code>radiusSquaredA</code> intersects the other circle with center <code>centerB</code> and square radius <code>radiusSquaredB</code>, and store the center of the line segment of intersection in the <code>(x, y)</code> components of the supplied vector and the half-length of that line segment in the z component. <p> This method returns <code>false</code> when one circle contains the other circle. <p> Reference: <a href="http://gamedev.stackexchange.com/questions/75756/sphere-sphere-intersection-and-circle-sphere-intersection">http://gamedev.stackexchange.com</a> @param centerA the first circle's center @param radiusSquaredA the square of the first circle's radius @param centerB the second circle's center @param radiusSquaredB the square of the second circle's radius @param intersectionCenterAndHL will hold the center of the line segment of intersection in the <code>(x, y)</code> components and the half-length in the z component @return <code>true</code> iff both circles intersect; <code>false</code> otherwise
[ "Test", "whether", "the", "one", "circle", "with", "center", "<code", ">", "centerA<", "/", "code", ">", "and", "square", "radius", "<code", ">", "radiusSquaredA<", "/", "code", ">", "intersects", "the", "other", "circle", "with", "center", "<code", ">", "centerB<", "/", "code", ">", "and", "square", "radius", "<code", ">", "radiusSquaredB<", "/", "code", ">", "and", "store", "the", "center", "of", "the", "line", "segment", "of", "intersection", "in", "the", "<code", ">", "(", "x", "y", ")", "<", "/", "code", ">", "components", "of", "the", "supplied", "vector", "and", "the", "half", "-", "length", "of", "that", "line", "segment", "in", "the", "z", "component", ".", "<p", ">", "This", "method", "returns", "<code", ">", "false<", "/", "code", ">", "when", "one", "circle", "contains", "the", "other", "circle", ".", "<p", ">", "Reference", ":", "<a", "href", "=", "http", ":", "//", "gamedev", ".", "stackexchange", ".", "com", "/", "questions", "/", "75756", "/", "sphere", "-", "sphere", "-", "intersection", "-", "and", "-", "circle", "-", "sphere", "-", "intersection", ">", "http", ":", "//", "gamedev", ".", "stackexchange", ".", "com<", "/", "a", ">" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Intersectiond.java#L3756-L3758
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cli/CliClient.java
CliClient.updateKsDefAttributes
private KsDef updateKsDefAttributes(Tree statement, KsDef ksDefToUpdate) { """ Used to update keyspace definition attributes @param statement - ANTRL tree representing current statement @param ksDefToUpdate - keyspace definition to update @return ksDef - updated keyspace definition """ KsDef ksDef = new KsDef(ksDefToUpdate); // removing all column definitions - thrift system_update_keyspace method requires that ksDef.setCf_defs(new LinkedList<CfDef>()); for(int i = 1; i < statement.getChildCount(); i += 2) { String currentStatement = statement.getChild(i).getText().toUpperCase(); AddKeyspaceArgument mArgument = AddKeyspaceArgument.valueOf(currentStatement); String mValue = statement.getChild(i + 1).getText(); switch(mArgument) { case PLACEMENT_STRATEGY: ksDef.setStrategy_class(CliUtils.unescapeSQLString(mValue)); break; case STRATEGY_OPTIONS: ksDef.setStrategy_options(getStrategyOptionsFromTree(statement.getChild(i + 1))); break; case DURABLE_WRITES: ksDef.setDurable_writes(Boolean.parseBoolean(mValue)); break; default: //must match one of the above or we'd throw an exception at the valueOf statement above. assert(false); } } // using default snitch options if strategy is NetworkTopologyStrategy and no options were set. if (ksDef.getStrategy_class().contains(".NetworkTopologyStrategy")) { Map<String, String> currentStrategyOptions = ksDef.getStrategy_options(); // adding default data center from SimpleSnitch if (currentStrategyOptions == null || currentStrategyOptions.isEmpty()) { SimpleSnitch snitch = new SimpleSnitch(); Map<String, String> options = new HashMap<String, String>(); try { options.put(snitch.getDatacenter(InetAddress.getLocalHost()), "1"); } catch (UnknownHostException e) { throw new RuntimeException(e); } ksDef.setStrategy_options(options); } } return ksDef; }
java
private KsDef updateKsDefAttributes(Tree statement, KsDef ksDefToUpdate) { KsDef ksDef = new KsDef(ksDefToUpdate); // removing all column definitions - thrift system_update_keyspace method requires that ksDef.setCf_defs(new LinkedList<CfDef>()); for(int i = 1; i < statement.getChildCount(); i += 2) { String currentStatement = statement.getChild(i).getText().toUpperCase(); AddKeyspaceArgument mArgument = AddKeyspaceArgument.valueOf(currentStatement); String mValue = statement.getChild(i + 1).getText(); switch(mArgument) { case PLACEMENT_STRATEGY: ksDef.setStrategy_class(CliUtils.unescapeSQLString(mValue)); break; case STRATEGY_OPTIONS: ksDef.setStrategy_options(getStrategyOptionsFromTree(statement.getChild(i + 1))); break; case DURABLE_WRITES: ksDef.setDurable_writes(Boolean.parseBoolean(mValue)); break; default: //must match one of the above or we'd throw an exception at the valueOf statement above. assert(false); } } // using default snitch options if strategy is NetworkTopologyStrategy and no options were set. if (ksDef.getStrategy_class().contains(".NetworkTopologyStrategy")) { Map<String, String> currentStrategyOptions = ksDef.getStrategy_options(); // adding default data center from SimpleSnitch if (currentStrategyOptions == null || currentStrategyOptions.isEmpty()) { SimpleSnitch snitch = new SimpleSnitch(); Map<String, String> options = new HashMap<String, String>(); try { options.put(snitch.getDatacenter(InetAddress.getLocalHost()), "1"); } catch (UnknownHostException e) { throw new RuntimeException(e); } ksDef.setStrategy_options(options); } } return ksDef; }
[ "private", "KsDef", "updateKsDefAttributes", "(", "Tree", "statement", ",", "KsDef", "ksDefToUpdate", ")", "{", "KsDef", "ksDef", "=", "new", "KsDef", "(", "ksDefToUpdate", ")", ";", "// removing all column definitions - thrift system_update_keyspace method requires that", "ksDef", ".", "setCf_defs", "(", "new", "LinkedList", "<", "CfDef", ">", "(", ")", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "statement", ".", "getChildCount", "(", ")", ";", "i", "+=", "2", ")", "{", "String", "currentStatement", "=", "statement", ".", "getChild", "(", "i", ")", ".", "getText", "(", ")", ".", "toUpperCase", "(", ")", ";", "AddKeyspaceArgument", "mArgument", "=", "AddKeyspaceArgument", ".", "valueOf", "(", "currentStatement", ")", ";", "String", "mValue", "=", "statement", ".", "getChild", "(", "i", "+", "1", ")", ".", "getText", "(", ")", ";", "switch", "(", "mArgument", ")", "{", "case", "PLACEMENT_STRATEGY", ":", "ksDef", ".", "setStrategy_class", "(", "CliUtils", ".", "unescapeSQLString", "(", "mValue", ")", ")", ";", "break", ";", "case", "STRATEGY_OPTIONS", ":", "ksDef", ".", "setStrategy_options", "(", "getStrategyOptionsFromTree", "(", "statement", ".", "getChild", "(", "i", "+", "1", ")", ")", ")", ";", "break", ";", "case", "DURABLE_WRITES", ":", "ksDef", ".", "setDurable_writes", "(", "Boolean", ".", "parseBoolean", "(", "mValue", ")", ")", ";", "break", ";", "default", ":", "//must match one of the above or we'd throw an exception at the valueOf statement above.", "assert", "(", "false", ")", ";", "}", "}", "// using default snitch options if strategy is NetworkTopologyStrategy and no options were set.", "if", "(", "ksDef", ".", "getStrategy_class", "(", ")", ".", "contains", "(", "\".NetworkTopologyStrategy\"", ")", ")", "{", "Map", "<", "String", ",", "String", ">", "currentStrategyOptions", "=", "ksDef", ".", "getStrategy_options", "(", ")", ";", "// adding default data center from SimpleSnitch", "if", "(", "currentStrategyOptions", "==", "null", "||", "currentStrategyOptions", ".", "isEmpty", "(", ")", ")", "{", "SimpleSnitch", "snitch", "=", "new", "SimpleSnitch", "(", ")", ";", "Map", "<", "String", ",", "String", ">", "options", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "try", "{", "options", ".", "put", "(", "snitch", ".", "getDatacenter", "(", "InetAddress", ".", "getLocalHost", "(", ")", ")", ",", "\"1\"", ")", ";", "}", "catch", "(", "UnknownHostException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "ksDef", ".", "setStrategy_options", "(", "options", ")", ";", "}", "}", "return", "ksDef", ";", "}" ]
Used to update keyspace definition attributes @param statement - ANTRL tree representing current statement @param ksDefToUpdate - keyspace definition to update @return ksDef - updated keyspace definition
[ "Used", "to", "update", "keyspace", "definition", "attributes" ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cli/CliClient.java#L1201-L1254
RestComm/media-core
rtp/src/main/java/org/restcomm/media/core/rtp/SsrcGenerator.java
SsrcGenerator.bytesToUIntLong
static long bytesToUIntLong(byte[] bytes, int index) { """ Combines four bytes (most significant bit first) into a 32 bit unsigned integer. @param bytes @param index of most significant byte @return long with the 32 bit unsigned integer """ long accum = 0; int i = 3; for (int shiftBy = 0; shiftBy < 32; shiftBy += 8) { accum |= ((long) (bytes[index + i] & 0xff)) << shiftBy; i--; } return accum; }
java
static long bytesToUIntLong(byte[] bytes, int index) { long accum = 0; int i = 3; for (int shiftBy = 0; shiftBy < 32; shiftBy += 8) { accum |= ((long) (bytes[index + i] & 0xff)) << shiftBy; i--; } return accum; }
[ "static", "long", "bytesToUIntLong", "(", "byte", "[", "]", "bytes", ",", "int", "index", ")", "{", "long", "accum", "=", "0", ";", "int", "i", "=", "3", ";", "for", "(", "int", "shiftBy", "=", "0", ";", "shiftBy", "<", "32", ";", "shiftBy", "+=", "8", ")", "{", "accum", "|=", "(", "(", "long", ")", "(", "bytes", "[", "index", "+", "i", "]", "&", "0xff", ")", ")", "<<", "shiftBy", ";", "i", "--", ";", "}", "return", "accum", ";", "}" ]
Combines four bytes (most significant bit first) into a 32 bit unsigned integer. @param bytes @param index of most significant byte @return long with the 32 bit unsigned integer
[ "Combines", "four", "bytes", "(", "most", "significant", "bit", "first", ")", "into", "a", "32", "bit", "unsigned", "integer", "." ]
train
https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/rtp/src/main/java/org/restcomm/media/core/rtp/SsrcGenerator.java#L51-L59
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/SeaGlassContext.java
SeaGlassContext.getContext
public static SeaGlassContext getContext(Class type, JComponent component, Region region, SynthStyle style, int state) { """ The method used to get a context. @param type the class of the context. @param component the component. @param region the region. @param style the style. @param state the state. @return the newly constructed context, corresponding to the arguments. """ SeaGlassContext context = null; synchronized (contextMap) { List instances = (List) contextMap.get(type); if (instances != null) { int size = instances.size(); if (size > 0) { context = (SeaGlassContext) instances.remove(size - 1); } } } if (context == null) { try { context = (SeaGlassContext) type.newInstance(); } catch (IllegalAccessException iae) { iae.printStackTrace(); } catch (InstantiationException ie) { ie.printStackTrace(); } } context.reset(component, region, style, state); return context; }
java
public static SeaGlassContext getContext(Class type, JComponent component, Region region, SynthStyle style, int state) { SeaGlassContext context = null; synchronized (contextMap) { List instances = (List) contextMap.get(type); if (instances != null) { int size = instances.size(); if (size > 0) { context = (SeaGlassContext) instances.remove(size - 1); } } } if (context == null) { try { context = (SeaGlassContext) type.newInstance(); } catch (IllegalAccessException iae) { iae.printStackTrace(); } catch (InstantiationException ie) { ie.printStackTrace(); } } context.reset(component, region, style, state); return context; }
[ "public", "static", "SeaGlassContext", "getContext", "(", "Class", "type", ",", "JComponent", "component", ",", "Region", "region", ",", "SynthStyle", "style", ",", "int", "state", ")", "{", "SeaGlassContext", "context", "=", "null", ";", "synchronized", "(", "contextMap", ")", "{", "List", "instances", "=", "(", "List", ")", "contextMap", ".", "get", "(", "type", ")", ";", "if", "(", "instances", "!=", "null", ")", "{", "int", "size", "=", "instances", ".", "size", "(", ")", ";", "if", "(", "size", ">", "0", ")", "{", "context", "=", "(", "SeaGlassContext", ")", "instances", ".", "remove", "(", "size", "-", "1", ")", ";", "}", "}", "}", "if", "(", "context", "==", "null", ")", "{", "try", "{", "context", "=", "(", "SeaGlassContext", ")", "type", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "IllegalAccessException", "iae", ")", "{", "iae", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "InstantiationException", "ie", ")", "{", "ie", ".", "printStackTrace", "(", ")", ";", "}", "}", "context", ".", "reset", "(", "component", ",", "region", ",", "style", ",", "state", ")", ";", "return", "context", ";", "}" ]
The method used to get a context. @param type the class of the context. @param component the component. @param region the region. @param style the style. @param state the state. @return the newly constructed context, corresponding to the arguments.
[ "The", "method", "used", "to", "get", "a", "context", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/SeaGlassContext.java#L127-L156
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/Code.java
Code.invokeStatic
public <R> void invokeStatic(MethodId<?, R> method, Local<? super R> target, Local<?>... args) { """ Calls the static method {@code method} using {@code args} and assigns the result to {@code target}. @param target the local to receive the method's return value, or {@code null} if the return type is {@code void} or if its value not needed. """ invoke(Rops.opInvokeStatic(method.prototype(true)), method, target, null, args); }
java
public <R> void invokeStatic(MethodId<?, R> method, Local<? super R> target, Local<?>... args) { invoke(Rops.opInvokeStatic(method.prototype(true)), method, target, null, args); }
[ "public", "<", "R", ">", "void", "invokeStatic", "(", "MethodId", "<", "?", ",", "R", ">", "method", ",", "Local", "<", "?", "super", "R", ">", "target", ",", "Local", "<", "?", ">", "...", "args", ")", "{", "invoke", "(", "Rops", ".", "opInvokeStatic", "(", "method", ".", "prototype", "(", "true", ")", ")", ",", "method", ",", "target", ",", "null", ",", "args", ")", ";", "}" ]
Calls the static method {@code method} using {@code args} and assigns the result to {@code target}. @param target the local to receive the method's return value, or {@code null} if the return type is {@code void} or if its value not needed.
[ "Calls", "the", "static", "method", "{", "@code", "method", "}", "using", "{", "@code", "args", "}", "and", "assigns", "the", "result", "to", "{", "@code", "target", "}", "." ]
train
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L645-L647
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java
ApiOvhDedicatedserver.serviceName_install_compatibleTemplatePartitionSchemes_GET
public ArrayList<String> serviceName_install_compatibleTemplatePartitionSchemes_GET(String serviceName, String templateName) throws IOException { """ Retrieve compatible install template partitions scheme REST: GET /dedicated/server/{serviceName}/install/compatibleTemplatePartitionSchemes @param templateName [required] @param serviceName [required] The internal name of your dedicated server """ String qPath = "/dedicated/server/{serviceName}/install/compatibleTemplatePartitionSchemes"; StringBuilder sb = path(qPath, serviceName); query(sb, "templateName", templateName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
java
public ArrayList<String> serviceName_install_compatibleTemplatePartitionSchemes_GET(String serviceName, String templateName) throws IOException { String qPath = "/dedicated/server/{serviceName}/install/compatibleTemplatePartitionSchemes"; StringBuilder sb = path(qPath, serviceName); query(sb, "templateName", templateName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
[ "public", "ArrayList", "<", "String", ">", "serviceName_install_compatibleTemplatePartitionSchemes_GET", "(", "String", "serviceName", ",", "String", "templateName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicated/server/{serviceName}/install/compatibleTemplatePartitionSchemes\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "query", "(", "sb", ",", "\"templateName\"", ",", "templateName", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t1", ")", ";", "}" ]
Retrieve compatible install template partitions scheme REST: GET /dedicated/server/{serviceName}/install/compatibleTemplatePartitionSchemes @param templateName [required] @param serviceName [required] The internal name of your dedicated server
[ "Retrieve", "compatible", "install", "template", "partitions", "scheme" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L1659-L1665
xdcrafts/flower
flower-tools/src/main/java/com/github/xdcrafts/flower/tools/ClassApi.java
ClassApi.findMethod
public static Method findMethod(Class clazz, String methodName) { """ Finds method with name, throws exception if no method found or there are many of them. """ final List<Method> methods = getDeclaredMethodsRecursively(clazz).get(methodName); if (methods.isEmpty()) { throw new IllegalArgumentException(clazz.getName() + "::" + methodName + " not found"); } final List<Method> specificMethods; if (methods.size() > 1) { specificMethods = methods.stream().filter(m -> m.getReturnType() != Object.class).collect(Collectors.toList()); } else { specificMethods = methods; } if (specificMethods.size() != 1) { throw new IllegalArgumentException( clazz.getName() + "::" + methodName + " more then one method found, can not decide which one to use. " + methods ); } return specificMethods.get(0); }
java
public static Method findMethod(Class clazz, String methodName) { final List<Method> methods = getDeclaredMethodsRecursively(clazz).get(methodName); if (methods.isEmpty()) { throw new IllegalArgumentException(clazz.getName() + "::" + methodName + " not found"); } final List<Method> specificMethods; if (methods.size() > 1) { specificMethods = methods.stream().filter(m -> m.getReturnType() != Object.class).collect(Collectors.toList()); } else { specificMethods = methods; } if (specificMethods.size() != 1) { throw new IllegalArgumentException( clazz.getName() + "::" + methodName + " more then one method found, can not decide which one to use. " + methods ); } return specificMethods.get(0); }
[ "public", "static", "Method", "findMethod", "(", "Class", "clazz", ",", "String", "methodName", ")", "{", "final", "List", "<", "Method", ">", "methods", "=", "getDeclaredMethodsRecursively", "(", "clazz", ")", ".", "get", "(", "methodName", ")", ";", "if", "(", "methods", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "clazz", ".", "getName", "(", ")", "+", "\"::\"", "+", "methodName", "+", "\" not found\"", ")", ";", "}", "final", "List", "<", "Method", ">", "specificMethods", ";", "if", "(", "methods", ".", "size", "(", ")", ">", "1", ")", "{", "specificMethods", "=", "methods", ".", "stream", "(", ")", ".", "filter", "(", "m", "->", "m", ".", "getReturnType", "(", ")", "!=", "Object", ".", "class", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}", "else", "{", "specificMethods", "=", "methods", ";", "}", "if", "(", "specificMethods", ".", "size", "(", ")", "!=", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "clazz", ".", "getName", "(", ")", "+", "\"::\"", "+", "methodName", "+", "\" more then one method found, can not decide which one to use. \"", "+", "methods", ")", ";", "}", "return", "specificMethods", ".", "get", "(", "0", ")", ";", "}" ]
Finds method with name, throws exception if no method found or there are many of them.
[ "Finds", "method", "with", "name", "throws", "exception", "if", "no", "method", "found", "or", "there", "are", "many", "of", "them", "." ]
train
https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/ClassApi.java#L135-L155
kikinteractive/ice
ice/src/main/java/com/kik/config/ice/internal/ConfigDescriptorFactory.java
ConfigDescriptorFactory.buildDescriptors
public List<ConfigDescriptor> buildDescriptors(Class<?> configClass, Optional<String> scopeOpt) { """ Build a {@link ConfigDescriptor} given a configuration interface reference. @param configClass config interface to build descriptors for @param scopeOpt optional scope name to include in config descriptors. @return A list of {@link ConfigDescriptor} instances describing the given config interface and scope name. """ if (!StaticConfigHelper.isValidConfigInterface(configClass)) { // condition is already logged. throw new ConfigException("Invalid Configuration class."); } List<ConfigDescriptor> descriptors = Lists.newArrayList(); for (Method method : configClass.getMethods()) { StaticConfigHelper.MethodValidationState validationState = StaticConfigHelper.isValidConfigInterfaceMethod(method); switch (validationState) { case OK: descriptors.add(internalBuildDescriptor(method, scopeOpt, getMethodDefaultValue(method))); case IS_DEFAULT: // Skip default interface methods break; default: log.debug("Configuration class {} was found to be invalid: {}", configClass.getName(), validationState.name()); throw new ConfigException("Invalid Configuration class: {}", validationState.name()); } } return descriptors; }
java
public List<ConfigDescriptor> buildDescriptors(Class<?> configClass, Optional<String> scopeOpt) { if (!StaticConfigHelper.isValidConfigInterface(configClass)) { // condition is already logged. throw new ConfigException("Invalid Configuration class."); } List<ConfigDescriptor> descriptors = Lists.newArrayList(); for (Method method : configClass.getMethods()) { StaticConfigHelper.MethodValidationState validationState = StaticConfigHelper.isValidConfigInterfaceMethod(method); switch (validationState) { case OK: descriptors.add(internalBuildDescriptor(method, scopeOpt, getMethodDefaultValue(method))); case IS_DEFAULT: // Skip default interface methods break; default: log.debug("Configuration class {} was found to be invalid: {}", configClass.getName(), validationState.name()); throw new ConfigException("Invalid Configuration class: {}", validationState.name()); } } return descriptors; }
[ "public", "List", "<", "ConfigDescriptor", ">", "buildDescriptors", "(", "Class", "<", "?", ">", "configClass", ",", "Optional", "<", "String", ">", "scopeOpt", ")", "{", "if", "(", "!", "StaticConfigHelper", ".", "isValidConfigInterface", "(", "configClass", ")", ")", "{", "// condition is already logged.", "throw", "new", "ConfigException", "(", "\"Invalid Configuration class.\"", ")", ";", "}", "List", "<", "ConfigDescriptor", ">", "descriptors", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "Method", "method", ":", "configClass", ".", "getMethods", "(", ")", ")", "{", "StaticConfigHelper", ".", "MethodValidationState", "validationState", "=", "StaticConfigHelper", ".", "isValidConfigInterfaceMethod", "(", "method", ")", ";", "switch", "(", "validationState", ")", "{", "case", "OK", ":", "descriptors", ".", "add", "(", "internalBuildDescriptor", "(", "method", ",", "scopeOpt", ",", "getMethodDefaultValue", "(", "method", ")", ")", ")", ";", "case", "IS_DEFAULT", ":", "// Skip default interface methods", "break", ";", "default", ":", "log", ".", "debug", "(", "\"Configuration class {} was found to be invalid: {}\"", ",", "configClass", ".", "getName", "(", ")", ",", "validationState", ".", "name", "(", ")", ")", ";", "throw", "new", "ConfigException", "(", "\"Invalid Configuration class: {}\"", ",", "validationState", ".", "name", "(", ")", ")", ";", "}", "}", "return", "descriptors", ";", "}" ]
Build a {@link ConfigDescriptor} given a configuration interface reference. @param configClass config interface to build descriptors for @param scopeOpt optional scope name to include in config descriptors. @return A list of {@link ConfigDescriptor} instances describing the given config interface and scope name.
[ "Build", "a", "{", "@link", "ConfigDescriptor", "}", "given", "a", "configuration", "interface", "reference", "." ]
train
https://github.com/kikinteractive/ice/blob/0c58d7bf2d9f6504892d0768d6022fcfa6df7514/ice/src/main/java/com/kik/config/ice/internal/ConfigDescriptorFactory.java#L76-L101
hawkular/hawkular-apm
server/rest/src/main/java/org/hawkular/apm/server/rest/RESTServiceUtil.java
RESTServiceUtil.decodeProperties
public static void decodeProperties(Set<PropertyCriteria> properties, String encoded) { """ This method processes a comma separated list of properties, defined as a name|value pair. @param properties The properties map @param encoded The string containing the encoded properties """ if (encoded != null && !encoded.trim().isEmpty()) { StringTokenizer st = new StringTokenizer(encoded, ","); while (st.hasMoreTokens()) { String token = st.nextToken(); String[] parts = token.split("[|]"); if (parts.length >= 2) { String name = parts[0].trim(); String value = parts[1].trim(); Operator op = Operator.HAS; if (parts.length > 2) { op = Operator.valueOf(parts[2].trim()); } log.tracef("Extracted property name [%s] value [%s] operator [%s]", name, value, op); properties.add(new PropertyCriteria(name, value, op)); } } } }
java
public static void decodeProperties(Set<PropertyCriteria> properties, String encoded) { if (encoded != null && !encoded.trim().isEmpty()) { StringTokenizer st = new StringTokenizer(encoded, ","); while (st.hasMoreTokens()) { String token = st.nextToken(); String[] parts = token.split("[|]"); if (parts.length >= 2) { String name = parts[0].trim(); String value = parts[1].trim(); Operator op = Operator.HAS; if (parts.length > 2) { op = Operator.valueOf(parts[2].trim()); } log.tracef("Extracted property name [%s] value [%s] operator [%s]", name, value, op); properties.add(new PropertyCriteria(name, value, op)); } } } }
[ "public", "static", "void", "decodeProperties", "(", "Set", "<", "PropertyCriteria", ">", "properties", ",", "String", "encoded", ")", "{", "if", "(", "encoded", "!=", "null", "&&", "!", "encoded", ".", "trim", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "encoded", ",", "\",\"", ")", ";", "while", "(", "st", ".", "hasMoreTokens", "(", ")", ")", "{", "String", "token", "=", "st", ".", "nextToken", "(", ")", ";", "String", "[", "]", "parts", "=", "token", ".", "split", "(", "\"[|]\"", ")", ";", "if", "(", "parts", ".", "length", ">=", "2", ")", "{", "String", "name", "=", "parts", "[", "0", "]", ".", "trim", "(", ")", ";", "String", "value", "=", "parts", "[", "1", "]", ".", "trim", "(", ")", ";", "Operator", "op", "=", "Operator", ".", "HAS", ";", "if", "(", "parts", ".", "length", ">", "2", ")", "{", "op", "=", "Operator", ".", "valueOf", "(", "parts", "[", "2", "]", ".", "trim", "(", ")", ")", ";", "}", "log", ".", "tracef", "(", "\"Extracted property name [%s] value [%s] operator [%s]\"", ",", "name", ",", "value", ",", "op", ")", ";", "properties", ".", "add", "(", "new", "PropertyCriteria", "(", "name", ",", "value", ",", "op", ")", ")", ";", "}", "}", "}", "}" ]
This method processes a comma separated list of properties, defined as a name|value pair. @param properties The properties map @param encoded The string containing the encoded properties
[ "This", "method", "processes", "a", "comma", "separated", "list", "of", "properties", "defined", "as", "a", "name|value", "pair", "." ]
train
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/server/rest/src/main/java/org/hawkular/apm/server/rest/RESTServiceUtil.java#L44-L65
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/compression/CompressionConfigParser.java
CompressionConfigParser.getCompressionType
public static String getCompressionType(Map<String, Object> properties) { """ Return compression type @param properties Compression config settings @return String representing compression type, null if none exists """ return (String) properties.get(COMPRESSION_TYPE_KEY); }
java
public static String getCompressionType(Map<String, Object> properties) { return (String) properties.get(COMPRESSION_TYPE_KEY); }
[ "public", "static", "String", "getCompressionType", "(", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "return", "(", "String", ")", "properties", ".", "get", "(", "COMPRESSION_TYPE_KEY", ")", ";", "}" ]
Return compression type @param properties Compression config settings @return String representing compression type, null if none exists
[ "Return", "compression", "type" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/compression/CompressionConfigParser.java#L57-L59
betfair/cougar
baseline/baseline-app/src/main/java/com/betfair/cougar/baseline/BaselineServiceImpl.java
BaselineServiceImpl.subscribeToMatchedBet
@Override public void subscribeToMatchedBet(ExecutionContext ctx, Object[] args, ExecutionObserver executionObserver) { """ Please note that this Service method is called by the Execution Venue to establish a communication channel from the transport to the Application to publish events. In essence, the transport subscribes to the app, so this method is called once for each publisher at application initialisation. You should never be calling this directly. The application should hold onto the passed in observer, and call onResult on that observer to emit an event. @param ctx @param args @param executionObserver """ if (getEventTransportIdentity(ctx).getPrincipal().getName().equals(SONIC_TRANSPORT_INSTANCE_ONE)) { this.matchedBetObserver = executionObserver; } }
java
@Override public void subscribeToMatchedBet(ExecutionContext ctx, Object[] args, ExecutionObserver executionObserver) { if (getEventTransportIdentity(ctx).getPrincipal().getName().equals(SONIC_TRANSPORT_INSTANCE_ONE)) { this.matchedBetObserver = executionObserver; } }
[ "@", "Override", "public", "void", "subscribeToMatchedBet", "(", "ExecutionContext", "ctx", ",", "Object", "[", "]", "args", ",", "ExecutionObserver", "executionObserver", ")", "{", "if", "(", "getEventTransportIdentity", "(", "ctx", ")", ".", "getPrincipal", "(", ")", ".", "getName", "(", ")", ".", "equals", "(", "SONIC_TRANSPORT_INSTANCE_ONE", ")", ")", "{", "this", ".", "matchedBetObserver", "=", "executionObserver", ";", "}", "}" ]
Please note that this Service method is called by the Execution Venue to establish a communication channel from the transport to the Application to publish events. In essence, the transport subscribes to the app, so this method is called once for each publisher at application initialisation. You should never be calling this directly. The application should hold onto the passed in observer, and call onResult on that observer to emit an event. @param ctx @param args @param executionObserver
[ "Please", "note", "that", "this", "Service", "method", "is", "called", "by", "the", "Execution", "Venue", "to", "establish", "a", "communication", "channel", "from", "the", "transport", "to", "the", "Application", "to", "publish", "events", ".", "In", "essence", "the", "transport", "subscribes", "to", "the", "app", "so", "this", "method", "is", "called", "once", "for", "each", "publisher", "at", "application", "initialisation", ".", "You", "should", "never", "be", "calling", "this", "directly", ".", "The", "application", "should", "hold", "onto", "the", "passed", "in", "observer", "and", "call", "onResult", "on", "that", "observer", "to", "emit", "an", "event", "." ]
train
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/baseline/baseline-app/src/main/java/com/betfair/cougar/baseline/BaselineServiceImpl.java#L1930-L1935
jglobus/JGlobus
gridftp/src/main/java/org/globus/ftp/FTPClient.java
FTPClient.setProtectionBufferSize
public void setProtectionBufferSize(int size) throws IOException, ServerException { """ Sets protection buffer size (defined in RFC 2228) @param size the size of buffer """ if (size <= 0) { throw new IllegalArgumentException("size <= 0"); } localServer.setProtectionBufferSize(size); try { Command cmd = new Command("PBSZ", Integer.toString(size)); controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused setting protection buffer size"); } this.session.protectionBufferSize = size; }
java
public void setProtectionBufferSize(int size) throws IOException, ServerException { if (size <= 0) { throw new IllegalArgumentException("size <= 0"); } localServer.setProtectionBufferSize(size); try { Command cmd = new Command("PBSZ", Integer.toString(size)); controlChannel.execute(cmd); } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } catch (UnexpectedReplyCodeException urce) { throw ServerException.embedUnexpectedReplyCodeException( urce, "Server refused setting protection buffer size"); } this.session.protectionBufferSize = size; }
[ "public", "void", "setProtectionBufferSize", "(", "int", "size", ")", "throws", "IOException", ",", "ServerException", "{", "if", "(", "size", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"size <= 0\"", ")", ";", "}", "localServer", ".", "setProtectionBufferSize", "(", "size", ")", ";", "try", "{", "Command", "cmd", "=", "new", "Command", "(", "\"PBSZ\"", ",", "Integer", ".", "toString", "(", "size", ")", ")", ";", "controlChannel", ".", "execute", "(", "cmd", ")", ";", "}", "catch", "(", "FTPReplyParseException", "rpe", ")", "{", "throw", "ServerException", ".", "embedFTPReplyParseException", "(", "rpe", ")", ";", "}", "catch", "(", "UnexpectedReplyCodeException", "urce", ")", "{", "throw", "ServerException", ".", "embedUnexpectedReplyCodeException", "(", "urce", ",", "\"Server refused setting protection buffer size\"", ")", ";", "}", "this", ".", "session", ".", "protectionBufferSize", "=", "size", ";", "}" ]
Sets protection buffer size (defined in RFC 2228) @param size the size of buffer
[ "Sets", "protection", "buffer", "size", "(", "defined", "in", "RFC", "2228", ")" ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gridftp/src/main/java/org/globus/ftp/FTPClient.java#L878-L897
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java
MultiViewOps.homographyStereo3Pts
public static DMatrixRMaj homographyStereo3Pts( DMatrixRMaj F , AssociatedPair p1, AssociatedPair p2, AssociatedPair p3) { """ Computes the homography induced from a planar surface when viewed from two views using correspondences of three points. Observations must be on the planar surface. @see boofcv.alg.geo.h.HomographyInducedStereo3Pts @param F Fundamental matrix @param p1 Associated point observation @param p2 Associated point observation @param p3 Associated point observation @return The homography from view 1 to view 2 or null if it fails """ HomographyInducedStereo3Pts alg = new HomographyInducedStereo3Pts(); alg.setFundamental(F,null); if( !alg.process(p1,p2,p3) ) return null; return alg.getHomography(); }
java
public static DMatrixRMaj homographyStereo3Pts( DMatrixRMaj F , AssociatedPair p1, AssociatedPair p2, AssociatedPair p3) { HomographyInducedStereo3Pts alg = new HomographyInducedStereo3Pts(); alg.setFundamental(F,null); if( !alg.process(p1,p2,p3) ) return null; return alg.getHomography(); }
[ "public", "static", "DMatrixRMaj", "homographyStereo3Pts", "(", "DMatrixRMaj", "F", ",", "AssociatedPair", "p1", ",", "AssociatedPair", "p2", ",", "AssociatedPair", "p3", ")", "{", "HomographyInducedStereo3Pts", "alg", "=", "new", "HomographyInducedStereo3Pts", "(", ")", ";", "alg", ".", "setFundamental", "(", "F", ",", "null", ")", ";", "if", "(", "!", "alg", ".", "process", "(", "p1", ",", "p2", ",", "p3", ")", ")", "return", "null", ";", "return", "alg", ".", "getHomography", "(", ")", ";", "}" ]
Computes the homography induced from a planar surface when viewed from two views using correspondences of three points. Observations must be on the planar surface. @see boofcv.alg.geo.h.HomographyInducedStereo3Pts @param F Fundamental matrix @param p1 Associated point observation @param p2 Associated point observation @param p3 Associated point observation @return The homography from view 1 to view 2 or null if it fails
[ "Computes", "the", "homography", "induced", "from", "a", "planar", "surface", "when", "viewed", "from", "two", "views", "using", "correspondences", "of", "three", "points", ".", "Observations", "must", "be", "on", "the", "planar", "surface", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java#L534-L541
Azure/azure-sdk-for-java
compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java
VirtualMachineScaleSetsInner.beginCreateOrUpdate
public VirtualMachineScaleSetInner beginCreateOrUpdate(String resourceGroupName, String vmScaleSetName, VirtualMachineScaleSetInner parameters) { """ Create or update a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set to create or update. @param parameters The scale set object. @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 VirtualMachineScaleSetInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, parameters).toBlocking().single().body(); }
java
public VirtualMachineScaleSetInner beginCreateOrUpdate(String resourceGroupName, String vmScaleSetName, VirtualMachineScaleSetInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, parameters).toBlocking().single().body(); }
[ "public", "VirtualMachineScaleSetInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "vmScaleSetName", ",", "VirtualMachineScaleSetInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmScaleSetName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Create or update a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set to create or update. @param parameters The scale set object. @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 VirtualMachineScaleSetInner object if successful.
[ "Create", "or", "update", "a", "VM", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetsInner.java#L282-L284
wildfly/wildfly-core
host-controller/src/main/java/org/jboss/as/host/controller/SecurityActions.java
SecurityActions.privilegedExecution
static <T, R> R privilegedExecution(Function<T, R> function, T t) { """ Execute the given function, in a privileged block if a security manager is checking. @param function the function @param t the argument to the function @param <T> the type of the argument to the function @param <R> the type of the function return value @return the return value of the function """ return privilegedExecution().execute(function, t); }
java
static <T, R> R privilegedExecution(Function<T, R> function, T t) { return privilegedExecution().execute(function, t); }
[ "static", "<", "T", ",", "R", ">", "R", "privilegedExecution", "(", "Function", "<", "T", ",", "R", ">", "function", ",", "T", "t", ")", "{", "return", "privilegedExecution", "(", ")", ".", "execute", "(", "function", ",", "t", ")", ";", "}" ]
Execute the given function, in a privileged block if a security manager is checking. @param function the function @param t the argument to the function @param <T> the type of the argument to the function @param <R> the type of the function return value @return the return value of the function
[ "Execute", "the", "given", "function", "in", "a", "privileged", "block", "if", "a", "security", "manager", "is", "checking", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/host/controller/SecurityActions.java#L46-L48
knowm/XChart
xchart/src/main/java/org/knowm/xchart/internal/chartpart/ToolTips.java
ToolTips.addData
void addData(double xOffset, double yOffset, String xValue, String yValue) { """ Adds a data (xValue, yValue) with coordinates (xOffset, yOffset). This point will be highlighted with a circle centering (xOffset, yOffset) """ String label = getLabel(xValue, yValue); addData(xOffset, yOffset, label); }
java
void addData(double xOffset, double yOffset, String xValue, String yValue) { String label = getLabel(xValue, yValue); addData(xOffset, yOffset, label); }
[ "void", "addData", "(", "double", "xOffset", ",", "double", "yOffset", ",", "String", "xValue", ",", "String", "yValue", ")", "{", "String", "label", "=", "getLabel", "(", "xValue", ",", "yValue", ")", ";", "addData", "(", "xOffset", ",", "yOffset", ",", "label", ")", ";", "}" ]
Adds a data (xValue, yValue) with coordinates (xOffset, yOffset). This point will be highlighted with a circle centering (xOffset, yOffset)
[ "Adds", "a", "data", "(", "xValue", "yValue", ")", "with", "coordinates", "(", "xOffset", "yOffset", ")", ".", "This", "point", "will", "be", "highlighted", "with", "a", "circle", "centering", "(", "xOffset", "yOffset", ")" ]
train
https://github.com/knowm/XChart/blob/677a105753a855edf24782fab1bf1f5aec3e642b/xchart/src/main/java/org/knowm/xchart/internal/chartpart/ToolTips.java#L121-L126
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldAdjustRegion.java
TldAdjustRegion.process
public boolean process( FastQueue<AssociatedPair> pairs , Rectangle2D_F64 targetRectangle ) { """ Adjusts target rectangle using track information @param pairs List of feature location in previous and current frame. @param targetRectangle (Input) current location of rectangle. (output) adjusted location @return true if successful """ // estimate how the rectangle has changed and update it if( !estimateMotion.process(pairs.toList()) ) return false; ScaleTranslate2D motion = estimateMotion.getModelParameters(); adjustRectangle(targetRectangle,motion); if( targetRectangle.p0.x < 0 || targetRectangle.p0.y < 0 ) return false; if( targetRectangle.p1.x >= imageWidth || targetRectangle.p1.y >= imageHeight ) return false; return true; }
java
public boolean process( FastQueue<AssociatedPair> pairs , Rectangle2D_F64 targetRectangle ) { // estimate how the rectangle has changed and update it if( !estimateMotion.process(pairs.toList()) ) return false; ScaleTranslate2D motion = estimateMotion.getModelParameters(); adjustRectangle(targetRectangle,motion); if( targetRectangle.p0.x < 0 || targetRectangle.p0.y < 0 ) return false; if( targetRectangle.p1.x >= imageWidth || targetRectangle.p1.y >= imageHeight ) return false; return true; }
[ "public", "boolean", "process", "(", "FastQueue", "<", "AssociatedPair", ">", "pairs", ",", "Rectangle2D_F64", "targetRectangle", ")", "{", "// estimate how the rectangle has changed and update it", "if", "(", "!", "estimateMotion", ".", "process", "(", "pairs", ".", "toList", "(", ")", ")", ")", "return", "false", ";", "ScaleTranslate2D", "motion", "=", "estimateMotion", ".", "getModelParameters", "(", ")", ";", "adjustRectangle", "(", "targetRectangle", ",", "motion", ")", ";", "if", "(", "targetRectangle", ".", "p0", ".", "x", "<", "0", "||", "targetRectangle", ".", "p0", ".", "y", "<", "0", ")", "return", "false", ";", "if", "(", "targetRectangle", ".", "p1", ".", "x", ">=", "imageWidth", "||", "targetRectangle", ".", "p1", ".", "y", ">=", "imageHeight", ")", "return", "false", ";", "return", "true", ";", "}" ]
Adjusts target rectangle using track information @param pairs List of feature location in previous and current frame. @param targetRectangle (Input) current location of rectangle. (output) adjusted location @return true if successful
[ "Adjusts", "target", "rectangle", "using", "track", "information" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldAdjustRegion.java#L72-L88
knightliao/disconf
disconf-client/src/main/java/com/baidu/disconf/client/support/utils/StringUtil.java
StringUtil.longToString
public static String longToString(long longValue, boolean noCase) { """ 将一个长整形转换成62进制的字符串。 @param longValue 64位数字 @param noCase 区分大小写 @return 62进制的字符串 """ char[] digits = noCase ? DIGITS_NOCASE : DIGITS; int digitsLength = digits.length; if (longValue == 0) { return String.valueOf(digits[0]); } if (longValue < 0) { longValue = -longValue; } StringBuilder strValue = new StringBuilder(); while (longValue != 0) { int digit = (int) (longValue % digitsLength); longValue = longValue / digitsLength; strValue.append(digits[digit]); } return strValue.toString(); }
java
public static String longToString(long longValue, boolean noCase) { char[] digits = noCase ? DIGITS_NOCASE : DIGITS; int digitsLength = digits.length; if (longValue == 0) { return String.valueOf(digits[0]); } if (longValue < 0) { longValue = -longValue; } StringBuilder strValue = new StringBuilder(); while (longValue != 0) { int digit = (int) (longValue % digitsLength); longValue = longValue / digitsLength; strValue.append(digits[digit]); } return strValue.toString(); }
[ "public", "static", "String", "longToString", "(", "long", "longValue", ",", "boolean", "noCase", ")", "{", "char", "[", "]", "digits", "=", "noCase", "?", "DIGITS_NOCASE", ":", "DIGITS", ";", "int", "digitsLength", "=", "digits", ".", "length", ";", "if", "(", "longValue", "==", "0", ")", "{", "return", "String", ".", "valueOf", "(", "digits", "[", "0", "]", ")", ";", "}", "if", "(", "longValue", "<", "0", ")", "{", "longValue", "=", "-", "longValue", ";", "}", "StringBuilder", "strValue", "=", "new", "StringBuilder", "(", ")", ";", "while", "(", "longValue", "!=", "0", ")", "{", "int", "digit", "=", "(", "int", ")", "(", "longValue", "%", "digitsLength", ")", ";", "longValue", "=", "longValue", "/", "digitsLength", ";", "strValue", ".", "append", "(", "digits", "[", "digit", "]", ")", ";", "}", "return", "strValue", ".", "toString", "(", ")", ";", "}" ]
将一个长整形转换成62进制的字符串。 @param longValue 64位数字 @param noCase 区分大小写 @return 62进制的字符串
[ "将一个长整形转换成62进制的字符串。" ]
train
https://github.com/knightliao/disconf/blob/d413cbce9334fe38a5a24982ce4db3a6ed8e98ea/disconf-client/src/main/java/com/baidu/disconf/client/support/utils/StringUtil.java#L444-L466
JodaOrg/joda-time
src/main/java/org/joda/time/convert/ReadablePartialConverter.java
ReadablePartialConverter.getChronology
public Chronology getChronology(Object object, Chronology chrono) { """ Gets the chronology, which is taken from the ReadableInstant. <p> If the passed in chronology is non-null, it is used. Otherwise the chronology from the instant is used. @param object the ReadablePartial to convert, must not be null @param chrono the chronology to use, null means use that from object @return the chronology, never null """ if (chrono == null) { chrono = ((ReadablePartial) object).getChronology(); chrono = DateTimeUtils.getChronology(chrono); } return chrono; }
java
public Chronology getChronology(Object object, Chronology chrono) { if (chrono == null) { chrono = ((ReadablePartial) object).getChronology(); chrono = DateTimeUtils.getChronology(chrono); } return chrono; }
[ "public", "Chronology", "getChronology", "(", "Object", "object", ",", "Chronology", "chrono", ")", "{", "if", "(", "chrono", "==", "null", ")", "{", "chrono", "=", "(", "(", "ReadablePartial", ")", "object", ")", ".", "getChronology", "(", ")", ";", "chrono", "=", "DateTimeUtils", ".", "getChronology", "(", "chrono", ")", ";", "}", "return", "chrono", ";", "}" ]
Gets the chronology, which is taken from the ReadableInstant. <p> If the passed in chronology is non-null, it is used. Otherwise the chronology from the instant is used. @param object the ReadablePartial to convert, must not be null @param chrono the chronology to use, null means use that from object @return the chronology, never null
[ "Gets", "the", "chronology", "which", "is", "taken", "from", "the", "ReadableInstant", ".", "<p", ">", "If", "the", "passed", "in", "chronology", "is", "non", "-", "null", "it", "is", "used", ".", "Otherwise", "the", "chronology", "from", "the", "instant", "is", "used", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/convert/ReadablePartialConverter.java#L66-L72
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/SweepHullDelaunay2D.java
SweepHullDelaunay2D.getHull
public Polygon getHull() { """ Get the convex hull only. <p> Note: if you also want the Delaunay Triangulation, you should get that first! @return Convex hull """ if(hull == null) { run(true); } DoubleMinMax minmaxX = new DoubleMinMax(); DoubleMinMax minmaxY = new DoubleMinMax(); List<double[]> hullp = new ArrayList<>(hull.size()); for(IntIntPair pair : hull) { double[] v = points.get(pair.first); hullp.add(v); minmaxX.put(v[0]); minmaxY.put(v[1]); } return new Polygon(hullp, minmaxX.getMin(), minmaxX.getMax(), minmaxY.getMin(), minmaxY.getMax()); }
java
public Polygon getHull() { if(hull == null) { run(true); } DoubleMinMax minmaxX = new DoubleMinMax(); DoubleMinMax minmaxY = new DoubleMinMax(); List<double[]> hullp = new ArrayList<>(hull.size()); for(IntIntPair pair : hull) { double[] v = points.get(pair.first); hullp.add(v); minmaxX.put(v[0]); minmaxY.put(v[1]); } return new Polygon(hullp, minmaxX.getMin(), minmaxX.getMax(), minmaxY.getMin(), minmaxY.getMax()); }
[ "public", "Polygon", "getHull", "(", ")", "{", "if", "(", "hull", "==", "null", ")", "{", "run", "(", "true", ")", ";", "}", "DoubleMinMax", "minmaxX", "=", "new", "DoubleMinMax", "(", ")", ";", "DoubleMinMax", "minmaxY", "=", "new", "DoubleMinMax", "(", ")", ";", "List", "<", "double", "[", "]", ">", "hullp", "=", "new", "ArrayList", "<>", "(", "hull", ".", "size", "(", ")", ")", ";", "for", "(", "IntIntPair", "pair", ":", "hull", ")", "{", "double", "[", "]", "v", "=", "points", ".", "get", "(", "pair", ".", "first", ")", ";", "hullp", ".", "add", "(", "v", ")", ";", "minmaxX", ".", "put", "(", "v", "[", "0", "]", ")", ";", "minmaxY", ".", "put", "(", "v", "[", "1", "]", ")", ";", "}", "return", "new", "Polygon", "(", "hullp", ",", "minmaxX", ".", "getMin", "(", ")", ",", "minmaxX", ".", "getMax", "(", ")", ",", "minmaxY", ".", "getMin", "(", ")", ",", "minmaxY", ".", "getMax", "(", ")", ")", ";", "}" ]
Get the convex hull only. <p> Note: if you also want the Delaunay Triangulation, you should get that first! @return Convex hull
[ "Get", "the", "convex", "hull", "only", ".", "<p", ">", "Note", ":", "if", "you", "also", "want", "the", "Delaunay", "Triangulation", "you", "should", "get", "that", "first!" ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/SweepHullDelaunay2D.java#L658-L672
jenkinsci/jenkins
core/src/main/java/hudson/model/Descriptor.java
Descriptor.findById
public static @CheckForNull <T extends Descriptor> T findById(Collection<? extends T> list, String id) { """ Finds a descriptor from a collection by its ID. @param id should match {@link #getId} @since 1.610 """ for (T d : list) { if(d.getId().equals(id)) return d; } return null; }
java
public static @CheckForNull <T extends Descriptor> T findById(Collection<? extends T> list, String id) { for (T d : list) { if(d.getId().equals(id)) return d; } return null; }
[ "public", "static", "@", "CheckForNull", "<", "T", "extends", "Descriptor", ">", "T", "findById", "(", "Collection", "<", "?", "extends", "T", ">", "list", ",", "String", "id", ")", "{", "for", "(", "T", "d", ":", "list", ")", "{", "if", "(", "d", ".", "getId", "(", ")", ".", "equals", "(", "id", ")", ")", "return", "d", ";", "}", "return", "null", ";", "}" ]
Finds a descriptor from a collection by its ID. @param id should match {@link #getId} @since 1.610
[ "Finds", "a", "descriptor", "from", "a", "collection", "by", "its", "ID", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/Descriptor.java#L1074-L1080
javafxports/javafxmobile-plugin
src/main/java/org/javafxports/jfxmobile/plugin/android/task/ApkBuilder.java
ApkBuilder.addResourcesFromJar
public JarStatus addResourcesFromJar(File jarFile) throws ApkCreationException, SealedApkException, DuplicateFileException { """ Adds the resources from a jar file. @param jarFile the jar File. @return a {@link JarStatus} object indicating if native libraries where found in the jar file. @throws ApkCreationException if an error occurred @throws SealedApkException if the APK is already sealed. @throws DuplicateFileException if a file conflicts with another already added to the APK at the same location inside the APK archive. """ if (mIsSealed) { throw new SealedApkException("APK is already sealed"); } try { verbosePrintln("%s:", jarFile); // reset the filter with this input. mFilter.reset(jarFile); // ask the builder to add the content of the file, filtered to only let through // the java resources. FileInputStream fis = new FileInputStream(jarFile); mBuilder.writeZip(fis, mFilter); fis.close(); // check if native libraries were found in the external library. This should // constitutes an error or warning depending on if they are in lib/ return new JarStatusImpl(mFilter.getNativeLibs(), mFilter.getNativeLibsConflict()); } catch (DuplicateFileException e) { mBuilder.cleanUp(); throw e; } catch (Exception e) { mBuilder.cleanUp(); throw new ApkCreationException(e, "Failed to add %s", jarFile); } }
java
public JarStatus addResourcesFromJar(File jarFile) throws ApkCreationException, SealedApkException, DuplicateFileException { if (mIsSealed) { throw new SealedApkException("APK is already sealed"); } try { verbosePrintln("%s:", jarFile); // reset the filter with this input. mFilter.reset(jarFile); // ask the builder to add the content of the file, filtered to only let through // the java resources. FileInputStream fis = new FileInputStream(jarFile); mBuilder.writeZip(fis, mFilter); fis.close(); // check if native libraries were found in the external library. This should // constitutes an error or warning depending on if they are in lib/ return new JarStatusImpl(mFilter.getNativeLibs(), mFilter.getNativeLibsConflict()); } catch (DuplicateFileException e) { mBuilder.cleanUp(); throw e; } catch (Exception e) { mBuilder.cleanUp(); throw new ApkCreationException(e, "Failed to add %s", jarFile); } }
[ "public", "JarStatus", "addResourcesFromJar", "(", "File", "jarFile", ")", "throws", "ApkCreationException", ",", "SealedApkException", ",", "DuplicateFileException", "{", "if", "(", "mIsSealed", ")", "{", "throw", "new", "SealedApkException", "(", "\"APK is already sealed\"", ")", ";", "}", "try", "{", "verbosePrintln", "(", "\"%s:\"", ",", "jarFile", ")", ";", "// reset the filter with this input.", "mFilter", ".", "reset", "(", "jarFile", ")", ";", "// ask the builder to add the content of the file, filtered to only let through", "// the java resources.", "FileInputStream", "fis", "=", "new", "FileInputStream", "(", "jarFile", ")", ";", "mBuilder", ".", "writeZip", "(", "fis", ",", "mFilter", ")", ";", "fis", ".", "close", "(", ")", ";", "// check if native libraries were found in the external library. This should", "// constitutes an error or warning depending on if they are in lib/", "return", "new", "JarStatusImpl", "(", "mFilter", ".", "getNativeLibs", "(", ")", ",", "mFilter", ".", "getNativeLibsConflict", "(", ")", ")", ";", "}", "catch", "(", "DuplicateFileException", "e", ")", "{", "mBuilder", ".", "cleanUp", "(", ")", ";", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "mBuilder", ".", "cleanUp", "(", ")", ";", "throw", "new", "ApkCreationException", "(", "e", ",", "\"Failed to add %s\"", ",", "jarFile", ")", ";", "}", "}" ]
Adds the resources from a jar file. @param jarFile the jar File. @return a {@link JarStatus} object indicating if native libraries where found in the jar file. @throws ApkCreationException if an error occurred @throws SealedApkException if the APK is already sealed. @throws DuplicateFileException if a file conflicts with another already added to the APK at the same location inside the APK archive.
[ "Adds", "the", "resources", "from", "a", "jar", "file", "." ]
train
https://github.com/javafxports/javafxmobile-plugin/blob/a9bef513b7e1bfa85f9a668226e6943c6d9f847f/src/main/java/org/javafxports/jfxmobile/plugin/android/task/ApkBuilder.java#L614-L642
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java
ServerParams.addConfigParam
private void addConfigParam(String name, Object value) throws ConfigurationException { """ (e.g., DBService) or a legacy YAML file option (e.g., dbhost). """ if (isModuleName(name)) { Utils.require(value instanceof Map, "Value for module '%s' should be a map: %s", name, value.toString()); updateMap(m_params, name, value); } else { setLegacyParam(name, value); } }
java
private void addConfigParam(String name, Object value) throws ConfigurationException { if (isModuleName(name)) { Utils.require(value instanceof Map, "Value for module '%s' should be a map: %s", name, value.toString()); updateMap(m_params, name, value); } else { setLegacyParam(name, value); } }
[ "private", "void", "addConfigParam", "(", "String", "name", ",", "Object", "value", ")", "throws", "ConfigurationException", "{", "if", "(", "isModuleName", "(", "name", ")", ")", "{", "Utils", ".", "require", "(", "value", "instanceof", "Map", ",", "\"Value for module '%s' should be a map: %s\"", ",", "name", ",", "value", ".", "toString", "(", ")", ")", ";", "updateMap", "(", "m_params", ",", "name", ",", "value", ")", ";", "}", "else", "{", "setLegacyParam", "(", "name", ",", "value", ")", ";", "}", "}" ]
(e.g., DBService) or a legacy YAML file option (e.g., dbhost).
[ "(", "e", ".", "g", ".", "DBService", ")", "or", "a", "legacy", "YAML", "file", "option", "(", "e", ".", "g", ".", "dbhost", ")", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/core/ServerParams.java#L490-L498
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/preferences/CmsUserSettingsDialog.java
CmsUserSettingsDialog.loadAndShow
public static void loadAndShow(final Runnable finishAction) { """ Loads the user settings dialog.<p> @param finishAction the action to execute after the user has changed his preferences """ CmsRpcAction<CmsUserSettingsBean> action = new CmsRpcAction<CmsUserSettingsBean>() { @Override public void execute() { start(200, false); CmsCoreProvider.getService().loadUserSettings(this); } @Override protected void onResponse(CmsUserSettingsBean result) { stop(false); CmsUserSettingsDialog dlg = new CmsUserSettingsDialog(result, finishAction); dlg.centerHorizontally(50); dlg.initWidth(); } }; action.execute(); }
java
public static void loadAndShow(final Runnable finishAction) { CmsRpcAction<CmsUserSettingsBean> action = new CmsRpcAction<CmsUserSettingsBean>() { @Override public void execute() { start(200, false); CmsCoreProvider.getService().loadUserSettings(this); } @Override protected void onResponse(CmsUserSettingsBean result) { stop(false); CmsUserSettingsDialog dlg = new CmsUserSettingsDialog(result, finishAction); dlg.centerHorizontally(50); dlg.initWidth(); } }; action.execute(); }
[ "public", "static", "void", "loadAndShow", "(", "final", "Runnable", "finishAction", ")", "{", "CmsRpcAction", "<", "CmsUserSettingsBean", ">", "action", "=", "new", "CmsRpcAction", "<", "CmsUserSettingsBean", ">", "(", ")", "{", "@", "Override", "public", "void", "execute", "(", ")", "{", "start", "(", "200", ",", "false", ")", ";", "CmsCoreProvider", ".", "getService", "(", ")", ".", "loadUserSettings", "(", "this", ")", ";", "}", "@", "Override", "protected", "void", "onResponse", "(", "CmsUserSettingsBean", "result", ")", "{", "stop", "(", "false", ")", ";", "CmsUserSettingsDialog", "dlg", "=", "new", "CmsUserSettingsDialog", "(", "result", ",", "finishAction", ")", ";", "dlg", ".", "centerHorizontally", "(", "50", ")", ";", "dlg", ".", "initWidth", "(", ")", ";", "}", "}", ";", "action", ".", "execute", "(", ")", ";", "}" ]
Loads the user settings dialog.<p> @param finishAction the action to execute after the user has changed his preferences
[ "Loads", "the", "user", "settings", "dialog", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/preferences/CmsUserSettingsDialog.java#L135-L159
aoindustries/aoweb-framework
src/main/java/com/aoindustries/website/framework/WebPage.java
WebPage.getClassLastModified
protected final long getClassLastModified() throws IOException, SQLException { """ Gets the last modified time of the java class file. If the class file is unavailable, it defaults to the time the servlets were loaded. @see WebSiteFrameworkConfiguration#getServletDirectory @see ErrorReportingServlet#getUptime() """ String dir=getServletContext().getRealPath("/WEB-INF/classes"); if(dir!=null && dir.length()>0) { // Try to get from the class file long lastMod=new File(dir, getClass().getName().replace('.', File.separatorChar) + ".class").lastModified(); if(lastMod!=0 && lastMod!=-1) return lastMod; } return getUptime(); }
java
protected final long getClassLastModified() throws IOException, SQLException { String dir=getServletContext().getRealPath("/WEB-INF/classes"); if(dir!=null && dir.length()>0) { // Try to get from the class file long lastMod=new File(dir, getClass().getName().replace('.', File.separatorChar) + ".class").lastModified(); if(lastMod!=0 && lastMod!=-1) return lastMod; } return getUptime(); }
[ "protected", "final", "long", "getClassLastModified", "(", ")", "throws", "IOException", ",", "SQLException", "{", "String", "dir", "=", "getServletContext", "(", ")", ".", "getRealPath", "(", "\"/WEB-INF/classes\"", ")", ";", "if", "(", "dir", "!=", "null", "&&", "dir", ".", "length", "(", ")", ">", "0", ")", "{", "// Try to get from the class file", "long", "lastMod", "=", "new", "File", "(", "dir", ",", "getClass", "(", ")", ".", "getName", "(", ")", ".", "replace", "(", "'", "'", ",", "File", ".", "separatorChar", ")", "+", "\".class\"", ")", ".", "lastModified", "(", ")", ";", "if", "(", "lastMod", "!=", "0", "&&", "lastMod", "!=", "-", "1", ")", "return", "lastMod", ";", "}", "return", "getUptime", "(", ")", ";", "}" ]
Gets the last modified time of the java class file. If the class file is unavailable, it defaults to the time the servlets were loaded. @see WebSiteFrameworkConfiguration#getServletDirectory @see ErrorReportingServlet#getUptime()
[ "Gets", "the", "last", "modified", "time", "of", "the", "java", "class", "file", ".", "If", "the", "class", "file", "is", "unavailable", "it", "defaults", "to", "the", "time", "the", "servlets", "were", "loaded", "." ]
train
https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L228-L236
twitter/hraven
hraven-core/src/main/java/com/twitter/hraven/datasource/FlowQueueService.java
FlowQueueService.getFlowsForStatus
public List<Flow> getFlowsForStatus(String cluster, Flow.Status status, int limit) throws IOException { """ Returns the flows currently listed in the given {@link Flow.Status} @param cluster The cluster where flows have run @param status The flows' status @param limit Return up to this many Flow instances @return a list of up to {@code limit} Flows @throws IOException in the case of an error retrieving the data """ return getFlowsForStatus(cluster, status, limit, null, null); }
java
public List<Flow> getFlowsForStatus(String cluster, Flow.Status status, int limit) throws IOException { return getFlowsForStatus(cluster, status, limit, null, null); }
[ "public", "List", "<", "Flow", ">", "getFlowsForStatus", "(", "String", "cluster", ",", "Flow", ".", "Status", "status", ",", "int", "limit", ")", "throws", "IOException", "{", "return", "getFlowsForStatus", "(", "cluster", ",", "status", ",", "limit", ",", "null", ",", "null", ")", ";", "}" ]
Returns the flows currently listed in the given {@link Flow.Status} @param cluster The cluster where flows have run @param status The flows' status @param limit Return up to this many Flow instances @return a list of up to {@code limit} Flows @throws IOException in the case of an error retrieving the data
[ "Returns", "the", "flows", "currently", "listed", "in", "the", "given", "{" ]
train
https://github.com/twitter/hraven/blob/e35996b6e2f016bcd18db0bad320be7c93d95208/hraven-core/src/main/java/com/twitter/hraven/datasource/FlowQueueService.java#L189-L192
square/protoparser
src/main/java/com/squareup/protoparser/OptionElement.java
OptionElement.findByName
public static OptionElement findByName(List<OptionElement> options, String name) { """ Return the option with the specified name from the supplied list or null. """ checkNotNull(options, "options"); checkNotNull(name, "name"); OptionElement found = null; for (OptionElement option : options) { if (option.name().equals(name)) { if (found != null) { throw new IllegalStateException("Multiple options match name: " + name); } found = option; } } return found; }
java
public static OptionElement findByName(List<OptionElement> options, String name) { checkNotNull(options, "options"); checkNotNull(name, "name"); OptionElement found = null; for (OptionElement option : options) { if (option.name().equals(name)) { if (found != null) { throw new IllegalStateException("Multiple options match name: " + name); } found = option; } } return found; }
[ "public", "static", "OptionElement", "findByName", "(", "List", "<", "OptionElement", ">", "options", ",", "String", "name", ")", "{", "checkNotNull", "(", "options", ",", "\"options\"", ")", ";", "checkNotNull", "(", "name", ",", "\"name\"", ")", ";", "OptionElement", "found", "=", "null", ";", "for", "(", "OptionElement", "option", ":", "options", ")", "{", "if", "(", "option", ".", "name", "(", ")", ".", "equals", "(", "name", ")", ")", "{", "if", "(", "found", "!=", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Multiple options match name: \"", "+", "name", ")", ";", "}", "found", "=", "option", ";", "}", "}", "return", "found", ";", "}" ]
Return the option with the specified name from the supplied list or null.
[ "Return", "the", "option", "with", "the", "specified", "name", "from", "the", "supplied", "list", "or", "null", "." ]
train
https://github.com/square/protoparser/blob/8be66bb8fe6658b04741df0358daabca501f2524/src/main/java/com/squareup/protoparser/OptionElement.java#L64-L78
datacleaner/DataCleaner
engine/core/src/main/java/org/datacleaner/result/save/AnalysisResultSaveHandler.java
AnalysisResultSaveHandler.createSafeAnalysisResult
public AnalysisResult createSafeAnalysisResult() { """ Creates a safe {@link AnalysisResult} for saving @return a new {@link AnalysisResult} or null if it is not possible to create a result that is safer than the previous. """ final Set<ComponentJob> unsafeKeys = getUnsafeResultElements().keySet(); if (unsafeKeys.isEmpty()) { return _analysisResult; } final Map<ComponentJob, AnalyzerResult> resultMap = new LinkedHashMap<>(_analysisResult.getResultMap()); for (final ComponentJob unsafeKey : unsafeKeys) { resultMap.remove(unsafeKey); } if (resultMap.isEmpty()) { return null; } return new SimpleAnalysisResult(resultMap, _analysisResult.getCreationDate()); }
java
public AnalysisResult createSafeAnalysisResult() { final Set<ComponentJob> unsafeKeys = getUnsafeResultElements().keySet(); if (unsafeKeys.isEmpty()) { return _analysisResult; } final Map<ComponentJob, AnalyzerResult> resultMap = new LinkedHashMap<>(_analysisResult.getResultMap()); for (final ComponentJob unsafeKey : unsafeKeys) { resultMap.remove(unsafeKey); } if (resultMap.isEmpty()) { return null; } return new SimpleAnalysisResult(resultMap, _analysisResult.getCreationDate()); }
[ "public", "AnalysisResult", "createSafeAnalysisResult", "(", ")", "{", "final", "Set", "<", "ComponentJob", ">", "unsafeKeys", "=", "getUnsafeResultElements", "(", ")", ".", "keySet", "(", ")", ";", "if", "(", "unsafeKeys", ".", "isEmpty", "(", ")", ")", "{", "return", "_analysisResult", ";", "}", "final", "Map", "<", "ComponentJob", ",", "AnalyzerResult", ">", "resultMap", "=", "new", "LinkedHashMap", "<>", "(", "_analysisResult", ".", "getResultMap", "(", ")", ")", ";", "for", "(", "final", "ComponentJob", "unsafeKey", ":", "unsafeKeys", ")", "{", "resultMap", ".", "remove", "(", "unsafeKey", ")", ";", "}", "if", "(", "resultMap", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "return", "new", "SimpleAnalysisResult", "(", "resultMap", ",", "_analysisResult", ".", "getCreationDate", "(", ")", ")", ";", "}" ]
Creates a safe {@link AnalysisResult} for saving @return a new {@link AnalysisResult} or null if it is not possible to create a result that is safer than the previous.
[ "Creates", "a", "safe", "{", "@link", "AnalysisResult", "}", "for", "saving" ]
train
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/result/save/AnalysisResultSaveHandler.java#L119-L135
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/util/MultiMap.java
MultiMap.addValues
public void addValues(Object name, List values) { """ Add values to multi valued entry. If the entry is single valued, it is converted to the first value of a multi valued entry. @param name The entry key. @param values The List of multiple values. """ Object lo = super.get(name); Object ln = LazyList.addCollection(lo,values); if (lo!=ln) super.put(name,ln); }
java
public void addValues(Object name, List values) { Object lo = super.get(name); Object ln = LazyList.addCollection(lo,values); if (lo!=ln) super.put(name,ln); }
[ "public", "void", "addValues", "(", "Object", "name", ",", "List", "values", ")", "{", "Object", "lo", "=", "super", ".", "get", "(", "name", ")", ";", "Object", "ln", "=", "LazyList", ".", "addCollection", "(", "lo", ",", "values", ")", ";", "if", "(", "lo", "!=", "ln", ")", "super", ".", "put", "(", "name", ",", "ln", ")", ";", "}" ]
Add values to multi valued entry. If the entry is single valued, it is converted to the first value of a multi valued entry. @param name The entry key. @param values The List of multiple values.
[ "Add", "values", "to", "multi", "valued", "entry", ".", "If", "the", "entry", "is", "single", "valued", "it", "is", "converted", "to", "the", "first", "value", "of", "a", "multi", "valued", "entry", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/util/MultiMap.java#L198-L204
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/UtilColor.java
UtilColor.isOpaqueTransparentExclusive
public static boolean isOpaqueTransparentExclusive(ColorRgba colorA, ColorRgba colorB) { """ Check if colors transparency type are exclusive (one is {@link ColorRgba#OPAQUE} and the other {@link ColorRgba#TRANSPARENT}). @param colorA The first color (must not be <code>null</code>). @param colorB The second color (must not be <code>null</code>). @return <code>true</code> if exclusive, <code>false</code> else. @throws LionEngineException If invalid arguments. """ Check.notNull(colorA); Check.notNull(colorB); return isOpaqueTransparentExclusive(colorA.getRgba(), colorB.getRgba()); }
java
public static boolean isOpaqueTransparentExclusive(ColorRgba colorA, ColorRgba colorB) { Check.notNull(colorA); Check.notNull(colorB); return isOpaqueTransparentExclusive(colorA.getRgba(), colorB.getRgba()); }
[ "public", "static", "boolean", "isOpaqueTransparentExclusive", "(", "ColorRgba", "colorA", ",", "ColorRgba", "colorB", ")", "{", "Check", ".", "notNull", "(", "colorA", ")", ";", "Check", ".", "notNull", "(", "colorB", ")", ";", "return", "isOpaqueTransparentExclusive", "(", "colorA", ".", "getRgba", "(", ")", ",", "colorB", ".", "getRgba", "(", ")", ")", ";", "}" ]
Check if colors transparency type are exclusive (one is {@link ColorRgba#OPAQUE} and the other {@link ColorRgba#TRANSPARENT}). @param colorA The first color (must not be <code>null</code>). @param colorB The second color (must not be <code>null</code>). @return <code>true</code> if exclusive, <code>false</code> else. @throws LionEngineException If invalid arguments.
[ "Check", "if", "colors", "transparency", "type", "are", "exclusive", "(", "one", "is", "{", "@link", "ColorRgba#OPAQUE", "}", "and", "the", "other", "{", "@link", "ColorRgba#TRANSPARENT", "}", ")", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/UtilColor.java#L159-L165
Ordinastie/MalisisCore
src/main/java/net/malisis/core/renderer/model/loader/ObjFileImporter.java
ObjFileImporter.addNormal
private void addNormal(String data) { """ Creates a new normal {@link Vector} from data and adds it to {@link #normals}. @param data the data """ String coords[] = data.split("\\s+"); float x = 0; float y = 0; float z = 0; if (coords.length != 3) { MalisisCore.log.error( "[ObjFileImporter] Wrong Normal coordinates number {} at line {} : {}", coords.length, lineNumber, currentLine); } else { x = Float.parseFloat(coords[0]); y = Float.parseFloat(coords[1]); z = Float.parseFloat(coords[2]); } normals.add(new Vector(x, y, z)); }
java
private void addNormal(String data) { String coords[] = data.split("\\s+"); float x = 0; float y = 0; float z = 0; if (coords.length != 3) { MalisisCore.log.error( "[ObjFileImporter] Wrong Normal coordinates number {} at line {} : {}", coords.length, lineNumber, currentLine); } else { x = Float.parseFloat(coords[0]); y = Float.parseFloat(coords[1]); z = Float.parseFloat(coords[2]); } normals.add(new Vector(x, y, z)); }
[ "private", "void", "addNormal", "(", "String", "data", ")", "{", "String", "coords", "[", "]", "=", "data", ".", "split", "(", "\"\\\\s+\"", ")", ";", "float", "x", "=", "0", ";", "float", "y", "=", "0", ";", "float", "z", "=", "0", ";", "if", "(", "coords", ".", "length", "!=", "3", ")", "{", "MalisisCore", ".", "log", ".", "error", "(", "\"[ObjFileImporter] Wrong Normal coordinates number {} at line {} : {}\"", ",", "coords", ".", "length", ",", "lineNumber", ",", "currentLine", ")", ";", "}", "else", "{", "x", "=", "Float", ".", "parseFloat", "(", "coords", "[", "0", "]", ")", ";", "y", "=", "Float", ".", "parseFloat", "(", "coords", "[", "1", "]", ")", ";", "z", "=", "Float", ".", "parseFloat", "(", "coords", "[", "2", "]", ")", ";", "}", "normals", ".", "add", "(", "new", "Vector", "(", "x", ",", "y", ",", "z", ")", ")", ";", "}" ]
Creates a new normal {@link Vector} from data and adds it to {@link #normals}. @param data the data
[ "Creates", "a", "new", "normal", "{", "@link", "Vector", "}", "from", "data", "and", "adds", "it", "to", "{", "@link", "#normals", "}", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/renderer/model/loader/ObjFileImporter.java#L257-L278
jmurty/java-xmlbuilder
src/main/java/com/jamesmurty/utils/BaseXMLBuilder.java
BaseXMLBuilder.instructionImpl
protected void instructionImpl(String target, String data) { """ Add an instruction to the element represented by this builder node. @param target the target value for the instruction. @param data the data value for the instruction """ xmlNode.appendChild(getDocument().createProcessingInstruction(target, data)); }
java
protected void instructionImpl(String target, String data) { xmlNode.appendChild(getDocument().createProcessingInstruction(target, data)); }
[ "protected", "void", "instructionImpl", "(", "String", "target", ",", "String", "data", ")", "{", "xmlNode", ".", "appendChild", "(", "getDocument", "(", ")", ".", "createProcessingInstruction", "(", "target", ",", "data", ")", ")", ";", "}" ]
Add an instruction to the element represented by this builder node. @param target the target value for the instruction. @param data the data value for the instruction
[ "Add", "an", "instruction", "to", "the", "element", "represented", "by", "this", "builder", "node", "." ]
train
https://github.com/jmurty/java-xmlbuilder/blob/7c224b8e8ed79808509322cb141dab5a88dd3cec/src/main/java/com/jamesmurty/utils/BaseXMLBuilder.java#L881-L883
algolia/algoliasearch-client-java
src/main/java/com/algolia/search/saas/Index.java
Index.batchSynonyms
public JSONObject batchSynonyms(List<JSONObject> objects, boolean forwardToReplicas, boolean replaceExistingSynonyms) throws AlgoliaException { """ Add or Replace a list of synonyms @param objects List of synonyms @param forwardToReplicas Forward the operation to the replica indices @param replaceExistingSynonyms Replace the existing synonyms with this batch """ return this.batchSynonyms(objects, forwardToReplicas, replaceExistingSynonyms, RequestOptions.empty); }
java
public JSONObject batchSynonyms(List<JSONObject> objects, boolean forwardToReplicas, boolean replaceExistingSynonyms) throws AlgoliaException { return this.batchSynonyms(objects, forwardToReplicas, replaceExistingSynonyms, RequestOptions.empty); }
[ "public", "JSONObject", "batchSynonyms", "(", "List", "<", "JSONObject", ">", "objects", ",", "boolean", "forwardToReplicas", ",", "boolean", "replaceExistingSynonyms", ")", "throws", "AlgoliaException", "{", "return", "this", ".", "batchSynonyms", "(", "objects", ",", "forwardToReplicas", ",", "replaceExistingSynonyms", ",", "RequestOptions", ".", "empty", ")", ";", "}" ]
Add or Replace a list of synonyms @param objects List of synonyms @param forwardToReplicas Forward the operation to the replica indices @param replaceExistingSynonyms Replace the existing synonyms with this batch
[ "Add", "or", "Replace", "a", "list", "of", "synonyms" ]
train
https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L1571-L1573
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.findResult
public static <S, T, U extends T, V extends T> T findResult(S[] self, U defaultResult, @ClosureParams(FirstParam.Component.class) Closure<V> condition) { """ Iterates through the Array calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. If all are null, the defaultResult is returned. @param self an Array @param defaultResult an Object that should be returned if all closure results are null @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned @return the first non-null result from calling the closure, or the defaultValue @since 2.5.0 """ return findResult(new ArrayIterator<S>(self), defaultResult, condition); }
java
public static <S, T, U extends T, V extends T> T findResult(S[] self, U defaultResult, @ClosureParams(FirstParam.Component.class) Closure<V> condition) { return findResult(new ArrayIterator<S>(self), defaultResult, condition); }
[ "public", "static", "<", "S", ",", "T", ",", "U", "extends", "T", ",", "V", "extends", "T", ">", "T", "findResult", "(", "S", "[", "]", "self", ",", "U", "defaultResult", ",", "@", "ClosureParams", "(", "FirstParam", ".", "Component", ".", "class", ")", "Closure", "<", "V", ">", "condition", ")", "{", "return", "findResult", "(", "new", "ArrayIterator", "<", "S", ">", "(", "self", ")", ",", "defaultResult", ",", "condition", ")", ";", "}" ]
Iterates through the Array calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. If all are null, the defaultResult is returned. @param self an Array @param defaultResult an Object that should be returned if all closure results are null @param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned @return the first non-null result from calling the closure, or the defaultValue @since 2.5.0
[ "Iterates", "through", "the", "Array", "calling", "the", "given", "closure", "condition", "for", "each", "item", "but", "stopping", "once", "the", "first", "non", "-", "null", "result", "is", "found", "and", "returning", "that", "result", ".", "If", "all", "are", "null", "the", "defaultResult", "is", "returned", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L4561-L4563
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/ProxySelectorImpl.java
ProxySelectorImpl.lookupProxy
private Proxy lookupProxy(String hostKey, String portKey, Proxy.Type type, int defaultPort) { """ Returns the proxy identified by the {@code hostKey} system property, or null. """ String host = System.getProperty(hostKey); if (host == null || host.isEmpty()) { return null; } int port = getSystemPropertyInt(portKey, defaultPort); return new Proxy(type, InetSocketAddress.createUnresolved(host, port)); }
java
private Proxy lookupProxy(String hostKey, String portKey, Proxy.Type type, int defaultPort) { String host = System.getProperty(hostKey); if (host == null || host.isEmpty()) { return null; } int port = getSystemPropertyInt(portKey, defaultPort); return new Proxy(type, InetSocketAddress.createUnresolved(host, port)); }
[ "private", "Proxy", "lookupProxy", "(", "String", "hostKey", ",", "String", "portKey", ",", "Proxy", ".", "Type", "type", ",", "int", "defaultPort", ")", "{", "String", "host", "=", "System", ".", "getProperty", "(", "hostKey", ")", ";", "if", "(", "host", "==", "null", "||", "host", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "int", "port", "=", "getSystemPropertyInt", "(", "portKey", ",", "defaultPort", ")", ";", "return", "new", "Proxy", "(", "type", ",", "InetSocketAddress", ".", "createUnresolved", "(", "host", ",", "port", ")", ")", ";", "}" ]
Returns the proxy identified by the {@code hostKey} system property, or null.
[ "Returns", "the", "proxy", "identified", "by", "the", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/ProxySelectorImpl.java#L94-L102
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/Request.java
Request.newMyFriendsRequest
public static Request newMyFriendsRequest(Session session, final GraphUserListCallback callback) { """ Creates a new Request configured to retrieve a user's friend list. @param session the Session to use, or null; if non-null, the session must be in an opened state @param callback a callback that will be called when the request is completed to handle success or error conditions @return a Request that is ready to execute """ Callback wrapper = new Callback() { @Override public void onCompleted(Response response) { if (callback != null) { callback.onCompleted(typedListFromResponse(response, GraphUser.class), response); } } }; return new Request(session, MY_FRIENDS, null, null, wrapper); }
java
public static Request newMyFriendsRequest(Session session, final GraphUserListCallback callback) { Callback wrapper = new Callback() { @Override public void onCompleted(Response response) { if (callback != null) { callback.onCompleted(typedListFromResponse(response, GraphUser.class), response); } } }; return new Request(session, MY_FRIENDS, null, null, wrapper); }
[ "public", "static", "Request", "newMyFriendsRequest", "(", "Session", "session", ",", "final", "GraphUserListCallback", "callback", ")", "{", "Callback", "wrapper", "=", "new", "Callback", "(", ")", "{", "@", "Override", "public", "void", "onCompleted", "(", "Response", "response", ")", "{", "if", "(", "callback", "!=", "null", ")", "{", "callback", ".", "onCompleted", "(", "typedListFromResponse", "(", "response", ",", "GraphUser", ".", "class", ")", ",", "response", ")", ";", "}", "}", "}", ";", "return", "new", "Request", "(", "session", ",", "MY_FRIENDS", ",", "null", ",", "null", ",", "wrapper", ")", ";", "}" ]
Creates a new Request configured to retrieve a user's friend list. @param session the Session to use, or null; if non-null, the session must be in an opened state @param callback a callback that will be called when the request is completed to handle success or error conditions @return a Request that is ready to execute
[ "Creates", "a", "new", "Request", "configured", "to", "retrieve", "a", "user", "s", "friend", "list", "." ]
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/Request.java#L296-L306
tvesalainen/util
ham/src/main/java/org/vesalainen/ham/Station.java
Station.inMap
public boolean inMap(String name, Location location) { """ Returns true if location is inside named map. @param name @param location @return """ MapArea map = maps.get(name); if (map == null) { throw new IllegalArgumentException(name); } return map.isInside(location); }
java
public boolean inMap(String name, Location location) { MapArea map = maps.get(name); if (map == null) { throw new IllegalArgumentException(name); } return map.isInside(location); }
[ "public", "boolean", "inMap", "(", "String", "name", ",", "Location", "location", ")", "{", "MapArea", "map", "=", "maps", ".", "get", "(", "name", ")", ";", "if", "(", "map", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "name", ")", ";", "}", "return", "map", ".", "isInside", "(", "location", ")", ";", "}" ]
Returns true if location is inside named map. @param name @param location @return
[ "Returns", "true", "if", "location", "is", "inside", "named", "map", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/ham/src/main/java/org/vesalainen/ham/Station.java#L57-L65
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/SessionsInner.java
SessionsInner.getAsync
public Observable<IntegrationAccountSessionInner> getAsync(String resourceGroupName, String integrationAccountName, String sessionName) { """ Gets an integration account session. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param sessionName The integration account session name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the IntegrationAccountSessionInner object """ return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, sessionName).map(new Func1<ServiceResponse<IntegrationAccountSessionInner>, IntegrationAccountSessionInner>() { @Override public IntegrationAccountSessionInner call(ServiceResponse<IntegrationAccountSessionInner> response) { return response.body(); } }); }
java
public Observable<IntegrationAccountSessionInner> getAsync(String resourceGroupName, String integrationAccountName, String sessionName) { return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, sessionName).map(new Func1<ServiceResponse<IntegrationAccountSessionInner>, IntegrationAccountSessionInner>() { @Override public IntegrationAccountSessionInner call(ServiceResponse<IntegrationAccountSessionInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "IntegrationAccountSessionInner", ">", "getAsync", "(", "String", "resourceGroupName", ",", "String", "integrationAccountName", ",", "String", "sessionName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "integrationAccountName", ",", "sessionName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "IntegrationAccountSessionInner", ">", ",", "IntegrationAccountSessionInner", ">", "(", ")", "{", "@", "Override", "public", "IntegrationAccountSessionInner", "call", "(", "ServiceResponse", "<", "IntegrationAccountSessionInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets an integration account session. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param sessionName The integration account session name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the IntegrationAccountSessionInner object
[ "Gets", "an", "integration", "account", "session", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/SessionsInner.java#L375-L382
alkacon/opencms-core
src/org/opencms/ui/apps/sessions/CmsUserInfoDialog.java
CmsUserInfoDialog.showUserInfo
public static void showUserInfo(CmsSessionInfo session) { """ Shows a dialog with user information for given session. @param session to show information for """ final Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide); CmsUserInfoDialog dialog = new CmsUserInfoDialog(session, new Runnable() { public void run() { window.close(); } }); window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_SHOW_USER_0)); window.setContent(dialog); A_CmsUI.get().addWindow(window); }
java
public static void showUserInfo(CmsSessionInfo session) { final Window window = CmsBasicDialog.prepareWindow(DialogWidth.wide); CmsUserInfoDialog dialog = new CmsUserInfoDialog(session, new Runnable() { public void run() { window.close(); } }); window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_SHOW_USER_0)); window.setContent(dialog); A_CmsUI.get().addWindow(window); }
[ "public", "static", "void", "showUserInfo", "(", "CmsSessionInfo", "session", ")", "{", "final", "Window", "window", "=", "CmsBasicDialog", ".", "prepareWindow", "(", "DialogWidth", ".", "wide", ")", ";", "CmsUserInfoDialog", "dialog", "=", "new", "CmsUserInfoDialog", "(", "session", ",", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "window", ".", "close", "(", ")", ";", "}", "}", ")", ";", "window", ".", "setCaption", "(", "CmsVaadinUtils", ".", "getMessageText", "(", "Messages", ".", "GUI_MESSAGES_SHOW_USER_0", ")", ")", ";", "window", ".", "setContent", "(", "dialog", ")", ";", "A_CmsUI", ".", "get", "(", ")", ".", "addWindow", "(", "window", ")", ";", "}" ]
Shows a dialog with user information for given session. @param session to show information for
[ "Shows", "a", "dialog", "with", "user", "information", "for", "given", "session", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/sessions/CmsUserInfoDialog.java#L163-L177
belaban/JGroups
src/org/jgroups/Message.java
Message.putHeader
public Message putHeader(short id, Header hdr) { """ Puts a header given an ID into the hashmap. Overwrites potential existing entry. """ if(id < 0) throw new IllegalArgumentException("An ID of " + id + " is invalid"); if(hdr != null) hdr.setProtId(id); synchronized(this) { Header[] resized_array=Headers.putHeader(this.headers, id, hdr, true); if(resized_array != null) this.headers=resized_array; } return this; }
java
public Message putHeader(short id, Header hdr) { if(id < 0) throw new IllegalArgumentException("An ID of " + id + " is invalid"); if(hdr != null) hdr.setProtId(id); synchronized(this) { Header[] resized_array=Headers.putHeader(this.headers, id, hdr, true); if(resized_array != null) this.headers=resized_array; } return this; }
[ "public", "Message", "putHeader", "(", "short", "id", ",", "Header", "hdr", ")", "{", "if", "(", "id", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"An ID of \"", "+", "id", "+", "\" is invalid\"", ")", ";", "if", "(", "hdr", "!=", "null", ")", "hdr", ".", "setProtId", "(", "id", ")", ";", "synchronized", "(", "this", ")", "{", "Header", "[", "]", "resized_array", "=", "Headers", ".", "putHeader", "(", "this", ".", "headers", ",", "id", ",", "hdr", ",", "true", ")", ";", "if", "(", "resized_array", "!=", "null", ")", "this", ".", "headers", "=", "resized_array", ";", "}", "return", "this", ";", "}" ]
Puts a header given an ID into the hashmap. Overwrites potential existing entry.
[ "Puts", "a", "header", "given", "an", "ID", "into", "the", "hashmap", ".", "Overwrites", "potential", "existing", "entry", "." ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/Message.java#L460-L471
redkale/redkale
src/org/redkale/convert/bson/BsonReader.java
BsonReader.hasNext
@Override public boolean hasNext(int startPosition, int contentLength) { """ 判断对象是否存在下一个属性或者数组是否存在下一个元素 @param startPosition 起始位置 @param contentLength 内容大小, 不确定的传-1 @return 是否存在 """ byte b = readByte(); if (b == SIGN_HASNEXT) return true; if (b != SIGN_NONEXT) throw new ConvertException("hasNext option must be (" + (SIGN_HASNEXT) + " or " + (SIGN_NONEXT) + ") but '" + b + "' at position(" + this.position + ")"); return false; }
java
@Override public boolean hasNext(int startPosition, int contentLength) { byte b = readByte(); if (b == SIGN_HASNEXT) return true; if (b != SIGN_NONEXT) throw new ConvertException("hasNext option must be (" + (SIGN_HASNEXT) + " or " + (SIGN_NONEXT) + ") but '" + b + "' at position(" + this.position + ")"); return false; }
[ "@", "Override", "public", "boolean", "hasNext", "(", "int", "startPosition", ",", "int", "contentLength", ")", "{", "byte", "b", "=", "readByte", "(", ")", ";", "if", "(", "b", "==", "SIGN_HASNEXT", ")", "return", "true", ";", "if", "(", "b", "!=", "SIGN_NONEXT", ")", "throw", "new", "ConvertException", "(", "\"hasNext option must be (\"", "+", "(", "SIGN_HASNEXT", ")", "+", "\" or \"", "+", "(", "SIGN_NONEXT", ")", "+", "\") but '\"", "+", "b", "+", "\"' at position(\"", "+", "this", ".", "position", "+", "\")\"", ")", ";", "return", "false", ";", "}" ]
判断对象是否存在下一个属性或者数组是否存在下一个元素 @param startPosition 起始位置 @param contentLength 内容大小, 不确定的传-1 @return 是否存在
[ "判断对象是否存在下一个属性或者数组是否存在下一个元素" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/convert/bson/BsonReader.java#L211-L218
OpenLiberty/open-liberty
dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/FileLogSet.java
FileLogSet.addFile
private void addFile(int index, String file) { """ Adds a file name to the files list at the specified index. If adding this file would cause the number of files to exceed the maximum, remove all files after the specified index, and then remove the oldest files until the number is reduced to the maximum. @param index the index in the files list to insert the file @param file the file name """ if (maxFiles > 0) { int numFiles = files.size(); int maxDateFiles = getMaxDateFiles(); // If there is no max or we have fewer than max, then we're done. if (maxDateFiles <= 0 || numFiles < maxDateFiles) { files.add(index, file); } else { // The file names we deal with (messages_xx.xx.xx_xx.xx.xx.log) // have dates, and we want to always be using the "most recent", // so delete everything "newer" (index and after), which might be // present if the system clock goes backwards, and then delete // the oldest files until only maxDateFiles-1 remain. while (files.size() > index) { removeFile(files.size() - 1); } while (files.size() >= maxDateFiles) { removeFile(0); } files.add(file); } } }
java
private void addFile(int index, String file) { if (maxFiles > 0) { int numFiles = files.size(); int maxDateFiles = getMaxDateFiles(); // If there is no max or we have fewer than max, then we're done. if (maxDateFiles <= 0 || numFiles < maxDateFiles) { files.add(index, file); } else { // The file names we deal with (messages_xx.xx.xx_xx.xx.xx.log) // have dates, and we want to always be using the "most recent", // so delete everything "newer" (index and after), which might be // present if the system clock goes backwards, and then delete // the oldest files until only maxDateFiles-1 remain. while (files.size() > index) { removeFile(files.size() - 1); } while (files.size() >= maxDateFiles) { removeFile(0); } files.add(file); } } }
[ "private", "void", "addFile", "(", "int", "index", ",", "String", "file", ")", "{", "if", "(", "maxFiles", ">", "0", ")", "{", "int", "numFiles", "=", "files", ".", "size", "(", ")", ";", "int", "maxDateFiles", "=", "getMaxDateFiles", "(", ")", ";", "// If there is no max or we have fewer than max, then we're done.", "if", "(", "maxDateFiles", "<=", "0", "||", "numFiles", "<", "maxDateFiles", ")", "{", "files", ".", "add", "(", "index", ",", "file", ")", ";", "}", "else", "{", "// The file names we deal with (messages_xx.xx.xx_xx.xx.xx.log)", "// have dates, and we want to always be using the \"most recent\",", "// so delete everything \"newer\" (index and after), which might be", "// present if the system clock goes backwards, and then delete", "// the oldest files until only maxDateFiles-1 remain.", "while", "(", "files", ".", "size", "(", ")", ">", "index", ")", "{", "removeFile", "(", "files", ".", "size", "(", ")", "-", "1", ")", ";", "}", "while", "(", "files", ".", "size", "(", ")", ">=", "maxDateFiles", ")", "{", "removeFile", "(", "0", ")", ";", "}", "files", ".", "add", "(", "file", ")", ";", "}", "}", "}" ]
Adds a file name to the files list at the specified index. If adding this file would cause the number of files to exceed the maximum, remove all files after the specified index, and then remove the oldest files until the number is reduced to the maximum. @param index the index in the files list to insert the file @param file the file name
[ "Adds", "a", "file", "name", "to", "the", "files", "list", "at", "the", "specified", "index", ".", "If", "adding", "this", "file", "would", "cause", "the", "number", "of", "files", "to", "exceed", "the", "maximum", "remove", "all", "files", "after", "the", "specified", "index", "and", "then", "remove", "the", "oldest", "files", "until", "the", "number", "is", "reduced", "to", "the", "maximum", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging/src/com/ibm/ws/logging/internal/impl/FileLogSet.java#L387-L411
rholder/moar-concurrent
src/main/java/com/github/rholder/moar/concurrent/StrategicExecutors.java
StrategicExecutors.newBalancingThreadPoolExecutor
public static BalancingThreadPoolExecutor newBalancingThreadPoolExecutor(int maxThreads, float targetUtilization, float smoothingWeight, int balanceAfter) { """ Return a capped {@link BalancingThreadPoolExecutor} with the given maximum number of threads, target utilization, smoothing weight, and balance after values. @param maxThreads maximum number of threads to use @param targetUtilization a float between 0.0 and 1.0 representing the percentage of the total CPU time to be used by this pool @param smoothingWeight smooth out the averages of the CPU and wait time over time such that tasks aren't too heavily skewed with old or spiking data @param balanceAfter balance the thread pool after this many tasks have run """ ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new CallerBlocksPolicy()); return newBalancingThreadPoolExecutor(tpe, targetUtilization, smoothingWeight, balanceAfter); }
java
public static BalancingThreadPoolExecutor newBalancingThreadPoolExecutor(int maxThreads, float targetUtilization, float smoothingWeight, int balanceAfter) { ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new CallerBlocksPolicy()); return newBalancingThreadPoolExecutor(tpe, targetUtilization, smoothingWeight, balanceAfter); }
[ "public", "static", "BalancingThreadPoolExecutor", "newBalancingThreadPoolExecutor", "(", "int", "maxThreads", ",", "float", "targetUtilization", ",", "float", "smoothingWeight", ",", "int", "balanceAfter", ")", "{", "ThreadPoolExecutor", "tpe", "=", "new", "ThreadPoolExecutor", "(", "1", ",", "maxThreads", ",", "60L", ",", "TimeUnit", ".", "SECONDS", ",", "new", "SynchronousQueue", "<", "Runnable", ">", "(", ")", ",", "new", "CallerBlocksPolicy", "(", ")", ")", ";", "return", "newBalancingThreadPoolExecutor", "(", "tpe", ",", "targetUtilization", ",", "smoothingWeight", ",", "balanceAfter", ")", ";", "}" ]
Return a capped {@link BalancingThreadPoolExecutor} with the given maximum number of threads, target utilization, smoothing weight, and balance after values. @param maxThreads maximum number of threads to use @param targetUtilization a float between 0.0 and 1.0 representing the percentage of the total CPU time to be used by this pool @param smoothingWeight smooth out the averages of the CPU and wait time over time such that tasks aren't too heavily skewed with old or spiking data @param balanceAfter balance the thread pool after this many tasks have run
[ "Return", "a", "capped", "{", "@link", "BalancingThreadPoolExecutor", "}", "with", "the", "given", "maximum", "number", "of", "threads", "target", "utilization", "smoothing", "weight", "and", "balance", "after", "values", "." ]
train
https://github.com/rholder/moar-concurrent/blob/c28facbf02e628cc37266c051c23d4a7654b4eba/src/main/java/com/github/rholder/moar/concurrent/StrategicExecutors.java#L67-L73
mboudreau/Alternator
src/main/java/com/amazonaws/services/dynamodb/model/BatchGetItemResult.java
BatchGetItemResult.withResponses
public BatchGetItemResult withResponses(java.util.Map<String,BatchResponse> responses) { """ Table names and the respective item attributes from the tables. <p> Returns a reference to this object so that method calls can be chained together. @param responses Table names and the respective item attributes from the tables. @return A reference to this updated object so that method calls can be chained together. """ setResponses(responses); return this; }
java
public BatchGetItemResult withResponses(java.util.Map<String,BatchResponse> responses) { setResponses(responses); return this; }
[ "public", "BatchGetItemResult", "withResponses", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "BatchResponse", ">", "responses", ")", "{", "setResponses", "(", "responses", ")", ";", "return", "this", ";", "}" ]
Table names and the respective item attributes from the tables. <p> Returns a reference to this object so that method calls can be chained together. @param responses Table names and the respective item attributes from the tables. @return A reference to this updated object so that method calls can be chained together.
[ "Table", "names", "and", "the", "respective", "item", "attributes", "from", "the", "tables", ".", "<p", ">", "Returns", "a", "reference", "to", "this", "object", "so", "that", "method", "calls", "can", "be", "chained", "together", "." ]
train
https://github.com/mboudreau/Alternator/blob/4b230ac843494cb10e46ddc2848f5b5d377d7b72/src/main/java/com/amazonaws/services/dynamodb/model/BatchGetItemResult.java#L74-L77
tango-controls/JTango
server/src/main/java/org/tango/server/attribute/AttributeConfiguration.java
AttributeConfiguration.setTangoType
public void setTangoType(final int tangoType, final AttrDataFormat format) throws DevFailed { """ Set the attribute type with Tango type. @param tangoType @throws DevFailed @see TangoConst for possible values """ setFormat(format); this.tangoType = tangoType; enumType = AttributeTangoType.getTypeFromTango(tangoType); if (format.equals(AttrDataFormat.SCALAR)) { type = enumType.getType(); } else if (format.equals(AttrDataFormat.SPECTRUM)) { type = Array.newInstance(enumType.getType(), 0).getClass(); } else { type = Array.newInstance(enumType.getType(), 0, 0).getClass(); } }
java
public void setTangoType(final int tangoType, final AttrDataFormat format) throws DevFailed { setFormat(format); this.tangoType = tangoType; enumType = AttributeTangoType.getTypeFromTango(tangoType); if (format.equals(AttrDataFormat.SCALAR)) { type = enumType.getType(); } else if (format.equals(AttrDataFormat.SPECTRUM)) { type = Array.newInstance(enumType.getType(), 0).getClass(); } else { type = Array.newInstance(enumType.getType(), 0, 0).getClass(); } }
[ "public", "void", "setTangoType", "(", "final", "int", "tangoType", ",", "final", "AttrDataFormat", "format", ")", "throws", "DevFailed", "{", "setFormat", "(", "format", ")", ";", "this", ".", "tangoType", "=", "tangoType", ";", "enumType", "=", "AttributeTangoType", ".", "getTypeFromTango", "(", "tangoType", ")", ";", "if", "(", "format", ".", "equals", "(", "AttrDataFormat", ".", "SCALAR", ")", ")", "{", "type", "=", "enumType", ".", "getType", "(", ")", ";", "}", "else", "if", "(", "format", ".", "equals", "(", "AttrDataFormat", ".", "SPECTRUM", ")", ")", "{", "type", "=", "Array", ".", "newInstance", "(", "enumType", ".", "getType", "(", ")", ",", "0", ")", ".", "getClass", "(", ")", ";", "}", "else", "{", "type", "=", "Array", ".", "newInstance", "(", "enumType", ".", "getType", "(", ")", ",", "0", ",", "0", ")", ".", "getClass", "(", ")", ";", "}", "}" ]
Set the attribute type with Tango type. @param tangoType @throws DevFailed @see TangoConst for possible values
[ "Set", "the", "attribute", "type", "with", "Tango", "type", "." ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/attribute/AttributeConfiguration.java#L245-L256
SonarSource/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/internal/FileMetadata.java
FileMetadata.computeLineHashesForIssueTracking
public static void computeLineHashesForIssueTracking(InputFile f, LineHashConsumer consumer) { """ Compute a MD5 hash of each line of the file after removing of all blank chars """ try { readFile(f.inputStream(), f.charset(), f.absolutePath(), new CharHandler[] {new LineHashComputer(consumer, f.file())}); } catch (IOException e) { throw new IllegalStateException("Failed to compute line hashes for " + f.absolutePath(), e); } }
java
public static void computeLineHashesForIssueTracking(InputFile f, LineHashConsumer consumer) { try { readFile(f.inputStream(), f.charset(), f.absolutePath(), new CharHandler[] {new LineHashComputer(consumer, f.file())}); } catch (IOException e) { throw new IllegalStateException("Failed to compute line hashes for " + f.absolutePath(), e); } }
[ "public", "static", "void", "computeLineHashesForIssueTracking", "(", "InputFile", "f", ",", "LineHashConsumer", "consumer", ")", "{", "try", "{", "readFile", "(", "f", ".", "inputStream", "(", ")", ",", "f", ".", "charset", "(", ")", ",", "f", ".", "absolutePath", "(", ")", ",", "new", "CharHandler", "[", "]", "{", "new", "LineHashComputer", "(", "consumer", ",", "f", ".", "file", "(", ")", ")", "}", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Failed to compute line hashes for \"", "+", "f", ".", "absolutePath", "(", ")", ",", "e", ")", ";", "}", "}" ]
Compute a MD5 hash of each line of the file after removing of all blank chars
[ "Compute", "a", "MD5", "hash", "of", "each", "line", "of", "the", "file", "after", "removing", "of", "all", "blank", "chars" ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/internal/FileMetadata.java#L154-L160
aws/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/retry/ClockSkewAdjuster.java
ClockSkewAdjuster.getAdjustment
public ClockSkewAdjustment getAdjustment(AdjustmentRequest adjustmentRequest) { """ Recommend a {@link ClockSkewAdjustment}, based on the provided {@link AdjustmentRequest}. """ ValidationUtils.assertNotNull(adjustmentRequest, "adjustmentRequest"); ValidationUtils.assertNotNull(adjustmentRequest.exception, "adjustmentRequest.exception"); ValidationUtils.assertNotNull(adjustmentRequest.clientRequest, "adjustmentRequest.clientRequest"); ValidationUtils.assertNotNull(adjustmentRequest.serviceResponse, "adjustmentRequest.serviceResponse"); int timeSkewInSeconds = 0; boolean isAdjustmentRecommended = false; try { if (isAdjustmentRecommended(adjustmentRequest)) { Date serverDate = getServerDate(adjustmentRequest); if (serverDate != null) { timeSkewInSeconds = timeSkewInSeconds(getCurrentDate(adjustmentRequest), serverDate); isAdjustmentRecommended = true; } } } catch (RuntimeException e) { log.warn("Unable to correct for clock skew.", e); } return new ClockSkewAdjustment(isAdjustmentRecommended, timeSkewInSeconds); }
java
public ClockSkewAdjustment getAdjustment(AdjustmentRequest adjustmentRequest) { ValidationUtils.assertNotNull(adjustmentRequest, "adjustmentRequest"); ValidationUtils.assertNotNull(adjustmentRequest.exception, "adjustmentRequest.exception"); ValidationUtils.assertNotNull(adjustmentRequest.clientRequest, "adjustmentRequest.clientRequest"); ValidationUtils.assertNotNull(adjustmentRequest.serviceResponse, "adjustmentRequest.serviceResponse"); int timeSkewInSeconds = 0; boolean isAdjustmentRecommended = false; try { if (isAdjustmentRecommended(adjustmentRequest)) { Date serverDate = getServerDate(adjustmentRequest); if (serverDate != null) { timeSkewInSeconds = timeSkewInSeconds(getCurrentDate(adjustmentRequest), serverDate); isAdjustmentRecommended = true; } } } catch (RuntimeException e) { log.warn("Unable to correct for clock skew.", e); } return new ClockSkewAdjustment(isAdjustmentRecommended, timeSkewInSeconds); }
[ "public", "ClockSkewAdjustment", "getAdjustment", "(", "AdjustmentRequest", "adjustmentRequest", ")", "{", "ValidationUtils", ".", "assertNotNull", "(", "adjustmentRequest", ",", "\"adjustmentRequest\"", ")", ";", "ValidationUtils", ".", "assertNotNull", "(", "adjustmentRequest", ".", "exception", ",", "\"adjustmentRequest.exception\"", ")", ";", "ValidationUtils", ".", "assertNotNull", "(", "adjustmentRequest", ".", "clientRequest", ",", "\"adjustmentRequest.clientRequest\"", ")", ";", "ValidationUtils", ".", "assertNotNull", "(", "adjustmentRequest", ".", "serviceResponse", ",", "\"adjustmentRequest.serviceResponse\"", ")", ";", "int", "timeSkewInSeconds", "=", "0", ";", "boolean", "isAdjustmentRecommended", "=", "false", ";", "try", "{", "if", "(", "isAdjustmentRecommended", "(", "adjustmentRequest", ")", ")", "{", "Date", "serverDate", "=", "getServerDate", "(", "adjustmentRequest", ")", ";", "if", "(", "serverDate", "!=", "null", ")", "{", "timeSkewInSeconds", "=", "timeSkewInSeconds", "(", "getCurrentDate", "(", "adjustmentRequest", ")", ",", "serverDate", ")", ";", "isAdjustmentRecommended", "=", "true", ";", "}", "}", "}", "catch", "(", "RuntimeException", "e", ")", "{", "log", ".", "warn", "(", "\"Unable to correct for clock skew.\"", ",", "e", ")", ";", "}", "return", "new", "ClockSkewAdjustment", "(", "isAdjustmentRecommended", ",", "timeSkewInSeconds", ")", ";", "}" ]
Recommend a {@link ClockSkewAdjustment}, based on the provided {@link AdjustmentRequest}.
[ "Recommend", "a", "{" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/retry/ClockSkewAdjuster.java#L68-L91
fabric8io/fabric8-forge
addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/helper/CamelVersionHelper.java
CamelVersionHelper.isGE
public static boolean isGE(String base, String other) { """ Checks whether other >= base @param base the base version @param other the other version @return <tt>true</tt> if GE, <tt>false</tt> otherwise """ ComparableVersion v1 = new ComparableVersion(base); ComparableVersion v2 = new ComparableVersion(other); return v2.compareTo(v1) >= 0; }
java
public static boolean isGE(String base, String other) { ComparableVersion v1 = new ComparableVersion(base); ComparableVersion v2 = new ComparableVersion(other); return v2.compareTo(v1) >= 0; }
[ "public", "static", "boolean", "isGE", "(", "String", "base", ",", "String", "other", ")", "{", "ComparableVersion", "v1", "=", "new", "ComparableVersion", "(", "base", ")", ";", "ComparableVersion", "v2", "=", "new", "ComparableVersion", "(", "other", ")", ";", "return", "v2", ".", "compareTo", "(", "v1", ")", ">=", "0", ";", "}" ]
Checks whether other >= base @param base the base version @param other the other version @return <tt>true</tt> if GE, <tt>false</tt> otherwise
[ "Checks", "whether", "other", ">", "=", "base" ]
train
https://github.com/fabric8io/fabric8-forge/blob/a59871bae4d5c5d3ece10f1e8758e73663087f19/addons/camel/src/main/java/io/fabric8/forge/camel/commands/project/helper/CamelVersionHelper.java#L44-L48
UrielCh/ovh-java-sdk
ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java
ApiOvhDomain.serviceName_glueRecord_host_GET
public OvhGlueRecord serviceName_glueRecord_host_GET(String serviceName, String host) throws IOException { """ Get this object properties REST: GET /domain/{serviceName}/glueRecord/{host} @param serviceName [required] The internal name of your domain @param host [required] Host of the glue record """ String qPath = "/domain/{serviceName}/glueRecord/{host}"; StringBuilder sb = path(qPath, serviceName, host); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhGlueRecord.class); }
java
public OvhGlueRecord serviceName_glueRecord_host_GET(String serviceName, String host) throws IOException { String qPath = "/domain/{serviceName}/glueRecord/{host}"; StringBuilder sb = path(qPath, serviceName, host); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhGlueRecord.class); }
[ "public", "OvhGlueRecord", "serviceName_glueRecord_host_GET", "(", "String", "serviceName", ",", "String", "host", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/domain/{serviceName}/glueRecord/{host}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "host", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhGlueRecord", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /domain/{serviceName}/glueRecord/{host} @param serviceName [required] The internal name of your domain @param host [required] Host of the glue record
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java#L1198-L1203
beihaifeiwu/dolphin
dolphin-common/src/main/java/com/freetmp/common/type/ResolvableType.java
ResolvableType.forMethodParameter
public static ResolvableType forMethodParameter(MethodParameter methodParameter, Type targetType) { """ Return a {@link ResolvableType} for the specified {@link MethodParameter}, overriding the target type to resolve with a specific given type. @param methodParameter the source method parameter (must not be {@code null}) @param targetType the type to resolve (a part of the method parameter's type) @return a {@link ResolvableType} for the specified method parameter @see #forMethodParameter(Method, int) """ Assert.notNull(methodParameter, "MethodParameter must not be null"); ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass()); return forType(targetType, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()). getNested(methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel); }
java
public static ResolvableType forMethodParameter(MethodParameter methodParameter, Type targetType) { Assert.notNull(methodParameter, "MethodParameter must not be null"); ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass()); return forType(targetType, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()). getNested(methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel); }
[ "public", "static", "ResolvableType", "forMethodParameter", "(", "MethodParameter", "methodParameter", ",", "Type", "targetType", ")", "{", "Assert", ".", "notNull", "(", "methodParameter", ",", "\"MethodParameter must not be null\"", ")", ";", "ResolvableType", "owner", "=", "forType", "(", "methodParameter", ".", "getContainingClass", "(", ")", ")", ".", "as", "(", "methodParameter", ".", "getDeclaringClass", "(", ")", ")", ";", "return", "forType", "(", "targetType", ",", "new", "MethodParameterTypeProvider", "(", "methodParameter", ")", ",", "owner", ".", "asVariableResolver", "(", ")", ")", ".", "getNested", "(", "methodParameter", ".", "getNestingLevel", "(", ")", ",", "methodParameter", ".", "typeIndexesPerLevel", ")", ";", "}" ]
Return a {@link ResolvableType} for the specified {@link MethodParameter}, overriding the target type to resolve with a specific given type. @param methodParameter the source method parameter (must not be {@code null}) @param targetType the type to resolve (a part of the method parameter's type) @return a {@link ResolvableType} for the specified method parameter @see #forMethodParameter(Method, int)
[ "Return", "a", "{" ]
train
https://github.com/beihaifeiwu/dolphin/blob/b100579cc6986dce5eba5593ebb5fbae7bad9d1a/dolphin-common/src/main/java/com/freetmp/common/type/ResolvableType.java#L1117-L1122
sksamuel/scrimage
scrimage-filters/src/main/java/thirdparty/jhlabs/math/Noise.java
Noise.noise2
public static float noise2(float x, float y) { """ Compute 2-dimensional Perlin noise. @param x the x coordinate @param y the y coordinate @return noise value at (x,y) """ int bx0, bx1, by0, by1, b00, b10, b01, b11; float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v; int i, j; if (start) { start = false; init(); } t = x + N; bx0 = ((int)t) & BM; bx1 = (bx0+1) & BM; rx0 = t - (int)t; rx1 = rx0 - 1.0f; t = y + N; by0 = ((int)t) & BM; by1 = (by0+1) & BM; ry0 = t - (int)t; ry1 = ry0 - 1.0f; i = p[bx0]; j = p[bx1]; b00 = p[i + by0]; b10 = p[j + by0]; b01 = p[i + by1]; b11 = p[j + by1]; sx = sCurve(rx0); sy = sCurve(ry0); q = g2[b00]; u = rx0 * q[0] + ry0 * q[1]; q = g2[b10]; v = rx1 * q[0] + ry0 * q[1]; a = lerp(sx, u, v); q = g2[b01]; u = rx0 * q[0] + ry1 * q[1]; q = g2[b11]; v = rx1 * q[0] + ry1 * q[1]; b = lerp(sx, u, v); return 1.5f*lerp(sy, a, b); }
java
public static float noise2(float x, float y) { int bx0, bx1, by0, by1, b00, b10, b01, b11; float rx0, rx1, ry0, ry1, q[], sx, sy, a, b, t, u, v; int i, j; if (start) { start = false; init(); } t = x + N; bx0 = ((int)t) & BM; bx1 = (bx0+1) & BM; rx0 = t - (int)t; rx1 = rx0 - 1.0f; t = y + N; by0 = ((int)t) & BM; by1 = (by0+1) & BM; ry0 = t - (int)t; ry1 = ry0 - 1.0f; i = p[bx0]; j = p[bx1]; b00 = p[i + by0]; b10 = p[j + by0]; b01 = p[i + by1]; b11 = p[j + by1]; sx = sCurve(rx0); sy = sCurve(ry0); q = g2[b00]; u = rx0 * q[0] + ry0 * q[1]; q = g2[b10]; v = rx1 * q[0] + ry0 * q[1]; a = lerp(sx, u, v); q = g2[b01]; u = rx0 * q[0] + ry1 * q[1]; q = g2[b11]; v = rx1 * q[0] + ry1 * q[1]; b = lerp(sx, u, v); return 1.5f*lerp(sy, a, b); }
[ "public", "static", "float", "noise2", "(", "float", "x", ",", "float", "y", ")", "{", "int", "bx0", ",", "bx1", ",", "by0", ",", "by1", ",", "b00", ",", "b10", ",", "b01", ",", "b11", ";", "float", "rx0", ",", "rx1", ",", "ry0", ",", "ry1", ",", "q", "[", "]", ",", "sx", ",", "sy", ",", "a", ",", "b", ",", "t", ",", "u", ",", "v", ";", "int", "i", ",", "j", ";", "if", "(", "start", ")", "{", "start", "=", "false", ";", "init", "(", ")", ";", "}", "t", "=", "x", "+", "N", ";", "bx0", "=", "(", "(", "int", ")", "t", ")", "&", "BM", ";", "bx1", "=", "(", "bx0", "+", "1", ")", "&", "BM", ";", "rx0", "=", "t", "-", "(", "int", ")", "t", ";", "rx1", "=", "rx0", "-", "1.0f", ";", "t", "=", "y", "+", "N", ";", "by0", "=", "(", "(", "int", ")", "t", ")", "&", "BM", ";", "by1", "=", "(", "by0", "+", "1", ")", "&", "BM", ";", "ry0", "=", "t", "-", "(", "int", ")", "t", ";", "ry1", "=", "ry0", "-", "1.0f", ";", "i", "=", "p", "[", "bx0", "]", ";", "j", "=", "p", "[", "bx1", "]", ";", "b00", "=", "p", "[", "i", "+", "by0", "]", ";", "b10", "=", "p", "[", "j", "+", "by0", "]", ";", "b01", "=", "p", "[", "i", "+", "by1", "]", ";", "b11", "=", "p", "[", "j", "+", "by1", "]", ";", "sx", "=", "sCurve", "(", "rx0", ")", ";", "sy", "=", "sCurve", "(", "ry0", ")", ";", "q", "=", "g2", "[", "b00", "]", ";", "u", "=", "rx0", "*", "q", "[", "0", "]", "+", "ry0", "*", "q", "[", "1", "]", ";", "q", "=", "g2", "[", "b10", "]", ";", "v", "=", "rx1", "*", "q", "[", "0", "]", "+", "ry0", "*", "q", "[", "1", "]", ";", "a", "=", "lerp", "(", "sx", ",", "u", ",", "v", ")", ";", "q", "=", "g2", "[", "b01", "]", ";", "u", "=", "rx0", "*", "q", "[", "0", "]", "+", "ry1", "*", "q", "[", "1", "]", ";", "q", "=", "g2", "[", "b11", "]", ";", "v", "=", "rx1", "*", "q", "[", "0", "]", "+", "ry1", "*", "q", "[", "1", "]", ";", "b", "=", "lerp", "(", "sx", ",", "u", ",", "v", ")", ";", "return", "1.5f", "*", "lerp", "(", "sy", ",", "a", ",", "b", ")", ";", "}" ]
Compute 2-dimensional Perlin noise. @param x the x coordinate @param y the y coordinate @return noise value at (x,y)
[ "Compute", "2", "-", "dimensional", "Perlin", "noise", "." ]
train
https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-filters/src/main/java/thirdparty/jhlabs/math/Noise.java#L117-L159
bbossgroups/bboss-elasticsearch
bboss-elasticsearch-rest/src/main/java/org/frameworkset/elasticsearch/ElasticSearchHelper.java
ElasticSearchHelper.booter
public static void booter(String[] elasticsearchServerNames,GetProperties configContext,boolean forceBoot) { """ <property name="elasticsearch.client" value="${elasticsearch.client:restful}"> <description> <![CDATA[ 客户端类型:transport,restful ]]></description> </property> <property name="elasticUser" value="${elasticUser:}"> <description> <![CDATA[ 认证用户 ]]></description> </property> <property name="elasticPassword" value="${elasticPassword:}"> <description> <![CDATA[ 认证口令 ]]></description> </property> <!--<property name="elasticsearch.hostNames" value="${elasticsearch.hostNames}"> <description> <![CDATA[ 指定序列化处理类,默认为kafka.serializer.DefaultEncoder,即byte[] ]]></description> </property>--> <property name="elasticsearch.rest.hostNames" value="${elasticsearch.rest.hostNames:127.0.0.1:9200}"> <description> <![CDATA[ rest协议地址 ]]></description> </property> <property name="elasticsearch.dateFormat" value="${elasticsearch.dateFormat:yyyy.MM.dd}"> <description> <![CDATA[ 索引日期格式]]></description> </property> <property name="elasticsearch.timeZone" value="${elasticsearch.timeZone:Asia/Shanghai}"> <description> <![CDATA[ 时区信息]]></description> </property> <property name="elasticsearch.ttl" value="${elasticsearch.ttl:2d}"> <description> <![CDATA[ ms(毫秒) s(秒) m(分钟) h(小时) d(天) w(星期)]]></description> </property> <property name="elasticsearch.showTemplate" value="${elasticsearch.showTemplate:false}"> <description> <![CDATA[ query dsl脚本日志调试开关,与log info级别日志结合使用]]></description> </property> <property name="elasticsearch.httpPool" value="${elasticsearch.httpPool:default}"> <description> <![CDATA[ http连接池逻辑名称,在conf/httpclient.xml中配置]]></description> </property> <property name="elasticsearch.discoverHost" value="${elasticsearch.discoverHost:false}"> <description> <![CDATA[ 是否启动节点自动发现功能,默认关闭,开启后每隔10秒探测新加或者移除的es节点,实时更新本地地址清单]]></description> </property> """ booter( elasticsearchServerNames, configContext, forceBoot,false); }
java
public static void booter(String[] elasticsearchServerNames,GetProperties configContext,boolean forceBoot){ booter( elasticsearchServerNames, configContext, forceBoot,false); }
[ "public", "static", "void", "booter", "(", "String", "[", "]", "elasticsearchServerNames", ",", "GetProperties", "configContext", ",", "boolean", "forceBoot", ")", "{", "booter", "(", "elasticsearchServerNames", ",", "configContext", ",", "forceBoot", ",", "false", ")", ";", "}" ]
<property name="elasticsearch.client" value="${elasticsearch.client:restful}"> <description> <![CDATA[ 客户端类型:transport,restful ]]></description> </property> <property name="elasticUser" value="${elasticUser:}"> <description> <![CDATA[ 认证用户 ]]></description> </property> <property name="elasticPassword" value="${elasticPassword:}"> <description> <![CDATA[ 认证口令 ]]></description> </property> <!--<property name="elasticsearch.hostNames" value="${elasticsearch.hostNames}"> <description> <![CDATA[ 指定序列化处理类,默认为kafka.serializer.DefaultEncoder,即byte[] ]]></description> </property>--> <property name="elasticsearch.rest.hostNames" value="${elasticsearch.rest.hostNames:127.0.0.1:9200}"> <description> <![CDATA[ rest协议地址 ]]></description> </property> <property name="elasticsearch.dateFormat" value="${elasticsearch.dateFormat:yyyy.MM.dd}"> <description> <![CDATA[ 索引日期格式]]></description> </property> <property name="elasticsearch.timeZone" value="${elasticsearch.timeZone:Asia/Shanghai}"> <description> <![CDATA[ 时区信息]]></description> </property> <property name="elasticsearch.ttl" value="${elasticsearch.ttl:2d}"> <description> <![CDATA[ ms(毫秒) s(秒) m(分钟) h(小时) d(天) w(星期)]]></description> </property> <property name="elasticsearch.showTemplate" value="${elasticsearch.showTemplate:false}"> <description> <![CDATA[ query dsl脚本日志调试开关,与log info级别日志结合使用]]></description> </property> <property name="elasticsearch.httpPool" value="${elasticsearch.httpPool:default}"> <description> <![CDATA[ http连接池逻辑名称,在conf/httpclient.xml中配置]]></description> </property> <property name="elasticsearch.discoverHost" value="${elasticsearch.discoverHost:false}"> <description> <![CDATA[ 是否启动节点自动发现功能,默认关闭,开启后每隔10秒探测新加或者移除的es节点,实时更新本地地址清单]]></description> </property>
[ "<property", "name", "=", "elasticsearch", ".", "client", "value", "=", "$", "{", "elasticsearch", ".", "client", ":", "restful", "}", ">", "<description", ">", "<!", "[", "CDATA", "[", "客户端类型", ":", "transport,restful", "]]", ">", "<", "/", "description", ">", "<", "/", "property", ">" ]
train
https://github.com/bbossgroups/bboss-elasticsearch/blob/31717c8aa2c4c880987be53aeeb8a0cf5183c3a7/bboss-elasticsearch-rest/src/main/java/org/frameworkset/elasticsearch/ElasticSearchHelper.java#L97-L99
netty/netty
common/src/main/java/io/netty/util/ConstantPool.java
ConstantPool.valueOf
public T valueOf(Class<?> firstNameComponent, String secondNameComponent) { """ Shortcut of {@link #valueOf(String) valueOf(firstNameComponent.getName() + "#" + secondNameComponent)}. """ if (firstNameComponent == null) { throw new NullPointerException("firstNameComponent"); } if (secondNameComponent == null) { throw new NullPointerException("secondNameComponent"); } return valueOf(firstNameComponent.getName() + '#' + secondNameComponent); }
java
public T valueOf(Class<?> firstNameComponent, String secondNameComponent) { if (firstNameComponent == null) { throw new NullPointerException("firstNameComponent"); } if (secondNameComponent == null) { throw new NullPointerException("secondNameComponent"); } return valueOf(firstNameComponent.getName() + '#' + secondNameComponent); }
[ "public", "T", "valueOf", "(", "Class", "<", "?", ">", "firstNameComponent", ",", "String", "secondNameComponent", ")", "{", "if", "(", "firstNameComponent", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"firstNameComponent\"", ")", ";", "}", "if", "(", "secondNameComponent", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"secondNameComponent\"", ")", ";", "}", "return", "valueOf", "(", "firstNameComponent", ".", "getName", "(", ")", "+", "'", "'", "+", "secondNameComponent", ")", ";", "}" ]
Shortcut of {@link #valueOf(String) valueOf(firstNameComponent.getName() + "#" + secondNameComponent)}.
[ "Shortcut", "of", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/ConstantPool.java#L39-L48
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
FieldUtils.removeFinalModifier
public static void removeFinalModifier(final Field field, final boolean forceAccess) { """ Removes the final modifier from a {@link Field}. @param field to remove the final modifier @param forceAccess whether to break scope restrictions using the {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only match {@code public} fields. @throws IllegalArgumentException if the field is {@code null} @since 3.3 """ Validate.isTrue(field != null, "The field must not be null"); try { if (Modifier.isFinal(field.getModifiers())) { // Do all JREs implement Field with a private ivar called "modifiers"? final Field modifiersField = Field.class.getDeclaredField("modifiers"); final boolean doForceAccess = forceAccess && !modifiersField.isAccessible(); if (doForceAccess) { modifiersField.setAccessible(true); } try { modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } finally { if (doForceAccess) { modifiersField.setAccessible(false); } } } } catch (final NoSuchFieldException ignored) { // The field class contains always a modifiers field } catch (final IllegalAccessException ignored) { // The modifiers field is made accessible } }
java
public static void removeFinalModifier(final Field field, final boolean forceAccess) { Validate.isTrue(field != null, "The field must not be null"); try { if (Modifier.isFinal(field.getModifiers())) { // Do all JREs implement Field with a private ivar called "modifiers"? final Field modifiersField = Field.class.getDeclaredField("modifiers"); final boolean doForceAccess = forceAccess && !modifiersField.isAccessible(); if (doForceAccess) { modifiersField.setAccessible(true); } try { modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } finally { if (doForceAccess) { modifiersField.setAccessible(false); } } } } catch (final NoSuchFieldException ignored) { // The field class contains always a modifiers field } catch (final IllegalAccessException ignored) { // The modifiers field is made accessible } }
[ "public", "static", "void", "removeFinalModifier", "(", "final", "Field", "field", ",", "final", "boolean", "forceAccess", ")", "{", "Validate", ".", "isTrue", "(", "field", "!=", "null", ",", "\"The field must not be null\"", ")", ";", "try", "{", "if", "(", "Modifier", ".", "isFinal", "(", "field", ".", "getModifiers", "(", ")", ")", ")", "{", "// Do all JREs implement Field with a private ivar called \"modifiers\"?", "final", "Field", "modifiersField", "=", "Field", ".", "class", ".", "getDeclaredField", "(", "\"modifiers\"", ")", ";", "final", "boolean", "doForceAccess", "=", "forceAccess", "&&", "!", "modifiersField", ".", "isAccessible", "(", ")", ";", "if", "(", "doForceAccess", ")", "{", "modifiersField", ".", "setAccessible", "(", "true", ")", ";", "}", "try", "{", "modifiersField", ".", "setInt", "(", "field", ",", "field", ".", "getModifiers", "(", ")", "&", "~", "Modifier", ".", "FINAL", ")", ";", "}", "finally", "{", "if", "(", "doForceAccess", ")", "{", "modifiersField", ".", "setAccessible", "(", "false", ")", ";", "}", "}", "}", "}", "catch", "(", "final", "NoSuchFieldException", "ignored", ")", "{", "// The field class contains always a modifiers field", "}", "catch", "(", "final", "IllegalAccessException", "ignored", ")", "{", "// The modifiers field is made accessible", "}", "}" ]
Removes the final modifier from a {@link Field}. @param field to remove the final modifier @param forceAccess whether to break scope restrictions using the {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only match {@code public} fields. @throws IllegalArgumentException if the field is {@code null} @since 3.3
[ "Removes", "the", "final", "modifier", "from", "a", "{", "@link", "Field", "}", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java#L720-L744
facebookarchive/hadoop-20
src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/server/ServerCore.java
ServerCore.addClientAndConnect
@Override public long addClientAndConnect(String host, int port) throws TTransportException, IOException { """ Adds the client to the internal data structures and connects to it. If the method throws an exception, then it is guaranteed it will also be removed from the internal structures before throwing the exception. @param host the host on which the client is running @param port the port on which the client is running the Thrift service @return the client's id. @throws TTransportException when something went wrong when connecting to the client. """ long clientId = getNewClientId(); LOG.info("Adding client with id=" + clientId + " host=" + host + " port=" + port + " and connecting ..."); ClientHandler.Client clientHandler; try { clientHandler = getClientConnection(host, port); LOG.info("Succesfully connected to client " + clientId); } catch (IOException e1) { LOG.error("Failed to connect to client " + clientId, e1); throw e1; } catch (TTransportException e2) { LOG.error("Failed to connect to client " + clientId, e2); throw e2; } // Save the client to the internal structures ClientData clientData = new ClientData(clientId, clientHandler, host, port); addClient(clientData); LOG.info("Successfully added client " + clientId + " and connected."); return clientId; }
java
@Override public long addClientAndConnect(String host, int port) throws TTransportException, IOException { long clientId = getNewClientId(); LOG.info("Adding client with id=" + clientId + " host=" + host + " port=" + port + " and connecting ..."); ClientHandler.Client clientHandler; try { clientHandler = getClientConnection(host, port); LOG.info("Succesfully connected to client " + clientId); } catch (IOException e1) { LOG.error("Failed to connect to client " + clientId, e1); throw e1; } catch (TTransportException e2) { LOG.error("Failed to connect to client " + clientId, e2); throw e2; } // Save the client to the internal structures ClientData clientData = new ClientData(clientId, clientHandler, host, port); addClient(clientData); LOG.info("Successfully added client " + clientId + " and connected."); return clientId; }
[ "@", "Override", "public", "long", "addClientAndConnect", "(", "String", "host", ",", "int", "port", ")", "throws", "TTransportException", ",", "IOException", "{", "long", "clientId", "=", "getNewClientId", "(", ")", ";", "LOG", ".", "info", "(", "\"Adding client with id=\"", "+", "clientId", "+", "\" host=\"", "+", "host", "+", "\" port=\"", "+", "port", "+", "\" and connecting ...\"", ")", ";", "ClientHandler", ".", "Client", "clientHandler", ";", "try", "{", "clientHandler", "=", "getClientConnection", "(", "host", ",", "port", ")", ";", "LOG", ".", "info", "(", "\"Succesfully connected to client \"", "+", "clientId", ")", ";", "}", "catch", "(", "IOException", "e1", ")", "{", "LOG", ".", "error", "(", "\"Failed to connect to client \"", "+", "clientId", ",", "e1", ")", ";", "throw", "e1", ";", "}", "catch", "(", "TTransportException", "e2", ")", "{", "LOG", ".", "error", "(", "\"Failed to connect to client \"", "+", "clientId", ",", "e2", ")", ";", "throw", "e2", ";", "}", "// Save the client to the internal structures", "ClientData", "clientData", "=", "new", "ClientData", "(", "clientId", ",", "clientHandler", ",", "host", ",", "port", ")", ";", "addClient", "(", "clientData", ")", ";", "LOG", ".", "info", "(", "\"Successfully added client \"", "+", "clientId", "+", "\" and connected.\"", ")", ";", "return", "clientId", ";", "}" ]
Adds the client to the internal data structures and connects to it. If the method throws an exception, then it is guaranteed it will also be removed from the internal structures before throwing the exception. @param host the host on which the client is running @param port the port on which the client is running the Thrift service @return the client's id. @throws TTransportException when something went wrong when connecting to the client.
[ "Adds", "the", "client", "to", "the", "internal", "data", "structures", "and", "connects", "to", "it", ".", "If", "the", "method", "throws", "an", "exception", "then", "it", "is", "guaranteed", "it", "will", "also", "be", "removed", "from", "the", "internal", "structures", "before", "throwing", "the", "exception", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/namespace-notifier/src/java/org/apache/hadoop/hdfs/notifier/server/ServerCore.java#L355-L379
DiUS/pact-jvm
pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java
PactDslJsonArray.arrayEachLike
public static PactDslJsonArray arrayEachLike(Integer numberExamples, PactDslJsonRootValue value) { """ Root level array where each item must match the provided matcher @param numberExamples Number of examples to generate """ PactDslJsonArray parent = new PactDslJsonArray("", "", null, true); parent.setNumberExamples(numberExamples); parent.matchers.addRule("", parent.matchMin(0)); parent.putObject(value); return parent; }
java
public static PactDslJsonArray arrayEachLike(Integer numberExamples, PactDslJsonRootValue value) { PactDslJsonArray parent = new PactDslJsonArray("", "", null, true); parent.setNumberExamples(numberExamples); parent.matchers.addRule("", parent.matchMin(0)); parent.putObject(value); return parent; }
[ "public", "static", "PactDslJsonArray", "arrayEachLike", "(", "Integer", "numberExamples", ",", "PactDslJsonRootValue", "value", ")", "{", "PactDslJsonArray", "parent", "=", "new", "PactDslJsonArray", "(", "\"\"", ",", "\"\"", ",", "null", ",", "true", ")", ";", "parent", ".", "setNumberExamples", "(", "numberExamples", ")", ";", "parent", ".", "matchers", ".", "addRule", "(", "\"\"", ",", "parent", ".", "matchMin", "(", "0", ")", ")", ";", "parent", ".", "putObject", "(", "value", ")", ";", "return", "parent", ";", "}" ]
Root level array where each item must match the provided matcher @param numberExamples Number of examples to generate
[ "Root", "level", "array", "where", "each", "item", "must", "match", "the", "provided", "matcher" ]
train
https://github.com/DiUS/pact-jvm/blob/2f447e9dd4ac152a6a36b7fcf8962d07de9ef3ef/pact-jvm-consumer/src/main/java/au/com/dius/pact/consumer/dsl/PactDslJsonArray.java#L757-L763
alkacon/opencms-core
src-modules/org/opencms/workplace/administration/CmsAdminMenuGroup.java
CmsAdminMenuGroup.addMenuItem
public void addMenuItem(CmsAdminMenuItem item, float position) { """ Adds a menu item at the given position.<p> @param item the item @param position the position @see org.opencms.workplace.tools.CmsIdentifiableObjectContainer#addIdentifiableObject(String, Object, float) """ m_container.addIdentifiableObject(item.getId(), item, position); }
java
public void addMenuItem(CmsAdminMenuItem item, float position) { m_container.addIdentifiableObject(item.getId(), item, position); }
[ "public", "void", "addMenuItem", "(", "CmsAdminMenuItem", "item", ",", "float", "position", ")", "{", "m_container", ".", "addIdentifiableObject", "(", "item", ".", "getId", "(", ")", ",", "item", ",", "position", ")", ";", "}" ]
Adds a menu item at the given position.<p> @param item the item @param position the position @see org.opencms.workplace.tools.CmsIdentifiableObjectContainer#addIdentifiableObject(String, Object, float)
[ "Adds", "a", "menu", "item", "at", "the", "given", "position", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/administration/CmsAdminMenuGroup.java#L87-L90
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/disparity/impl/ImplDisparityScoreSadRect_S16.java
ImplDisparityScoreSadRect_S16.computeFirstRow
private void computeFirstRow(GrayS16 left, GrayS16 right ) { """ Initializes disparity calculation by finding the scores for the initial block of horizontal rows. """ // compute horizontal scores for first row block for( int row = 0; row < regionHeight; row++ ) { int scores[] = horizontalScore[row]; UtilDisparityScore.computeScoreRow(left, right, row, scores, minDisparity,maxDisparity,regionWidth,elementScore); } // compute score for the top possible row for( int i = 0; i < lengthHorizontal; i++ ) { int sum = 0; for( int row = 0; row < regionHeight; row++ ) { sum += horizontalScore[row][i]; } verticalScore[i] = sum; } // compute disparity computeDisparity.process(radiusY, verticalScore); }
java
private void computeFirstRow(GrayS16 left, GrayS16 right ) { // compute horizontal scores for first row block for( int row = 0; row < regionHeight; row++ ) { int scores[] = horizontalScore[row]; UtilDisparityScore.computeScoreRow(left, right, row, scores, minDisparity,maxDisparity,regionWidth,elementScore); } // compute score for the top possible row for( int i = 0; i < lengthHorizontal; i++ ) { int sum = 0; for( int row = 0; row < regionHeight; row++ ) { sum += horizontalScore[row][i]; } verticalScore[i] = sum; } // compute disparity computeDisparity.process(radiusY, verticalScore); }
[ "private", "void", "computeFirstRow", "(", "GrayS16", "left", ",", "GrayS16", "right", ")", "{", "// compute horizontal scores for first row block", "for", "(", "int", "row", "=", "0", ";", "row", "<", "regionHeight", ";", "row", "++", ")", "{", "int", "scores", "[", "]", "=", "horizontalScore", "[", "row", "]", ";", "UtilDisparityScore", ".", "computeScoreRow", "(", "left", ",", "right", ",", "row", ",", "scores", ",", "minDisparity", ",", "maxDisparity", ",", "regionWidth", ",", "elementScore", ")", ";", "}", "// compute score for the top possible row", "for", "(", "int", "i", "=", "0", ";", "i", "<", "lengthHorizontal", ";", "i", "++", ")", "{", "int", "sum", "=", "0", ";", "for", "(", "int", "row", "=", "0", ";", "row", "<", "regionHeight", ";", "row", "++", ")", "{", "sum", "+=", "horizontalScore", "[", "row", "]", "[", "i", "]", ";", "}", "verticalScore", "[", "i", "]", "=", "sum", ";", "}", "// compute disparity", "computeDisparity", ".", "process", "(", "radiusY", ",", "verticalScore", ")", ";", "}" ]
Initializes disparity calculation by finding the scores for the initial block of horizontal rows.
[ "Initializes", "disparity", "calculation", "by", "finding", "the", "scores", "for", "the", "initial", "block", "of", "horizontal", "rows", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/disparity/impl/ImplDisparityScoreSadRect_S16.java#L83-L104
cdapio/tigon
tigon-queue/src/main/java/co/cask/tigon/data/security/HBaseTokenUtils.java
HBaseTokenUtils.obtainToken
public static Credentials obtainToken(Configuration hConf, Credentials credentials) { """ Gets a HBase delegation token and stores it in the given Credentials. @return the same Credentials instance as the one given in parameter. """ if (!User.isHBaseSecurityEnabled(hConf)) { return credentials; } try { Class c = Class.forName("org.apache.hadoop.hbase.security.token.TokenUtil"); Method method = c.getMethod("obtainToken", Configuration.class); Token<? extends TokenIdentifier> token = castToken(method.invoke(null, hConf)); credentials.addToken(token.getService(), token); return credentials; } catch (Exception e) { LOG.error("Failed to get secure token for HBase.", e); throw Throwables.propagate(e); } }
java
public static Credentials obtainToken(Configuration hConf, Credentials credentials) { if (!User.isHBaseSecurityEnabled(hConf)) { return credentials; } try { Class c = Class.forName("org.apache.hadoop.hbase.security.token.TokenUtil"); Method method = c.getMethod("obtainToken", Configuration.class); Token<? extends TokenIdentifier> token = castToken(method.invoke(null, hConf)); credentials.addToken(token.getService(), token); return credentials; } catch (Exception e) { LOG.error("Failed to get secure token for HBase.", e); throw Throwables.propagate(e); } }
[ "public", "static", "Credentials", "obtainToken", "(", "Configuration", "hConf", ",", "Credentials", "credentials", ")", "{", "if", "(", "!", "User", ".", "isHBaseSecurityEnabled", "(", "hConf", ")", ")", "{", "return", "credentials", ";", "}", "try", "{", "Class", "c", "=", "Class", ".", "forName", "(", "\"org.apache.hadoop.hbase.security.token.TokenUtil\"", ")", ";", "Method", "method", "=", "c", ".", "getMethod", "(", "\"obtainToken\"", ",", "Configuration", ".", "class", ")", ";", "Token", "<", "?", "extends", "TokenIdentifier", ">", "token", "=", "castToken", "(", "method", ".", "invoke", "(", "null", ",", "hConf", ")", ")", ";", "credentials", ".", "addToken", "(", "token", ".", "getService", "(", ")", ",", "token", ")", ";", "return", "credentials", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "\"Failed to get secure token for HBase.\"", ",", "e", ")", ";", "throw", "Throwables", ".", "propagate", "(", "e", ")", ";", "}", "}" ]
Gets a HBase delegation token and stores it in the given Credentials. @return the same Credentials instance as the one given in parameter.
[ "Gets", "a", "HBase", "delegation", "token", "and", "stores", "it", "in", "the", "given", "Credentials", "." ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-queue/src/main/java/co/cask/tigon/data/security/HBaseTokenUtils.java#L42-L60
googleads/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/utils/v201902/DateTimes.java
DateTimes.toDateTime
public static DateTime toDateTime(String dateTime, String timeZoneId) { """ Converts a string in the form of {@code yyyy-MM-dd'T'HH:mm:ss} to an API date time in the time zone supplied. """ return dateTimesHelper.toDateTime(dateTime, timeZoneId); }
java
public static DateTime toDateTime(String dateTime, String timeZoneId) { return dateTimesHelper.toDateTime(dateTime, timeZoneId); }
[ "public", "static", "DateTime", "toDateTime", "(", "String", "dateTime", ",", "String", "timeZoneId", ")", "{", "return", "dateTimesHelper", ".", "toDateTime", "(", "dateTime", ",", "timeZoneId", ")", ";", "}" ]
Converts a string in the form of {@code yyyy-MM-dd'T'HH:mm:ss} to an API date time in the time zone supplied.
[ "Converts", "a", "string", "in", "the", "form", "of", "{" ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/utils/v201902/DateTimes.java#L52-L54
BlueBrain/bluima
modules/bluima_abbreviations/src/main/java/com/wcohen/ss/expt/SourcedMatchData.java
SourcedMatchData.addInstance
public void addInstance(String src,String id,String text) { """ Add a single instance, with given src and id, to the datafile """ Instance inst = new Instance(src,id,text); ArrayList list = (ArrayList)sourceLists.get(src); if (list==null) { list = new ArrayList(); sourceLists.put(src,list); sourceNames.add(src); } list.add(inst); }
java
public void addInstance(String src,String id,String text) { Instance inst = new Instance(src,id,text); ArrayList list = (ArrayList)sourceLists.get(src); if (list==null) { list = new ArrayList(); sourceLists.put(src,list); sourceNames.add(src); } list.add(inst); }
[ "public", "void", "addInstance", "(", "String", "src", ",", "String", "id", ",", "String", "text", ")", "{", "Instance", "inst", "=", "new", "Instance", "(", "src", ",", "id", ",", "text", ")", ";", "ArrayList", "list", "=", "(", "ArrayList", ")", "sourceLists", ".", "get", "(", "src", ")", ";", "if", "(", "list", "==", "null", ")", "{", "list", "=", "new", "ArrayList", "(", ")", ";", "sourceLists", ".", "put", "(", "src", ",", "list", ")", ";", "sourceNames", ".", "add", "(", "src", ")", ";", "}", "list", ".", "add", "(", "inst", ")", ";", "}" ]
Add a single instance, with given src and id, to the datafile
[ "Add", "a", "single", "instance", "with", "given", "src", "and", "id", "to", "the", "datafile" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_abbreviations/src/main/java/com/wcohen/ss/expt/SourcedMatchData.java#L68-L78
igniterealtime/REST-API-Client
src/main/java/org/igniterealtime/restclient/RestApiClient.java
RestApiClient.addOutcastGroup
public Response addOutcastGroup(String roomName, String groupName) { """ Adds the group outcast. @param roomName the room name @param groupName the groupName @return the response """ return restClient.post("chatrooms/" + roomName + "/outcasts/group/" + groupName, null, new HashMap<String, String>()); }
java
public Response addOutcastGroup(String roomName, String groupName) { return restClient.post("chatrooms/" + roomName + "/outcasts/group/" + groupName, null, new HashMap<String, String>()); }
[ "public", "Response", "addOutcastGroup", "(", "String", "roomName", ",", "String", "groupName", ")", "{", "return", "restClient", ".", "post", "(", "\"chatrooms/\"", "+", "roomName", "+", "\"/outcasts/group/\"", "+", "groupName", ",", "null", ",", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ")", ";", "}" ]
Adds the group outcast. @param roomName the room name @param groupName the groupName @return the response
[ "Adds", "the", "group", "outcast", "." ]
train
https://github.com/igniterealtime/REST-API-Client/blob/fd544dd770ec2ababa47fef51579522ddce09f05/src/main/java/org/igniterealtime/restclient/RestApiClient.java#L437-L439
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.handleRequestRedirect
private void handleRequestRedirect( final CrawlCandidate currentCrawlCandidate, final String redirectedUrl) { """ Creates a crawl request for the redirected URL, feeds it to the crawler and calls the appropriate event callback. @param currentCrawlCandidate the current crawl candidate @param redirectedUrl the URL of the redirected request """ CrawlRequestBuilder builder = new CrawlRequestBuilder(redirectedUrl) .setPriority(currentCrawlCandidate.getPriority()); currentCrawlCandidate.getMetadata().ifPresent(builder::setMetadata); CrawlRequest redirectedRequest = builder.build(); crawlFrontier.feedRequest(redirectedRequest, false); callbackManager.call(CrawlEvent.REQUEST_REDIRECT, new RequestRedirectEvent(currentCrawlCandidate, redirectedRequest)); }
java
private void handleRequestRedirect( final CrawlCandidate currentCrawlCandidate, final String redirectedUrl) { CrawlRequestBuilder builder = new CrawlRequestBuilder(redirectedUrl) .setPriority(currentCrawlCandidate.getPriority()); currentCrawlCandidate.getMetadata().ifPresent(builder::setMetadata); CrawlRequest redirectedRequest = builder.build(); crawlFrontier.feedRequest(redirectedRequest, false); callbackManager.call(CrawlEvent.REQUEST_REDIRECT, new RequestRedirectEvent(currentCrawlCandidate, redirectedRequest)); }
[ "private", "void", "handleRequestRedirect", "(", "final", "CrawlCandidate", "currentCrawlCandidate", ",", "final", "String", "redirectedUrl", ")", "{", "CrawlRequestBuilder", "builder", "=", "new", "CrawlRequestBuilder", "(", "redirectedUrl", ")", ".", "setPriority", "(", "currentCrawlCandidate", ".", "getPriority", "(", ")", ")", ";", "currentCrawlCandidate", ".", "getMetadata", "(", ")", ".", "ifPresent", "(", "builder", "::", "setMetadata", ")", ";", "CrawlRequest", "redirectedRequest", "=", "builder", ".", "build", "(", ")", ";", "crawlFrontier", ".", "feedRequest", "(", "redirectedRequest", ",", "false", ")", ";", "callbackManager", ".", "call", "(", "CrawlEvent", ".", "REQUEST_REDIRECT", ",", "new", "RequestRedirectEvent", "(", "currentCrawlCandidate", ",", "redirectedRequest", ")", ")", ";", "}" ]
Creates a crawl request for the redirected URL, feeds it to the crawler and calls the appropriate event callback. @param currentCrawlCandidate the current crawl candidate @param redirectedUrl the URL of the redirected request
[ "Creates", "a", "crawl", "request", "for", "the", "redirected", "URL", "feeds", "it", "to", "the", "crawler", "and", "calls", "the", "appropriate", "event", "callback", "." ]
train
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L457-L468
xmlunit/xmlunit
xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/XMLUnit.java
XMLUnit.compareXML
public static Diff compareXML(InputSource control, InputSource test) throws SAXException, IOException { """ Compare XML documents provided by two InputSource classes @param control Control document @param test Document to test @return Diff object describing differences in documents @throws SAXException @throws IOException """ return new Diff(control, test); }
java
public static Diff compareXML(InputSource control, InputSource test) throws SAXException, IOException { return new Diff(control, test); }
[ "public", "static", "Diff", "compareXML", "(", "InputSource", "control", ",", "InputSource", "test", ")", "throws", "SAXException", ",", "IOException", "{", "return", "new", "Diff", "(", "control", ",", "test", ")", ";", "}" ]
Compare XML documents provided by two InputSource classes @param control Control document @param test Document to test @return Diff object describing differences in documents @throws SAXException @throws IOException
[ "Compare", "XML", "documents", "provided", "by", "two", "InputSource", "classes" ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/XMLUnit.java#L567-L570
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.addCompositeEntityChildAsync
public Observable<UUID> addCompositeEntityChildAsync(UUID appId, String versionId, UUID cEntityId, AddCompositeEntityChildOptionalParameter addCompositeEntityChildOptionalParameter) { """ Creates a single child in an existing composite entity model. @param appId The application ID. @param versionId The version ID. @param cEntityId The composite entity extractor ID. @param addCompositeEntityChildOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the UUID object """ return addCompositeEntityChildWithServiceResponseAsync(appId, versionId, cEntityId, addCompositeEntityChildOptionalParameter).map(new Func1<ServiceResponse<UUID>, UUID>() { @Override public UUID call(ServiceResponse<UUID> response) { return response.body(); } }); }
java
public Observable<UUID> addCompositeEntityChildAsync(UUID appId, String versionId, UUID cEntityId, AddCompositeEntityChildOptionalParameter addCompositeEntityChildOptionalParameter) { return addCompositeEntityChildWithServiceResponseAsync(appId, versionId, cEntityId, addCompositeEntityChildOptionalParameter).map(new Func1<ServiceResponse<UUID>, UUID>() { @Override public UUID call(ServiceResponse<UUID> response) { return response.body(); } }); }
[ "public", "Observable", "<", "UUID", ">", "addCompositeEntityChildAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "cEntityId", ",", "AddCompositeEntityChildOptionalParameter", "addCompositeEntityChildOptionalParameter", ")", "{", "return", "addCompositeEntityChildWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "cEntityId", ",", "addCompositeEntityChildOptionalParameter", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "UUID", ">", ",", "UUID", ">", "(", ")", "{", "@", "Override", "public", "UUID", "call", "(", "ServiceResponse", "<", "UUID", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates a single child in an existing composite entity model. @param appId The application ID. @param versionId The version ID. @param cEntityId The composite entity extractor ID. @param addCompositeEntityChildOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the UUID object
[ "Creates", "a", "single", "child", "in", "an", "existing", "composite", "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#L6863-L6870
redlink-gmbh/redlink-java-sdk
src/main/java/io/redlink/sdk/impl/analysis/model/EnhancementsParserFactory.java
EnhancementsParserFactory.createDefaultParser
public static final EnhancementsParser createDefaultParser(HttpResponse response) throws EnhancementParserException, IOException { """ Create an {@link RDFStructureParser} as default {@link EnhancementsParser}. The method will try to parse an Enhancement Structure in RDF format, ignoring the {@link HttpResponse} {@link MediaType}. Users need to ensure that the {@link HttpResponse} contains the Enhancement Structure in that format @param response @return @throws EnhancementParserException """ ParserConfig config = new ParserConfig(); // Prevent malformed datetime values // TODO review - added to prevent errors when parsing invalid dates config.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, false); String uri = response.getFirstHeader(REDLINK).getValue(); if (uri == null || uri.isEmpty()) { uri = "urn:uuid-" + UUID.randomUUID().toString(); } Model result = new TreeModel(); //Prepare to read the response String charsetStr = ContentType.getOrDefault(response.getEntity()).getCharset().displayName(); Charset charset; if(charsetStr == null){ charset = UTF8; } else { try { charset = Charset.forName(charsetStr); }catch (IllegalCharsetNameException | UnsupportedCharsetException e){ log.warn("Unable to use charset '"+ charsetStr +"'. Will fallback to UTF-8", e); charset = UTF8; } } Reader reader = new InputStreamReader(response.getEntity().getContent(), charset); try { ValueFactory vf = new MemValueFactory(); RDFFormat format = RDFFormat.forMIMEType(ContentType.getOrDefault(response.getEntity()).getMimeType()); RDFParser parser = Rio.createParser(format, vf); parser.setParserConfig(config); parser.setRDFHandler(new ContextStatementCollector(result, vf)); parser.parse(reader, uri); } catch (RDFHandlerException | RDFParseException e) { throw new EnhancementParserException("Error Parsing Analysis results" ,e); } catch (IOException e) { throw new EnhancementParserException("Unable to read Analysis response" ,e); } finally { IOUtils.closeQuietly(reader); } return new RDFStructureParser(result); }
java
public static final EnhancementsParser createDefaultParser(HttpResponse response) throws EnhancementParserException, IOException { ParserConfig config = new ParserConfig(); // Prevent malformed datetime values // TODO review - added to prevent errors when parsing invalid dates config.set(BasicParserSettings.VERIFY_DATATYPE_VALUES, false); String uri = response.getFirstHeader(REDLINK).getValue(); if (uri == null || uri.isEmpty()) { uri = "urn:uuid-" + UUID.randomUUID().toString(); } Model result = new TreeModel(); //Prepare to read the response String charsetStr = ContentType.getOrDefault(response.getEntity()).getCharset().displayName(); Charset charset; if(charsetStr == null){ charset = UTF8; } else { try { charset = Charset.forName(charsetStr); }catch (IllegalCharsetNameException | UnsupportedCharsetException e){ log.warn("Unable to use charset '"+ charsetStr +"'. Will fallback to UTF-8", e); charset = UTF8; } } Reader reader = new InputStreamReader(response.getEntity().getContent(), charset); try { ValueFactory vf = new MemValueFactory(); RDFFormat format = RDFFormat.forMIMEType(ContentType.getOrDefault(response.getEntity()).getMimeType()); RDFParser parser = Rio.createParser(format, vf); parser.setParserConfig(config); parser.setRDFHandler(new ContextStatementCollector(result, vf)); parser.parse(reader, uri); } catch (RDFHandlerException | RDFParseException e) { throw new EnhancementParserException("Error Parsing Analysis results" ,e); } catch (IOException e) { throw new EnhancementParserException("Unable to read Analysis response" ,e); } finally { IOUtils.closeQuietly(reader); } return new RDFStructureParser(result); }
[ "public", "static", "final", "EnhancementsParser", "createDefaultParser", "(", "HttpResponse", "response", ")", "throws", "EnhancementParserException", ",", "IOException", "{", "ParserConfig", "config", "=", "new", "ParserConfig", "(", ")", ";", "// Prevent malformed datetime values", "// TODO review - added to prevent errors when parsing invalid dates", "config", ".", "set", "(", "BasicParserSettings", ".", "VERIFY_DATATYPE_VALUES", ",", "false", ")", ";", "String", "uri", "=", "response", ".", "getFirstHeader", "(", "REDLINK", ")", ".", "getValue", "(", ")", ";", "if", "(", "uri", "==", "null", "||", "uri", ".", "isEmpty", "(", ")", ")", "{", "uri", "=", "\"urn:uuid-\"", "+", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ";", "}", "Model", "result", "=", "new", "TreeModel", "(", ")", ";", "//Prepare to read the response", "String", "charsetStr", "=", "ContentType", ".", "getOrDefault", "(", "response", ".", "getEntity", "(", ")", ")", ".", "getCharset", "(", ")", ".", "displayName", "(", ")", ";", "Charset", "charset", ";", "if", "(", "charsetStr", "==", "null", ")", "{", "charset", "=", "UTF8", ";", "}", "else", "{", "try", "{", "charset", "=", "Charset", ".", "forName", "(", "charsetStr", ")", ";", "}", "catch", "(", "IllegalCharsetNameException", "|", "UnsupportedCharsetException", "e", ")", "{", "log", ".", "warn", "(", "\"Unable to use charset '\"", "+", "charsetStr", "+", "\"'. Will fallback to UTF-8\"", ",", "e", ")", ";", "charset", "=", "UTF8", ";", "}", "}", "Reader", "reader", "=", "new", "InputStreamReader", "(", "response", ".", "getEntity", "(", ")", ".", "getContent", "(", ")", ",", "charset", ")", ";", "try", "{", "ValueFactory", "vf", "=", "new", "MemValueFactory", "(", ")", ";", "RDFFormat", "format", "=", "RDFFormat", ".", "forMIMEType", "(", "ContentType", ".", "getOrDefault", "(", "response", ".", "getEntity", "(", ")", ")", ".", "getMimeType", "(", ")", ")", ";", "RDFParser", "parser", "=", "Rio", ".", "createParser", "(", "format", ",", "vf", ")", ";", "parser", ".", "setParserConfig", "(", "config", ")", ";", "parser", ".", "setRDFHandler", "(", "new", "ContextStatementCollector", "(", "result", ",", "vf", ")", ")", ";", "parser", ".", "parse", "(", "reader", ",", "uri", ")", ";", "}", "catch", "(", "RDFHandlerException", "|", "RDFParseException", "e", ")", "{", "throw", "new", "EnhancementParserException", "(", "\"Error Parsing Analysis results\"", ",", "e", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "EnhancementParserException", "(", "\"Unable to read Analysis response\"", ",", "e", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "reader", ")", ";", "}", "return", "new", "RDFStructureParser", "(", "result", ")", ";", "}" ]
Create an {@link RDFStructureParser} as default {@link EnhancementsParser}. The method will try to parse an Enhancement Structure in RDF format, ignoring the {@link HttpResponse} {@link MediaType}. Users need to ensure that the {@link HttpResponse} contains the Enhancement Structure in that format @param response @return @throws EnhancementParserException
[ "Create", "an", "{", "@link", "RDFStructureParser", "}", "as", "default", "{", "@link", "EnhancementsParser", "}", ".", "The", "method", "will", "try", "to", "parse", "an", "Enhancement", "Structure", "in", "RDF", "format", "ignoring", "the", "{", "@link", "HttpResponse", "}", "{", "@link", "MediaType", "}", ".", "Users", "need", "to", "ensure", "that", "the", "{", "@link", "HttpResponse", "}", "contains", "the", "Enhancement", "Structure", "in", "that", "format" ]
train
https://github.com/redlink-gmbh/redlink-java-sdk/blob/c412ff11bd80da52ade09f2483ab29cdbff5a28a/src/main/java/io/redlink/sdk/impl/analysis/model/EnhancementsParserFactory.java#L63-L102