repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
infinispan/infinispan
server/hotrod/src/main/java/org/infinispan/server/hotrod/LifecycleCallbacks.java
LifecycleCallbacks.registerServerTransactionTable
private void registerServerTransactionTable(ComponentRegistry componentRegistry, String cacheName) { //skip for global tx table and non-transactional cache if (GLOBAL_TX_TABLE_CACHE_NAME.equals(cacheName) || !componentRegistry.getComponent(Configuration.class).transaction().transactionMode().isTransactional()) { return; } EmbeddedCacheManager cacheManager = componentRegistry.getGlobalComponentRegistry() .getComponent(EmbeddedCacheManager.class); createGlobalTxTable(cacheManager); // TODO We need a way for a module to install a factory before the default implementation is instantiated BasicComponentRegistry basicComponentRegistry = componentRegistry.getComponent(BasicComponentRegistry.class); basicComponentRegistry.replaceComponent(PerCacheTxTable.class.getName(), new PerCacheTxTable(cacheManager.getAddress()), true); basicComponentRegistry.replaceComponent(TransactionOriginatorChecker.class.getName(), new ServerTransactionOriginatorChecker(), true); basicComponentRegistry.rewire(); }
java
private void registerServerTransactionTable(ComponentRegistry componentRegistry, String cacheName) { //skip for global tx table and non-transactional cache if (GLOBAL_TX_TABLE_CACHE_NAME.equals(cacheName) || !componentRegistry.getComponent(Configuration.class).transaction().transactionMode().isTransactional()) { return; } EmbeddedCacheManager cacheManager = componentRegistry.getGlobalComponentRegistry() .getComponent(EmbeddedCacheManager.class); createGlobalTxTable(cacheManager); // TODO We need a way for a module to install a factory before the default implementation is instantiated BasicComponentRegistry basicComponentRegistry = componentRegistry.getComponent(BasicComponentRegistry.class); basicComponentRegistry.replaceComponent(PerCacheTxTable.class.getName(), new PerCacheTxTable(cacheManager.getAddress()), true); basicComponentRegistry.replaceComponent(TransactionOriginatorChecker.class.getName(), new ServerTransactionOriginatorChecker(), true); basicComponentRegistry.rewire(); }
[ "private", "void", "registerServerTransactionTable", "(", "ComponentRegistry", "componentRegistry", ",", "String", "cacheName", ")", "{", "//skip for global tx table and non-transactional cache", "if", "(", "GLOBAL_TX_TABLE_CACHE_NAME", ".", "equals", "(", "cacheName", ")", "...
Registers the {@link PerCacheTxTable} to a transactional cache.
[ "Registers", "the", "{" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/hotrod/src/main/java/org/infinispan/server/hotrod/LifecycleCallbacks.java#L103-L117
kiegroup/jbpmmigration
src/main/java/org/jbpm/migration/Validator.java
Validator.validateDefinition
static boolean validateDefinition(final Document def, final ProcessLanguage language) { return XmlUtils.validate(new DOMSource(def), language.getSchemaSources()); }
java
static boolean validateDefinition(final Document def, final ProcessLanguage language) { return XmlUtils.validate(new DOMSource(def), language.getSchemaSources()); }
[ "static", "boolean", "validateDefinition", "(", "final", "Document", "def", ",", "final", "ProcessLanguage", "language", ")", "{", "return", "XmlUtils", ".", "validate", "(", "new", "DOMSource", "(", "def", ")", ",", "language", ".", "getSchemaSources", "(", "...
Validate a given jPDL process definition against the applicable definition language's schema. @param def The process definition, in {@link Document} format. @param language The process definition language for which the given definition is to be validated. @return Whether the validation was successful.
[ "Validate", "a", "given", "jPDL", "process", "definition", "against", "the", "applicable", "definition", "language", "s", "schema", "." ]
train
https://github.com/kiegroup/jbpmmigration/blob/5e133e2824aa38f316a2eb061123313a7276aba0/src/main/java/org/jbpm/migration/Validator.java#L86-L88
perwendel/spark
src/main/java/spark/Routable.java
Routable.createRouteImpl
private RouteImpl createRouteImpl(String path, String acceptType, Route route) { if (defaultResponseTransformer != null) { return ResponseTransformerRouteImpl.create(path, acceptType, route, defaultResponseTransformer); } return RouteImpl.create(path, acceptType, route); }
java
private RouteImpl createRouteImpl(String path, String acceptType, Route route) { if (defaultResponseTransformer != null) { return ResponseTransformerRouteImpl.create(path, acceptType, route, defaultResponseTransformer); } return RouteImpl.create(path, acceptType, route); }
[ "private", "RouteImpl", "createRouteImpl", "(", "String", "path", ",", "String", "acceptType", ",", "Route", "route", ")", "{", "if", "(", "defaultResponseTransformer", "!=", "null", ")", "{", "return", "ResponseTransformerRouteImpl", ".", "create", "(", "path", ...
Create route implementation or use default response transformer @param path the path @param acceptType the accept type @param route the route @return ResponseTransformerRouteImpl or RouteImpl
[ "Create", "route", "implementation", "or", "use", "default", "response", "transformer" ]
train
https://github.com/perwendel/spark/blob/080fb1f9d6e580f6742e9589044c7420d3157b8b/src/main/java/spark/Routable.java#L806-L811
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.setStorageAccount
public StorageBundle setStorageAccount(String vaultBaseUrl, String storageAccountName, String resourceId, String activeKeyName, boolean autoRegenerateKey) { return setStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName, resourceId, activeKeyName, autoRegenerateKey).toBlocking().single().body(); }
java
public StorageBundle setStorageAccount(String vaultBaseUrl, String storageAccountName, String resourceId, String activeKeyName, boolean autoRegenerateKey) { return setStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName, resourceId, activeKeyName, autoRegenerateKey).toBlocking().single().body(); }
[ "public", "StorageBundle", "setStorageAccount", "(", "String", "vaultBaseUrl", ",", "String", "storageAccountName", ",", "String", "resourceId", ",", "String", "activeKeyName", ",", "boolean", "autoRegenerateKey", ")", "{", "return", "setStorageAccountWithServiceResponseAsy...
Creates or updates a new storage account. This operation requires the storage/set permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param storageAccountName The name of the storage account. @param resourceId Storage account resource id. @param activeKeyName Current active storage account key name. @param autoRegenerateKey whether keyvault should manage the storage account for the user. @throws IllegalArgumentException thrown if parameters fail the validation @throws KeyVaultErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the StorageBundle object if successful.
[ "Creates", "or", "updates", "a", "new", "storage", "account", ".", "This", "operation", "requires", "the", "storage", "/", "set", "permission", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L9868-L9870
jMetal/jMetal
jmetal-core/src/main/java/org/uma/jmetal/qualityindicator/impl/InvertedGenerationalDistancePlus.java
InvertedGenerationalDistancePlus.invertedGenerationalDistancePlus
public double invertedGenerationalDistancePlus(Front front, Front referenceFront) { double sum = 0.0; for (int i = 0 ; i < referenceFront.getNumberOfPoints(); i++) { sum += FrontUtils.distanceToClosestPoint(referenceFront.getPoint(i), front, new DominanceDistance()); } // STEP 4. Divide the sum by the maximum number of points of the reference Pareto front return sum / referenceFront.getNumberOfPoints(); }
java
public double invertedGenerationalDistancePlus(Front front, Front referenceFront) { double sum = 0.0; for (int i = 0 ; i < referenceFront.getNumberOfPoints(); i++) { sum += FrontUtils.distanceToClosestPoint(referenceFront.getPoint(i), front, new DominanceDistance()); } // STEP 4. Divide the sum by the maximum number of points of the reference Pareto front return sum / referenceFront.getNumberOfPoints(); }
[ "public", "double", "invertedGenerationalDistancePlus", "(", "Front", "front", ",", "Front", "referenceFront", ")", "{", "double", "sum", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "referenceFront", ".", "getNumberOfPoints", "(", ")", ...
Returns the inverted generational distance plus value for a given front @param front The front @param referenceFront The reference pareto front
[ "Returns", "the", "inverted", "generational", "distance", "plus", "value", "for", "a", "given", "front" ]
train
https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-core/src/main/java/org/uma/jmetal/qualityindicator/impl/InvertedGenerationalDistancePlus.java#L67-L77
JoeKerouac/utils
src/main/java/com/joe/utils/reflect/asm/AsmInvokeDistributeFactory.java
AsmInvokeDistributeFactory.buildByteCode
public byte[] buildByteCode(Class<?> parentClass, String className) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(version, // Java version ACC_PUBLIC, // public class convert(className), // package and name null, // signature (null means not generic) convert(parentClass), // superclass new String[] { convert(InvokeDistribute.class) }); // 声明保存实际Target的字段 cw.visitField(ACC_PRIVATE + ACC_FINAL, TARGET_FIELD_NAME, getByteCodeType(parentClass), null, null).visitEnd(); /* 为类构建默认构造器(编译器会自动生成,但是此处要手动生成bytecode就只能手动生成无参构造器了) */ generateDefaultConstructor(cw, parentClass, className); // 构建分发方法 buildMethod(cw, className, parentClass); // buildMethod(cw); // finish the class definition cw.visitEnd(); return cw.toByteArray(); }
java
public byte[] buildByteCode(Class<?> parentClass, String className) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(version, // Java version ACC_PUBLIC, // public class convert(className), // package and name null, // signature (null means not generic) convert(parentClass), // superclass new String[] { convert(InvokeDistribute.class) }); // 声明保存实际Target的字段 cw.visitField(ACC_PRIVATE + ACC_FINAL, TARGET_FIELD_NAME, getByteCodeType(parentClass), null, null).visitEnd(); /* 为类构建默认构造器(编译器会自动生成,但是此处要手动生成bytecode就只能手动生成无参构造器了) */ generateDefaultConstructor(cw, parentClass, className); // 构建分发方法 buildMethod(cw, className, parentClass); // buildMethod(cw); // finish the class definition cw.visitEnd(); return cw.toByteArray(); }
[ "public", "byte", "[", "]", "buildByteCode", "(", "Class", "<", "?", ">", "parentClass", ",", "String", "className", ")", "{", "ClassWriter", "cw", "=", "new", "ClassWriter", "(", "ClassWriter", ".", "COMPUTE_MAXS", ")", ";", "cw", ".", "visit", "(", "ve...
构建byte code @param parentClass 父类 @param className 生成的class名 @return 生成的class的byte code数据
[ "构建byte", "code" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/reflect/asm/AsmInvokeDistributeFactory.java#L127-L152
GerdHolz/TOVAL
src/de/invation/code/toval/validate/Validate.java
Validate.isFalse
public static void isFalse(Boolean expression, String constraint) { if(!validation) return; notNull(expression); notNull(constraint); if(!expression) throw new ParameterException(ErrorCode.CONSTRAINT, "Parameter must not fulfill constraint \""+constraint+"\""); }
java
public static void isFalse(Boolean expression, String constraint) { if(!validation) return; notNull(expression); notNull(constraint); if(!expression) throw new ParameterException(ErrorCode.CONSTRAINT, "Parameter must not fulfill constraint \""+constraint+"\""); }
[ "public", "static", "void", "isFalse", "(", "Boolean", "expression", ",", "String", "constraint", ")", "{", "if", "(", "!", "validation", ")", "return", ";", "notNull", "(", "expression", ")", ";", "notNull", "(", "constraint", ")", ";", "if", "(", "!", ...
Checks if the given boolean expression evaluates to <code>false</code>. @param expression The expression to evaluate. @param constraint Textual description of the expression to include in the exception in case the validation fails. @throws ParameterException if the given expression does not evaluate to <code>false</code>.
[ "Checks", "if", "the", "given", "boolean", "expression", "evaluates", "to", "<code", ">", "false<", "/", "code", ">", "." ]
train
https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/validate/Validate.java#L179-L185
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/Assert.java
Assert.isInstanceOf
public static void isInstanceOf(Object obj, Class<?> type, RuntimeException cause) { if (isNotInstanceOf(obj, type)) { throw cause; } }
java
public static void isInstanceOf(Object obj, Class<?> type, RuntimeException cause) { if (isNotInstanceOf(obj, type)) { throw cause; } }
[ "public", "static", "void", "isInstanceOf", "(", "Object", "obj", ",", "Class", "<", "?", ">", "type", ",", "RuntimeException", "cause", ")", "{", "if", "(", "isNotInstanceOf", "(", "obj", ",", "type", ")", ")", "{", "throw", "cause", ";", "}", "}" ]
Asserts that the given {@link Object} is an instance of the specified {@link Class type}. The assertion holds if and only if the {@link Object} is not {@literal null} and is an instance of the specified {@link Class type}. This assertion functions exactly the same as the Java {@literal instanceof} operator. @param obj {@link Object} evaluated as an instance of the {@link Class type}. @param type {@link Class type} used to evaluate the {@link Object} in the {@literal instanceof} operator. @param cause {@link RuntimeException} thrown if the assertion fails. @throws java.lang.RuntimeException if the {@link Object} is not an instance of {@link Class type}. @see java.lang.Class#isInstance(Object)
[ "Asserts", "that", "the", "given", "{", "@link", "Object", "}", "is", "an", "instance", "of", "the", "specified", "{", "@link", "Class", "type", "}", "." ]
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/Assert.java#L757-L761
facebookarchive/hadoop-20
src/contrib/capacity-scheduler/src/java/org/apache/hadoop/mapred/CapacitySchedulerConf.java
CapacitySchedulerConf.setMaxCapacity
public void setMaxCapacity(String queue,float maxCapacity) { rmConf.setFloat( toFullPropertyName(queue, MAX_CAPACITY_PROPERTY), maxCapacity); }
java
public void setMaxCapacity(String queue,float maxCapacity) { rmConf.setFloat( toFullPropertyName(queue, MAX_CAPACITY_PROPERTY), maxCapacity); }
[ "public", "void", "setMaxCapacity", "(", "String", "queue", ",", "float", "maxCapacity", ")", "{", "rmConf", ".", "setFloat", "(", "toFullPropertyName", "(", "queue", ",", "MAX_CAPACITY_PROPERTY", ")", ",", "maxCapacity", ")", ";", "}" ]
Sets the maxCapacity of the given queue. @param queue name of the queue @param maxCapacity percent of the cluster for the queue.
[ "Sets", "the", "maxCapacity", "of", "the", "given", "queue", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/capacity-scheduler/src/java/org/apache/hadoop/mapred/CapacitySchedulerConf.java#L228-L231
krummas/DrizzleJDBC
src/main/java/org/drizzle/jdbc/CommonDatabaseMetaData.java
CommonDatabaseMetaData.getSuperTypes
public ResultSet getSuperTypes(final String catalog, final String schemaPattern, final String typeNamePattern) throws SQLException { log.info("getting empty result set, get super types"); return getEmptyResultSet(); }
java
public ResultSet getSuperTypes(final String catalog, final String schemaPattern, final String typeNamePattern) throws SQLException { log.info("getting empty result set, get super types"); return getEmptyResultSet(); }
[ "public", "ResultSet", "getSuperTypes", "(", "final", "String", "catalog", ",", "final", "String", "schemaPattern", ",", "final", "String", "typeNamePattern", ")", "throws", "SQLException", "{", "log", ".", "info", "(", "\"getting empty result set, get super types\"", ...
Retrieves a description of the user-defined type (UDT) hierarchies defined in a particular schema in this database. Only the immediate super type/ sub type relationship is modeled. <p/> Only supertype information for UDTs matching the catalog, schema, and type name is returned. The type name parameter may be a fully-qualified name. When the UDT name supplied is a fully-qualified name, the catalog and schemaPattern parameters are ignored. <p/> If a UDT does not have a direct super type, it is not listed here. A row of the <code>ResultSet</code> object returned by this method describes the designated UDT and a direct supertype. A row has the following columns: <OL> <LI><B>TYPE_CAT</B> String => the UDT's catalog (may be <code>null</code>) <LI><B>TYPE_SCHEM</B> String => UDT's schema (may be <code>null</code>) <LI><B>TYPE_NAME</B> String => type name of the UDT <LI><B>SUPERTYPE_CAT</B> String => the direct super type's catalog (may be <code>null</code>) <LI><B>SUPERTYPE_SCHEM</B> String => the direct super type's schema (may be <code>null</code>) <LI><B>SUPERTYPE_NAME</B> String => the direct super type's name </OL> <p/> <P><B>Note:</B> If the driver does not support type hierarchies, an empty result set is returned. @param catalog a catalog name; "" retrieves those without a catalog; <code>null</code> means drop catalog name from the selection criteria @param schemaPattern a schema name pattern; "" retrieves those without a schema @param typeNamePattern a UDT name pattern; may be a fully-qualified name @return a <code>ResultSet</code> object in which a row gives information about the designated UDT @throws java.sql.SQLException if a database access error occurs @see #getSearchStringEscape @since 1.4
[ "Retrieves", "a", "description", "of", "the", "user", "-", "defined", "type", "(", "UDT", ")", "hierarchies", "defined", "in", "a", "particular", "schema", "in", "this", "database", ".", "Only", "the", "immediate", "super", "type", "/", "sub", "type", "rel...
train
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/CommonDatabaseMetaData.java#L2299-L2302
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/io/file/FileHelper.java
FileHelper.getDirectoryContent
@Nonnull @ReturnsMutableCopy public static ICommonsList <File> getDirectoryContent (@Nonnull final File aDirectory) { ValueEnforcer.notNull (aDirectory, "Directory"); return _getDirectoryContent (aDirectory, aDirectory.listFiles ()); }
java
@Nonnull @ReturnsMutableCopy public static ICommonsList <File> getDirectoryContent (@Nonnull final File aDirectory) { ValueEnforcer.notNull (aDirectory, "Directory"); return _getDirectoryContent (aDirectory, aDirectory.listFiles ()); }
[ "@", "Nonnull", "@", "ReturnsMutableCopy", "public", "static", "ICommonsList", "<", "File", ">", "getDirectoryContent", "(", "@", "Nonnull", "final", "File", "aDirectory", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aDirectory", ",", "\"Directory\"", ")", "...
This is a replacement for <code>File.listFiles()</code> doing some additional checks on permissions. The order of the returned files is defined by the underlying {@link File#listFiles()} method. @param aDirectory The directory to be listed. May not be <code>null</code>. @return Never <code>null</code>.
[ "This", "is", "a", "replacement", "for", "<code", ">", "File", ".", "listFiles", "()", "<", "/", "code", ">", "doing", "some", "additional", "checks", "on", "permissions", ".", "The", "order", "of", "the", "returned", "files", "is", "defined", "by", "the...
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/io/file/FileHelper.java#L690-L697
aol/cyclops
cyclops/src/main/java/cyclops/companion/Streams.java
Streams.foldLeftMapToType
public final static <R,T> R foldLeftMapToType(final Stream<T> stream, final Reducer<R,T> reducer) { return reducer.foldMap(stream); }
java
public final static <R,T> R foldLeftMapToType(final Stream<T> stream, final Reducer<R,T> reducer) { return reducer.foldMap(stream); }
[ "public", "final", "static", "<", "R", ",", "T", ">", "R", "foldLeftMapToType", "(", "final", "Stream", "<", "T", ">", "stream", ",", "final", "Reducer", "<", "R", ",", "T", ">", "reducer", ")", "{", "return", "reducer", ".", "foldMap", "(", "stream"...
Attempt to transform this Monad to the same type as the supplied Monoid (using mapToType on the monoid interface) Then use Monoid to reduce values @param reducer Monoid to reduce values @return Reduce result
[ "Attempt", "to", "transform", "this", "Monad", "to", "the", "same", "type", "as", "the", "supplied", "Monoid", "(", "using", "mapToType", "on", "the", "monoid", "interface", ")", "Then", "use", "Monoid", "to", "reduce", "values" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/cyclops/companion/Streams.java#L1973-L1975
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java
GeoJsonToAssembler.fromTransferObject
public Polygon fromTransferObject(PolygonTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); return createPolygon(input.getCoordinates(), crsId); }
java
public Polygon fromTransferObject(PolygonTo input, CrsId crsId) { if (input == null) { return null; } crsId = getCrsId(input, crsId); isValid(input); return createPolygon(input.getCoordinates(), crsId); }
[ "public", "Polygon", "fromTransferObject", "(", "PolygonTo", "input", ",", "CrsId", "crsId", ")", "{", "if", "(", "input", "==", "null", ")", "{", "return", "null", ";", "}", "crsId", "=", "getCrsId", "(", "input", ",", "crsId", ")", ";", "isValid", "(...
Creates a polygon object starting from a transfer object. @param input the polygon transfer object @param crsId the crs id to use (ignores the crs of the input). If null, uses the crs of the input. @return the corresponding geometry @throws IllegalArgumentException If the geometry could not be constructed due to an invalid transfer object
[ "Creates", "a", "polygon", "object", "starting", "from", "a", "transfer", "object", "." ]
train
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/to/GeoJsonToAssembler.java#L242-L249
RestComm/Restcomm-Connect
restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/number/NumberSelectorServiceImpl.java
NumberSelectorServiceImpl.findByRegex
private NumberSelectionResult findByRegex(List<String> numberQueries, Sid sourceOrganizationSid, Sid destOrg) { NumberSelectionResult numberFound = new NumberSelectionResult(null, false, null); IncomingPhoneNumberFilter.Builder filterBuilder = IncomingPhoneNumberFilter.Builder.builder(); filterBuilder.byOrgSid(destOrg.toString()); filterBuilder.byPureSIP(Boolean.TRUE); List<IncomingPhoneNumber> regexList = numbersDao.getIncomingPhoneNumbersRegex(filterBuilder.build()); if (logger.isDebugEnabled()) { logger.debug(String.format("Found %d Regex IncomingPhone numbers.", regexList.size())); } //order by regex length Set<IncomingPhoneNumber> regexSet = new TreeSet<IncomingPhoneNumber>(new NumberLengthComparator()); regexSet.addAll(regexList); if (regexList != null && regexList.size() > 0) { NumberSelectionResult matchingRegex = findFirstMatchingRegex(numberQueries, regexSet); if (matchingRegex.getNumber() != null) { numberFound = matchingRegex; } } return numberFound; }
java
private NumberSelectionResult findByRegex(List<String> numberQueries, Sid sourceOrganizationSid, Sid destOrg) { NumberSelectionResult numberFound = new NumberSelectionResult(null, false, null); IncomingPhoneNumberFilter.Builder filterBuilder = IncomingPhoneNumberFilter.Builder.builder(); filterBuilder.byOrgSid(destOrg.toString()); filterBuilder.byPureSIP(Boolean.TRUE); List<IncomingPhoneNumber> regexList = numbersDao.getIncomingPhoneNumbersRegex(filterBuilder.build()); if (logger.isDebugEnabled()) { logger.debug(String.format("Found %d Regex IncomingPhone numbers.", regexList.size())); } //order by regex length Set<IncomingPhoneNumber> regexSet = new TreeSet<IncomingPhoneNumber>(new NumberLengthComparator()); regexSet.addAll(regexList); if (regexList != null && regexList.size() > 0) { NumberSelectionResult matchingRegex = findFirstMatchingRegex(numberQueries, regexSet); if (matchingRegex.getNumber() != null) { numberFound = matchingRegex; } } return numberFound; }
[ "private", "NumberSelectionResult", "findByRegex", "(", "List", "<", "String", ">", "numberQueries", ",", "Sid", "sourceOrganizationSid", ",", "Sid", "destOrg", ")", "{", "NumberSelectionResult", "numberFound", "=", "new", "NumberSelectionResult", "(", "null", ",", ...
This will take the regexes available in given organization, and evalute them agsint the given list of numbers, returning the first match. The list of regexes will be ordered by length to ensure the longest regexes matching any number in the list is returned first. In this case, organization details are required. @param numberQueries @param sourceOrganizationSid @param destOrg @return the longest regex matching any number in the list, null if no match
[ "This", "will", "take", "the", "regexes", "available", "in", "given", "organization", "and", "evalute", "them", "agsint", "the", "given", "list", "of", "numbers", "returning", "the", "first", "match", "." ]
train
https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/number/NumberSelectorServiceImpl.java#L361-L383
apache/fluo
modules/api/src/main/java/org/apache/fluo/api/config/FluoConfiguration.java
FluoConfiguration.getAccumuloPassword
public String getAccumuloPassword() { if (containsKey(ACCUMULO_PASSWORD_PROP)) { return verifyNotNull(ACCUMULO_PASSWORD_PROP, getString(ACCUMULO_PASSWORD_PROP)); } else if (containsKey(CLIENT_ACCUMULO_PASSWORD_PROP)) { return verifyNotNull(CLIENT_ACCUMULO_PASSWORD_PROP, getString(CLIENT_ACCUMULO_PASSWORD_PROP)); } throw new NoSuchElementException(ACCUMULO_PASSWORD_PROP + " is not set!"); }
java
public String getAccumuloPassword() { if (containsKey(ACCUMULO_PASSWORD_PROP)) { return verifyNotNull(ACCUMULO_PASSWORD_PROP, getString(ACCUMULO_PASSWORD_PROP)); } else if (containsKey(CLIENT_ACCUMULO_PASSWORD_PROP)) { return verifyNotNull(CLIENT_ACCUMULO_PASSWORD_PROP, getString(CLIENT_ACCUMULO_PASSWORD_PROP)); } throw new NoSuchElementException(ACCUMULO_PASSWORD_PROP + " is not set!"); }
[ "public", "String", "getAccumuloPassword", "(", ")", "{", "if", "(", "containsKey", "(", "ACCUMULO_PASSWORD_PROP", ")", ")", "{", "return", "verifyNotNull", "(", "ACCUMULO_PASSWORD_PROP", ",", "getString", "(", "ACCUMULO_PASSWORD_PROP", ")", ")", ";", "}", "else",...
Gets the Apache Accumulo password property value {@value #ACCUMULO_PASSWORD_PROP} @throws NoSuchElementException if {@value #ACCUMULO_PASSWORD_PROP} is not set
[ "Gets", "the", "Apache", "Accumulo", "password", "property", "value", "{", "@value", "#ACCUMULO_PASSWORD_PROP", "}" ]
train
https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/api/src/main/java/org/apache/fluo/api/config/FluoConfiguration.java#L511-L518
classgraph/classgraph
src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java
FileUtils.getParentDirPath
public static String getParentDirPath(final String path, final char separator) { final int lastSlashIdx = path.lastIndexOf(separator); if (lastSlashIdx <= 0) { return ""; } return path.substring(0, lastSlashIdx); }
java
public static String getParentDirPath(final String path, final char separator) { final int lastSlashIdx = path.lastIndexOf(separator); if (lastSlashIdx <= 0) { return ""; } return path.substring(0, lastSlashIdx); }
[ "public", "static", "String", "getParentDirPath", "(", "final", "String", "path", ",", "final", "char", "separator", ")", "{", "final", "int", "lastSlashIdx", "=", "path", ".", "lastIndexOf", "(", "separator", ")", ";", "if", "(", "lastSlashIdx", "<=", "0", ...
Get the parent dir path. @param path the path @param separator the separator @return the parent dir path
[ "Get", "the", "parent", "dir", "path", "." ]
train
https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L431-L437
xiancloud/xian
xian-core/src/main/java/info/xiancloud/core/message/UnitResponse.java
UnitResponse.createException
public static UnitResponse createException(String errCode, Throwable exception) { return UnitResponse.createException(exception).setCode(errCode); }
java
public static UnitResponse createException(String errCode, Throwable exception) { return UnitResponse.createException(exception).setCode(errCode); }
[ "public", "static", "UnitResponse", "createException", "(", "String", "errCode", ",", "Throwable", "exception", ")", "{", "return", "UnitResponse", ".", "createException", "(", "exception", ")", ".", "setCode", "(", "errCode", ")", ";", "}" ]
Create an exception unit response object. @param errCode the error code for the unit response. @param exception the exception object. @return the newly created unit response.
[ "Create", "an", "exception", "unit", "response", "object", "." ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-core/src/main/java/info/xiancloud/core/message/UnitResponse.java#L139-L141
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/CareWebShellEx.java
CareWebShellEx.registerFromId
public ElementBase registerFromId(String path, String id, IPropertyProvider propertySource) throws Exception { return register(path, pluginById(id), propertySource); }
java
public ElementBase registerFromId(String path, String id, IPropertyProvider propertySource) throws Exception { return register(path, pluginById(id), propertySource); }
[ "public", "ElementBase", "registerFromId", "(", "String", "path", ",", "String", "id", ",", "IPropertyProvider", "propertySource", ")", "throws", "Exception", "{", "return", "register", "(", "path", ",", "pluginById", "(", "id", ")", ",", "propertySource", ")", ...
Registers the plugin with the specified id and path. If a tree path is absent, the plugin is associated with the tab itself. @param path Format is &lt;tab name&gt;\&lt;tree node path&gt; @param id Unique id of plugin @param propertySource Optional source for retrieving property values. @return Container created for the plugin. @throws Exception Unspecified exception.
[ "Registers", "the", "plugin", "with", "the", "specified", "id", "and", "path", ".", "If", "a", "tree", "path", "is", "absent", "the", "plugin", "is", "associated", "with", "the", "tab", "itself", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/CareWebShellEx.java#L162-L164
andrehertwig/admintool
admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java
AdminToolLog4j2Util.getStringOutput
public String getStringOutput(String appenderName, String encoding) throws UnsupportedEncodingException { AdminToolLog4j2OutputStream baos = outputStreams.get(appenderName); String output = ""; if (null != baos) { output = baos.getAndReset(encoding); } return output.trim().isEmpty() ? null : output; }
java
public String getStringOutput(String appenderName, String encoding) throws UnsupportedEncodingException { AdminToolLog4j2OutputStream baos = outputStreams.get(appenderName); String output = ""; if (null != baos) { output = baos.getAndReset(encoding); } return output.trim().isEmpty() ? null : output; }
[ "public", "String", "getStringOutput", "(", "String", "appenderName", ",", "String", "encoding", ")", "throws", "UnsupportedEncodingException", "{", "AdminToolLog4j2OutputStream", "baos", "=", "outputStreams", ".", "get", "(", "appenderName", ")", ";", "String", "outp...
returns the log messages from custom appenders output stream @param appenderName @param encoding @return @throws UnsupportedEncodingException @since 1.1.1
[ "returns", "the", "log", "messages", "from", "custom", "appenders", "output", "stream" ]
train
https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-log4j2/src/main/java/de/chandre/admintool/log4j2/AdminToolLog4j2Util.java#L500-L508
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java
WordVectorSerializer.writeVocabCache
public static void writeVocabCache(@NonNull VocabCache<VocabWord> vocabCache, @NonNull OutputStream stream) throws IOException { try (PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8)))) { // saving general vocab information writer.println("" + vocabCache.numWords() + " " + vocabCache.totalNumberOfDocs() + " " + vocabCache.totalWordOccurrences()); for (int x = 0; x < vocabCache.numWords(); x++) { VocabWord word = vocabCache.elementAtIndex(x); writer.println(word.toJSON()); } } }
java
public static void writeVocabCache(@NonNull VocabCache<VocabWord> vocabCache, @NonNull OutputStream stream) throws IOException { try (PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8)))) { // saving general vocab information writer.println("" + vocabCache.numWords() + " " + vocabCache.totalNumberOfDocs() + " " + vocabCache.totalWordOccurrences()); for (int x = 0; x < vocabCache.numWords(); x++) { VocabWord word = vocabCache.elementAtIndex(x); writer.println(word.toJSON()); } } }
[ "public", "static", "void", "writeVocabCache", "(", "@", "NonNull", "VocabCache", "<", "VocabWord", ">", "vocabCache", ",", "@", "NonNull", "OutputStream", "stream", ")", "throws", "IOException", "{", "try", "(", "PrintWriter", "writer", "=", "new", "PrintWriter...
This method saves vocab cache to provided OutputStream. Please note: it saves only vocab content, so it's suitable mostly for BagOfWords/TF-IDF vectorizers @param vocabCache @param stream @throws UnsupportedEncodingException
[ "This", "method", "saves", "vocab", "cache", "to", "provided", "OutputStream", ".", "Please", "note", ":", "it", "saves", "only", "vocab", "content", "so", "it", "s", "suitable", "mostly", "for", "BagOfWords", "/", "TF", "-", "IDF", "vectorizers" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java#L2201-L2212
pravega/pravega
common/src/main/java/io/pravega/common/io/BoundedInputStream.java
BoundedInputStream.subStream
public BoundedInputStream subStream(int bound) { Preconditions.checkArgument(bound >= 0 && bound <= this.remaining, "bound must be a non-negative integer and less than or equal to the remaining length."); this.remaining -= bound; return new BoundedInputStream(this.in, bound); }
java
public BoundedInputStream subStream(int bound) { Preconditions.checkArgument(bound >= 0 && bound <= this.remaining, "bound must be a non-negative integer and less than or equal to the remaining length."); this.remaining -= bound; return new BoundedInputStream(this.in, bound); }
[ "public", "BoundedInputStream", "subStream", "(", "int", "bound", ")", "{", "Preconditions", ".", "checkArgument", "(", "bound", ">=", "0", "&&", "bound", "<=", "this", ".", "remaining", ",", "\"bound must be a non-negative integer and less than or equal to the remaining ...
Creates a new BoundedInputStream wrapping the same InputStream as this one, starting at the current position, with the given bound. NOTE: both this instance and the result of this method should not be both used at the same time to read from the InputStream. When this method returns, this instance's remaining count will be reduced by the given bound (that's since upon closing, the BoundedInputStream will auto-advance to its bound position). @param bound The bound of the sub-stream. @return A new instance of a BoundedInputStream.
[ "Creates", "a", "new", "BoundedInputStream", "wrapping", "the", "same", "InputStream", "as", "this", "one", "starting", "at", "the", "current", "position", "with", "the", "given", "bound", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/io/BoundedInputStream.java#L113-L118
Minecrell/TerminalConsoleAppender
src/main/java/net/minecrell/terminalconsole/HighlightErrorConverter.java
HighlightErrorConverter.newInstance
public static HighlightErrorConverter newInstance(Configuration config, String[] options) { if (options.length != 1) { LOGGER.error("Incorrect number of options on highlightError. Expected 1 received " + options.length); return null; } if (options[0] == null) { LOGGER.error("No pattern supplied on highlightError"); return null; } PatternParser parser = PatternLayout.createPatternParser(config); List<PatternFormatter> formatters = parser.parse(options[0]); return new HighlightErrorConverter(formatters); }
java
public static HighlightErrorConverter newInstance(Configuration config, String[] options) { if (options.length != 1) { LOGGER.error("Incorrect number of options on highlightError. Expected 1 received " + options.length); return null; } if (options[0] == null) { LOGGER.error("No pattern supplied on highlightError"); return null; } PatternParser parser = PatternLayout.createPatternParser(config); List<PatternFormatter> formatters = parser.parse(options[0]); return new HighlightErrorConverter(formatters); }
[ "public", "static", "HighlightErrorConverter", "newInstance", "(", "Configuration", "config", ",", "String", "[", "]", "options", ")", "{", "if", "(", "options", ".", "length", "!=", "1", ")", "{", "LOGGER", ".", "error", "(", "\"Incorrect number of options on h...
Gets a new instance of the {@link HighlightErrorConverter} with the specified options. @param config The current configuration @param options The pattern options @return The new instance
[ "Gets", "a", "new", "instance", "of", "the", "{", "@link", "HighlightErrorConverter", "}", "with", "the", "specified", "options", "." ]
train
https://github.com/Minecrell/TerminalConsoleAppender/blob/a540454b397ee488993019fbcacc49b2d88f1752/src/main/java/net/minecrell/terminalconsole/HighlightErrorConverter.java#L141-L154
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/LettuceFutures.java
LettuceFutures.awaitAll
public static boolean awaitAll(Duration timeout, Future<?>... futures) { return awaitAll(timeout.toNanos(), TimeUnit.NANOSECONDS, futures); }
java
public static boolean awaitAll(Duration timeout, Future<?>... futures) { return awaitAll(timeout.toNanos(), TimeUnit.NANOSECONDS, futures); }
[ "public", "static", "boolean", "awaitAll", "(", "Duration", "timeout", ",", "Future", "<", "?", ">", "...", "futures", ")", "{", "return", "awaitAll", "(", "timeout", ".", "toNanos", "(", ")", ",", "TimeUnit", ".", "NANOSECONDS", ",", "futures", ")", ";"...
Wait until futures are complete or the supplied timeout is reached. Commands are not canceled (in contrast to {@link #awaitOrCancel(RedisFuture, long, TimeUnit)}) when the timeout expires. @param timeout Maximum time to wait for futures to complete. @param futures Futures to wait for. @return {@literal true} if all futures complete in time, otherwise {@literal false} @since 5.0
[ "Wait", "until", "futures", "are", "complete", "or", "the", "supplied", "timeout", "is", "reached", ".", "Commands", "are", "not", "canceled", "(", "in", "contrast", "to", "{", "@link", "#awaitOrCancel", "(", "RedisFuture", "long", "TimeUnit", ")", "}", ")",...
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/LettuceFutures.java#L45-L47
joniles/mpxj
src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java
MSPDIReader.readCalendars
private void readCalendars(Project project, HashMap<BigInteger, ProjectCalendar> map) { Project.Calendars calendars = project.getCalendars(); if (calendars != null) { LinkedList<Pair<ProjectCalendar, BigInteger>> baseCalendars = new LinkedList<Pair<ProjectCalendar, BigInteger>>(); for (Project.Calendars.Calendar cal : calendars.getCalendar()) { readCalendar(cal, map, baseCalendars); } updateBaseCalendarNames(baseCalendars, map); } try { ProjectProperties properties = m_projectFile.getProjectProperties(); BigInteger calendarID = new BigInteger(properties.getDefaultCalendarName()); ProjectCalendar calendar = map.get(calendarID); m_projectFile.setDefaultCalendar(calendar); } catch (Exception ex) { // Ignore exceptions } }
java
private void readCalendars(Project project, HashMap<BigInteger, ProjectCalendar> map) { Project.Calendars calendars = project.getCalendars(); if (calendars != null) { LinkedList<Pair<ProjectCalendar, BigInteger>> baseCalendars = new LinkedList<Pair<ProjectCalendar, BigInteger>>(); for (Project.Calendars.Calendar cal : calendars.getCalendar()) { readCalendar(cal, map, baseCalendars); } updateBaseCalendarNames(baseCalendars, map); } try { ProjectProperties properties = m_projectFile.getProjectProperties(); BigInteger calendarID = new BigInteger(properties.getDefaultCalendarName()); ProjectCalendar calendar = map.get(calendarID); m_projectFile.setDefaultCalendar(calendar); } catch (Exception ex) { // Ignore exceptions } }
[ "private", "void", "readCalendars", "(", "Project", "project", ",", "HashMap", "<", "BigInteger", ",", "ProjectCalendar", ">", "map", ")", "{", "Project", ".", "Calendars", "calendars", "=", "project", ".", "getCalendars", "(", ")", ";", "if", "(", "calendar...
This method extracts calendar data from an MSPDI file. @param project Root node of the MSPDI file @param map Map of calendar UIDs to names
[ "This", "method", "extracts", "calendar", "data", "from", "an", "MSPDI", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java#L384-L409
netty/netty
common/src/main/java/io/netty/util/internal/PlatformDependent.java
PlatformDependent.isZero
public static boolean isZero(byte[] bytes, int startPos, int length) { return !hasUnsafe() || !unalignedAccess() ? isZeroSafe(bytes, startPos, length) : PlatformDependent0.isZero(bytes, startPos, length); }
java
public static boolean isZero(byte[] bytes, int startPos, int length) { return !hasUnsafe() || !unalignedAccess() ? isZeroSafe(bytes, startPos, length) : PlatformDependent0.isZero(bytes, startPos, length); }
[ "public", "static", "boolean", "isZero", "(", "byte", "[", "]", "bytes", ",", "int", "startPos", ",", "int", "length", ")", "{", "return", "!", "hasUnsafe", "(", ")", "||", "!", "unalignedAccess", "(", ")", "?", "isZeroSafe", "(", "bytes", ",", "startP...
Determine if a subsection of an array is zero. @param bytes The byte array. @param startPos The starting index (inclusive) in {@code bytes}. @param length The amount of bytes to check for zero. @return {@code false} if {@code bytes[startPos:startsPos+length)} contains a value other than zero.
[ "Determine", "if", "a", "subsection", "of", "an", "array", "is", "zero", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/internal/PlatformDependent.java#L709-L713
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java
NumberUtil.div
public static BigDecimal div(Number v1, Number v2, int scale) { return div(v1, v2, scale, RoundingMode.HALF_UP); }
java
public static BigDecimal div(Number v1, Number v2, int scale) { return div(v1, v2, scale, RoundingMode.HALF_UP); }
[ "public", "static", "BigDecimal", "div", "(", "Number", "v1", ",", "Number", "v2", ",", "int", "scale", ")", "{", "return", "div", "(", "v1", ",", "v2", ",", "scale", ",", "RoundingMode", ".", "HALF_UP", ")", ";", "}" ]
提供(相对)精确的除法运算,当发生除不尽的情况时,由scale指定精确度,后面的四舍五入 @param v1 被除数 @param v2 除数 @param scale 精确度,如果为负值,取绝对值 @return 两个参数的商 @since 3.1.0
[ "提供", "(", "相对", ")", "精确的除法运算", "当发生除不尽的情况时", "由scale指定精确度", "后面的四舍五入" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java#L623-L625
Bedework/bw-util
bw-util-struts/src/main/java/org/bedework/util/struts/UtilAbstractAction.java
UtilAbstractAction.getReqPar
protected String getReqPar(final HttpServletRequest req, final String name) throws Throwable { return Util.checkNull(req.getParameter(name)); }
java
protected String getReqPar(final HttpServletRequest req, final String name) throws Throwable { return Util.checkNull(req.getParameter(name)); }
[ "protected", "String", "getReqPar", "(", "final", "HttpServletRequest", "req", ",", "final", "String", "name", ")", "throws", "Throwable", "{", "return", "Util", ".", "checkNull", "(", "req", ".", "getParameter", "(", "name", ")", ")", ";", "}" ]
Get a request parameter stripped of white space. Return null for zero length. @param req @param name name of parameter @return String value @throws Throwable
[ "Get", "a", "request", "parameter", "stripped", "of", "white", "space", ".", "Return", "null", "for", "zero", "length", "." ]
train
https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-struts/src/main/java/org/bedework/util/struts/UtilAbstractAction.java#L981-L983
aws/aws-sdk-java
aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/Input.java
Input.withAudioSelectorGroups
public Input withAudioSelectorGroups(java.util.Map<String, AudioSelectorGroup> audioSelectorGroups) { setAudioSelectorGroups(audioSelectorGroups); return this; }
java
public Input withAudioSelectorGroups(java.util.Map<String, AudioSelectorGroup> audioSelectorGroups) { setAudioSelectorGroups(audioSelectorGroups); return this; }
[ "public", "Input", "withAudioSelectorGroups", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "AudioSelectorGroup", ">", "audioSelectorGroups", ")", "{", "setAudioSelectorGroups", "(", "audioSelectorGroups", ")", ";", "return", "this", ";", "}" ]
Specifies set of audio selectors within an input to combine. An input may have multiple audio selector groups. See "Audio Selector Group":#inputs-audio_selector_group for more information. @param audioSelectorGroups Specifies set of audio selectors within an input to combine. An input may have multiple audio selector groups. See "Audio Selector Group":#inputs-audio_selector_group for more information. @return Returns a reference to this object so that method calls can be chained together.
[ "Specifies", "set", "of", "audio", "selectors", "within", "an", "input", "to", "combine", ".", "An", "input", "may", "have", "multiple", "audio", "selector", "groups", ".", "See", "Audio", "Selector", "Group", ":", "#inputs", "-", "audio_selector_group", "for"...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/Input.java#L158-L161
thorntail/thorntail
fractions/swagger/src/main/java/org/wildfly/swarm/swagger/runtime/SwaggerArchivePreparer.java
SwaggerArchivePreparer.extractAndAddPackageInfo
private static void extractAndAddPackageInfo(ClassInfo classInfo, Set<String> packages, IndexView indexView) { if (classInfo == null) { return; } // Check if we were given an abstract class / interface, in which case we need to check the IndexView to see if there // is an implementation or not. String className = classInfo.name().toString(); if (indexView != null) { DotName dotName = DotName.createSimple(className); if (Modifier.isInterface(classInfo.flags())) { indexView.getAllKnownImplementors(dotName).forEach(ci -> extractAndAddPackageInfo(ci, packages, indexView)); } else if (Modifier.isAbstract(classInfo.flags())) { indexView.getAllKnownSubclasses(dotName).forEach(ci -> extractAndAddPackageInfo(ci, packages, indexView)); } } StringBuilder builder = new StringBuilder(className).reverse(); int idx = builder.indexOf("."); if (idx != -1) { builder.delete(0, idx + 1); } packages.add(builder.reverse().toString()); }
java
private static void extractAndAddPackageInfo(ClassInfo classInfo, Set<String> packages, IndexView indexView) { if (classInfo == null) { return; } // Check if we were given an abstract class / interface, in which case we need to check the IndexView to see if there // is an implementation or not. String className = classInfo.name().toString(); if (indexView != null) { DotName dotName = DotName.createSimple(className); if (Modifier.isInterface(classInfo.flags())) { indexView.getAllKnownImplementors(dotName).forEach(ci -> extractAndAddPackageInfo(ci, packages, indexView)); } else if (Modifier.isAbstract(classInfo.flags())) { indexView.getAllKnownSubclasses(dotName).forEach(ci -> extractAndAddPackageInfo(ci, packages, indexView)); } } StringBuilder builder = new StringBuilder(className).reverse(); int idx = builder.indexOf("."); if (idx != -1) { builder.delete(0, idx + 1); } packages.add(builder.reverse().toString()); }
[ "private", "static", "void", "extractAndAddPackageInfo", "(", "ClassInfo", "classInfo", ",", "Set", "<", "String", ">", "packages", ",", "IndexView", "indexView", ")", "{", "if", "(", "classInfo", "==", "null", ")", "{", "return", ";", "}", "// Check if we wer...
Extract the package information from the given {@code ClassInfo} object. @param classInfo the class metadata. @param packages the collection to which we need to add the package information.
[ "Extract", "the", "package", "information", "from", "the", "given", "{", "@code", "ClassInfo", "}", "object", "." ]
train
https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/fractions/swagger/src/main/java/org/wildfly/swarm/swagger/runtime/SwaggerArchivePreparer.java#L291-L313
spotbugs/spotbugs
eclipsePlugin/src/de/tobject/findbugs/reporter/MarkerUtil.java
MarkerUtil.getMarkerFromEditor
public static IMarker getMarkerFromEditor(ITextSelection selection, IEditorPart editor) { IResource resource = (IResource) editor.getEditorInput().getAdapter(IFile.class); IMarker[] allMarkers; if (resource != null) { allMarkers = getMarkers(resource, IResource.DEPTH_ZERO); } else { IClassFile classFile = (IClassFile) editor.getEditorInput().getAdapter(IClassFile.class); if (classFile == null) { return null; } Set<IMarker> markers = getMarkers(classFile.getType()); allMarkers = markers.toArray(new IMarker[markers.size()]); } // if editor contains only one FB marker, do some cheating and always // return it. if (allMarkers.length == 1) { return allMarkers[0]; } // +1 because it counts real lines, but editor shows lines + 1 int startLine = selection.getStartLine() + 1; for (IMarker marker : allMarkers) { int line = getEditorLine(marker); if (startLine == line) { return marker; } } return null; }
java
public static IMarker getMarkerFromEditor(ITextSelection selection, IEditorPart editor) { IResource resource = (IResource) editor.getEditorInput().getAdapter(IFile.class); IMarker[] allMarkers; if (resource != null) { allMarkers = getMarkers(resource, IResource.DEPTH_ZERO); } else { IClassFile classFile = (IClassFile) editor.getEditorInput().getAdapter(IClassFile.class); if (classFile == null) { return null; } Set<IMarker> markers = getMarkers(classFile.getType()); allMarkers = markers.toArray(new IMarker[markers.size()]); } // if editor contains only one FB marker, do some cheating and always // return it. if (allMarkers.length == 1) { return allMarkers[0]; } // +1 because it counts real lines, but editor shows lines + 1 int startLine = selection.getStartLine() + 1; for (IMarker marker : allMarkers) { int line = getEditorLine(marker); if (startLine == line) { return marker; } } return null; }
[ "public", "static", "IMarker", "getMarkerFromEditor", "(", "ITextSelection", "selection", ",", "IEditorPart", "editor", ")", "{", "IResource", "resource", "=", "(", "IResource", ")", "editor", ".", "getEditorInput", "(", ")", ".", "getAdapter", "(", "IFile", "."...
Tries to retrieve right bug marker for given selection. If there are many markers for given editor, and text selection doesn't match any of them, return null. If there is only one marker for given editor, returns this marker in any case. @param selection @param editor @return may return null
[ "Tries", "to", "retrieve", "right", "bug", "marker", "for", "given", "selection", ".", "If", "there", "are", "many", "markers", "for", "given", "editor", "and", "text", "selection", "doesn", "t", "match", "any", "of", "them", "return", "null", ".", "If", ...
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/reporter/MarkerUtil.java#L881-L908
Azure/azure-sdk-for-java
compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/DisksInner.java
DisksInner.revokeAccessAsync
public Observable<OperationStatusResponseInner> revokeAccessAsync(String resourceGroupName, String diskName) { return revokeAccessWithServiceResponseAsync(resourceGroupName, diskName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) { return response.body(); } }); }
java
public Observable<OperationStatusResponseInner> revokeAccessAsync(String resourceGroupName, String diskName) { return revokeAccessWithServiceResponseAsync(resourceGroupName, diskName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatusResponseInner", ">", "revokeAccessAsync", "(", "String", "resourceGroupName", ",", "String", "diskName", ")", "{", "return", "revokeAccessWithServiceResponseAsync", "(", "resourceGroupName", ",", "diskName", ")", ".", "map", ...
Revokes access to a disk. @param resourceGroupName The name of the resource group. @param diskName The name of the managed disk that is being created. The name can't be changed after the disk is created. Supported characters for the name are a-z, A-Z, 0-9 and _. The maximum name length is 80 characters. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Revokes", "access", "to", "a", "disk", "." ]
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/DisksInner.java#L1149-L1156
Azure/azure-sdk-for-java
network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/ExpressRouteCircuitAuthorizationsInner.java
ExpressRouteCircuitAuthorizationsInner.createOrUpdate
public ExpressRouteCircuitAuthorizationInner createOrUpdate(String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).toBlocking().last().body(); }
java
public ExpressRouteCircuitAuthorizationInner createOrUpdate(String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).toBlocking().last().body(); }
[ "public", "ExpressRouteCircuitAuthorizationInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "circuitName", ",", "String", "authorizationName", ",", "ExpressRouteCircuitAuthorizationInner", "authorizationParameters", ")", "{", "return", "createOrUpdateW...
Creates or updates an authorization in the specified express route circuit. @param resourceGroupName The name of the resource group. @param circuitName The name of the express route circuit. @param authorizationName The name of the authorization. @param authorizationParameters Parameters supplied to the create or update express route circuit authorization operation. @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 ExpressRouteCircuitAuthorizationInner object if successful.
[ "Creates", "or", "updates", "an", "authorization", "in", "the", "specified", "express", "route", "circuit", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/ExpressRouteCircuitAuthorizationsInner.java#L362-L364
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.publishAll
private String publishAll(KeenProject project, Map<String, List<Map<String, Object>>> events) throws IOException { // just using basic JDK HTTP library String urlString = String.format(Locale.US, "%s/%s/projects/%s/events", getBaseUrl(), KeenConstants.API_VERSION, project.getProjectId()); URL url = new URL(urlString); return publishObject(project, url, events); }
java
private String publishAll(KeenProject project, Map<String, List<Map<String, Object>>> events) throws IOException { // just using basic JDK HTTP library String urlString = String.format(Locale.US, "%s/%s/projects/%s/events", getBaseUrl(), KeenConstants.API_VERSION, project.getProjectId()); URL url = new URL(urlString); return publishObject(project, url, events); }
[ "private", "String", "publishAll", "(", "KeenProject", "project", ",", "Map", "<", "String", ",", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", ">", "events", ")", "throws", "IOException", "{", "// just using basic JDK HTTP library", "String", "u...
Publishes a batch of events to the Keen service. @param project The project in which to publish the event. @param events A map from collection name to a list of event maps. @return The response from the server. @throws IOException If there was an error communicating with the server.
[ "Publishes", "a", "batch", "of", "events", "to", "the", "Keen", "service", "." ]
train
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1425-L1432
RestComm/sip-servlets
containers/sip-servlets-as10/src/main/java/org/mobicents/servlet/sip/startup/ConvergedServletContextImpl.java
ConvergedServletContextImpl.doPrivileged
private Object doPrivileged(final String methodName, final Class<?>[] clazz, Object[] params) { try { Method method = context.getClass().getMethod(methodName, clazz); return executeMethod(method, context, params); } catch (Exception ex) { try { handleException(ex); } catch (Throwable t) { handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; } finally { params = null; } }
java
private Object doPrivileged(final String methodName, final Class<?>[] clazz, Object[] params) { try { Method method = context.getClass().getMethod(methodName, clazz); return executeMethod(method, context, params); } catch (Exception ex) { try { handleException(ex); } catch (Throwable t) { handleThrowable(t); throw new RuntimeException(t.getMessage()); } return null; } finally { params = null; } }
[ "private", "Object", "doPrivileged", "(", "final", "String", "methodName", ",", "final", "Class", "<", "?", ">", "[", "]", "clazz", ",", "Object", "[", "]", "params", ")", "{", "try", "{", "Method", "method", "=", "context", ".", "getClass", "(", ")", ...
Use reflection to invoke the requested method. Cache the method object to speed up the process @param methodName The method to invoke. @param clazz The class where the method is. @param params The arguments passed to the called method.
[ "Use", "reflection", "to", "invoke", "the", "requested", "method", ".", "Cache", "the", "method", "object", "to", "speed", "up", "the", "process" ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/containers/sip-servlets-as10/src/main/java/org/mobicents/servlet/sip/startup/ConvergedServletContextImpl.java#L834-L850
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/Step.java
Step.checkInputText
protected boolean checkInputText(PageElement pageElement, String textOrKey) throws FailureException, TechnicalException { WebElement inputText = null; String value = getTextOrKey(textOrKey); try { inputText = Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(pageElement))); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, pageElement.getPage().getCallBack()); } return !(inputText == null || value == null || inputText.getAttribute(VALUE) == null || !value.equals(inputText.getAttribute(VALUE).trim())); }
java
protected boolean checkInputText(PageElement pageElement, String textOrKey) throws FailureException, TechnicalException { WebElement inputText = null; String value = getTextOrKey(textOrKey); try { inputText = Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(pageElement))); } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, pageElement.getPage().getCallBack()); } return !(inputText == null || value == null || inputText.getAttribute(VALUE) == null || !value.equals(inputText.getAttribute(VALUE).trim())); }
[ "protected", "boolean", "checkInputText", "(", "PageElement", "pageElement", ",", "String", "textOrKey", ")", "throws", "FailureException", ",", "TechnicalException", "{", "WebElement", "inputText", "=", "null", ";", "String", "value", "=", "getTextOrKey", "(", "tex...
Checks if input text contains expected value. @param pageElement Is target element @param textOrKey Is the data to check (text or text in context (after a save)) @return true or false @throws FailureException if the scenario encounters a functional error @throws TechnicalException
[ "Checks", "if", "input", "text", "contains", "expected", "value", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L288-L297
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/MergeRequestApi.java
MergeRequestApi.cancelMergeRequest
public MergeRequest cancelMergeRequest(Object projectIdOrPath, Integer mergeRequestIid) throws GitLabApiException { if (mergeRequestIid == null) { throw new RuntimeException("mergeRequestIid cannot be null"); } Response response = put(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "cancel_merge_when_pipeline_succeeds"); return (response.readEntity(MergeRequest.class)); }
java
public MergeRequest cancelMergeRequest(Object projectIdOrPath, Integer mergeRequestIid) throws GitLabApiException { if (mergeRequestIid == null) { throw new RuntimeException("mergeRequestIid cannot be null"); } Response response = put(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "cancel_merge_when_pipeline_succeeds"); return (response.readEntity(MergeRequest.class)); }
[ "public", "MergeRequest", "cancelMergeRequest", "(", "Object", "projectIdOrPath", ",", "Integer", "mergeRequestIid", ")", "throws", "GitLabApiException", "{", "if", "(", "mergeRequestIid", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"mergeReques...
Cancel merge when pipeline succeeds. If you don't have permissions to accept this merge request, you'll get a 401. If the merge request is already merged or closed, you get 405 and error message 'Method Not Allowed'. In case the merge request is not set to be merged when the pipeline succeeds, you'll also get a 406 error. <p>NOTE: GitLab API V4 uses IID (internal ID), V3 uses ID to identify the merge request.</p> <pre><code>GitLab Endpoint: PUT /projects/:id/merge_requests/:merge_request_iid/cancel_merge_when_pipeline_succeeds</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param mergeRequestIid the internal ID of the merge request @return the updated merge request @throws GitLabApiException if any exception occurs
[ "Cancel", "merge", "when", "pipeline", "succeeds", ".", "If", "you", "don", "t", "have", "permissions", "to", "accept", "this", "merge", "request", "you", "ll", "get", "a", "401", ".", "If", "the", "merge", "request", "is", "already", "merged", "or", "cl...
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/MergeRequestApi.java#L674-L682
alkacon/opencms-core
src/org/opencms/relations/CmsCategoryService.java
CmsCategoryService.copyCategories
public void copyCategories(CmsObject cms, CmsResource fromResource, String toResourceSitePath) throws CmsException { List<CmsCategory> categories = readResourceCategories(cms, fromResource); for (CmsCategory category : categories) { addResourceToCategory(cms, toResourceSitePath, category); } }
java
public void copyCategories(CmsObject cms, CmsResource fromResource, String toResourceSitePath) throws CmsException { List<CmsCategory> categories = readResourceCategories(cms, fromResource); for (CmsCategory category : categories) { addResourceToCategory(cms, toResourceSitePath, category); } }
[ "public", "void", "copyCategories", "(", "CmsObject", "cms", ",", "CmsResource", "fromResource", ",", "String", "toResourceSitePath", ")", "throws", "CmsException", "{", "List", "<", "CmsCategory", ">", "categories", "=", "readResourceCategories", "(", "cms", ",", ...
Adds all categories from one resource to another, skipping categories that are not available for the resource copied to. The resource where categories are copied to has to be locked. @param cms the CmsObject used for reading and writing. @param fromResource the resource to copy the categories from. @param toResourceSitePath the full site path of the resource to copy the categories to. @throws CmsException thrown if copying the resources fails.
[ "Adds", "all", "categories", "from", "one", "resource", "to", "another", "skipping", "categories", "that", "are", "not", "available", "for", "the", "resource", "copied", "to", "." ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/relations/CmsCategoryService.java#L167-L173
jronrun/benayn
benayn-berkeley/src/main/java/com/benayn/berkeley/Berkeley.java
Berkeley.getSequence
public Sequence getSequence(String sequenceKey, SequenceConfig sequenceConfig) { Sequence sequence = sequences.get(checkNotNull(sequenceKey)); if (null == sequence) { sequence = sequenceDB().openSequence(null, sequenceDB().getEntry(sequenceKey), firstNonNull(sequenceConfig, defaultSequenceConfig())); sequences.put(sequenceKey, sequence); } return sequence; }
java
public Sequence getSequence(String sequenceKey, SequenceConfig sequenceConfig) { Sequence sequence = sequences.get(checkNotNull(sequenceKey)); if (null == sequence) { sequence = sequenceDB().openSequence(null, sequenceDB().getEntry(sequenceKey), firstNonNull(sequenceConfig, defaultSequenceConfig())); sequences.put(sequenceKey, sequence); } return sequence; }
[ "public", "Sequence", "getSequence", "(", "String", "sequenceKey", ",", "SequenceConfig", "sequenceConfig", ")", "{", "Sequence", "sequence", "=", "sequences", ".", "get", "(", "checkNotNull", "(", "sequenceKey", ")", ")", ";", "if", "(", "null", "==", "sequen...
Returns a {@link Sequence} instance with given configuration or {@link Berkeley#defaultSequenceConfig()} if null
[ "Returns", "a", "{" ]
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-berkeley/src/main/java/com/benayn/berkeley/Berkeley.java#L2713-L2722
xiancloud/xian
xian-log/xian-gelf-common/src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
ConfigurationSupport.setAdditionalFieldTypes
public static void setAdditionalFieldTypes(String spec, GelfMessageAssembler gelfMessageAssembler) { if (null != spec) { String[] properties = spec.split(MULTI_VALUE_DELIMITTER); for (String field : properties) { final int index = field.indexOf(EQ); if (-1 != index) { gelfMessageAssembler.setAdditionalFieldType(field.substring(0, index), field.substring(index + 1)); } } } }
java
public static void setAdditionalFieldTypes(String spec, GelfMessageAssembler gelfMessageAssembler) { if (null != spec) { String[] properties = spec.split(MULTI_VALUE_DELIMITTER); for (String field : properties) { final int index = field.indexOf(EQ); if (-1 != index) { gelfMessageAssembler.setAdditionalFieldType(field.substring(0, index), field.substring(index + 1)); } } } }
[ "public", "static", "void", "setAdditionalFieldTypes", "(", "String", "spec", ",", "GelfMessageAssembler", "gelfMessageAssembler", ")", "{", "if", "(", "null", "!=", "spec", ")", "{", "String", "[", "]", "properties", "=", "spec", ".", "split", "(", "MULTI_VAL...
Set the additional field types. @param spec field=String,field1=Double, ... See {@link GelfMessage} for supported types. @param gelfMessageAssembler the Gelf message assembler to apply the configuration
[ "Set", "the", "additional", "field", "types", "." ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-log/xian-gelf-common/src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java#L77-L88
killbill/killbill
subscription/src/main/java/org/killbill/billing/subscription/alignment/PlanAligner.java
PlanAligner.getCurrentTimedPhaseOnChange
public TimedPhase getCurrentTimedPhaseOnChange(final DefaultSubscriptionBase subscription, final Plan plan, final DateTime effectiveDate, final PhaseType newPlanInitialPhaseType, final Catalog catalog, final InternalTenantContext context) throws CatalogApiException, SubscriptionBaseApiException { return getTimedPhaseOnChange(subscription, plan, effectiveDate, newPlanInitialPhaseType, WhichPhase.CURRENT, catalog, context); }
java
public TimedPhase getCurrentTimedPhaseOnChange(final DefaultSubscriptionBase subscription, final Plan plan, final DateTime effectiveDate, final PhaseType newPlanInitialPhaseType, final Catalog catalog, final InternalTenantContext context) throws CatalogApiException, SubscriptionBaseApiException { return getTimedPhaseOnChange(subscription, plan, effectiveDate, newPlanInitialPhaseType, WhichPhase.CURRENT, catalog, context); }
[ "public", "TimedPhase", "getCurrentTimedPhaseOnChange", "(", "final", "DefaultSubscriptionBase", "subscription", ",", "final", "Plan", "plan", ",", "final", "DateTime", "effectiveDate", ",", "final", "PhaseType", "newPlanInitialPhaseType", ",", "final", "Catalog", "catalo...
Returns current Phase for that Plan change @param subscription the subscription in change (only start date, bundle start date, current phase, plan and pricelist are looked at) @param plan the current Plan @param effectiveDate the effective change date (driven by the catalog policy, i.e. when the change occurs) @param newPlanInitialPhaseType the phase on which to start when switching to new plan @return the current phase @throws CatalogApiException for catalog errors @throws org.killbill.billing.subscription.api.user.SubscriptionBaseApiException for subscription errors
[ "Returns", "current", "Phase", "for", "that", "Plan", "change" ]
train
https://github.com/killbill/killbill/blob/6457b485fb32a182c76197a83f428123331f1380/subscription/src/main/java/org/killbill/billing/subscription/alignment/PlanAligner.java#L113-L121
Netflix/spectator
spectator-api/src/main/java/com/netflix/spectator/api/Utils.java
Utils.getTagValue
public static String getTagValue(Id id, String k) { Preconditions.checkNotNull(id, "id"); return getTagValue(id.tags(), k); }
java
public static String getTagValue(Id id, String k) { Preconditions.checkNotNull(id, "id"); return getTagValue(id.tags(), k); }
[ "public", "static", "String", "getTagValue", "(", "Id", "id", ",", "String", "k", ")", "{", "Preconditions", ".", "checkNotNull", "(", "id", ",", "\"id\"", ")", ";", "return", "getTagValue", "(", "id", ".", "tags", "(", ")", ",", "k", ")", ";", "}" ]
Returns the value associated with with a given key or null if no such key is present in the set of tags. @param id Identifier with a set of tags to search. @param k Key to search for. @return Value for the key or null if the key is not present.
[ "Returns", "the", "value", "associated", "with", "with", "a", "given", "key", "or", "null", "if", "no", "such", "key", "is", "present", "in", "the", "set", "of", "tags", "." ]
train
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/Utils.java#L97-L100
windup/windup
reporting/api/src/main/java/org/jboss/windup/reporting/service/QuickfixService.java
QuickfixService.getOrCreate
@SuppressWarnings("unchecked") public QuickfixModel getOrCreate(String name, QuickfixType type) { Iterable<Vertex> results = (Iterable<Vertex>)getQuery().getRawTraversal().has(QuickfixModel.PROPERTY_TYPE, type).has(QuickfixModel.PROPERTY_DESCRIPTION, name).toList(); if (!results.iterator().hasNext()) { QuickfixModel model = create(); model.setQuickfixType(type); model.setName(name); return model; } return frame(results.iterator().next()); }
java
@SuppressWarnings("unchecked") public QuickfixModel getOrCreate(String name, QuickfixType type) { Iterable<Vertex> results = (Iterable<Vertex>)getQuery().getRawTraversal().has(QuickfixModel.PROPERTY_TYPE, type).has(QuickfixModel.PROPERTY_DESCRIPTION, name).toList(); if (!results.iterator().hasNext()) { QuickfixModel model = create(); model.setQuickfixType(type); model.setName(name); return model; } return frame(results.iterator().next()); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "QuickfixModel", "getOrCreate", "(", "String", "name", ",", "QuickfixType", "type", ")", "{", "Iterable", "<", "Vertex", ">", "results", "=", "(", "Iterable", "<", "Vertex", ">", ")", "getQuery", ...
Tries to find a link with the specified description and href. If it cannot, then it will return a new one.
[ "Tries", "to", "find", "a", "link", "with", "the", "specified", "description", "and", "href", ".", "If", "it", "cannot", "then", "it", "will", "return", "a", "new", "one", "." ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/QuickfixService.java#L27-L39
UrielCh/ovh-java-sdk
ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java
ApiOvhPrice.vps_2018v1_cloud_option_optionName_GET
public OvhPrice vps_2018v1_cloud_option_optionName_GET(net.minidev.ovh.api.price.vps._2018v1.cloud.OvhOptionEnum optionName) throws IOException { String qPath = "/price/vps/2018v1/cloud/option/{optionName}"; StringBuilder sb = path(qPath, optionName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPrice.class); }
java
public OvhPrice vps_2018v1_cloud_option_optionName_GET(net.minidev.ovh.api.price.vps._2018v1.cloud.OvhOptionEnum optionName) throws IOException { String qPath = "/price/vps/2018v1/cloud/option/{optionName}"; StringBuilder sb = path(qPath, optionName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPrice.class); }
[ "public", "OvhPrice", "vps_2018v1_cloud_option_optionName_GET", "(", "net", ".", "minidev", ".", "ovh", ".", "api", ".", "price", ".", "vps", ".", "_2018v1", ".", "cloud", ".", "OvhOptionEnum", "optionName", ")", "throws", "IOException", "{", "String", "qPath", ...
Get price of VPS Cloud Options 2015/2016 REST: GET /price/vps/2018v1/cloud/option/{optionName} @param optionName [required] Option
[ "Get", "price", "of", "VPS", "Cloud", "Options", "2015", "/", "2016" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java#L6823-L6828
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/ProjectManager.java
ProjectManager.getProjectFileHandler
public ProjectFileHandler getProjectFileHandler(final Project project, final int version) throws ProjectManagerException { return this.azkabanProjectLoader.getProjectFile(project, version); }
java
public ProjectFileHandler getProjectFileHandler(final Project project, final int version) throws ProjectManagerException { return this.azkabanProjectLoader.getProjectFile(project, version); }
[ "public", "ProjectFileHandler", "getProjectFileHandler", "(", "final", "Project", "project", ",", "final", "int", "version", ")", "throws", "ProjectManagerException", "{", "return", "this", ".", "azkabanProjectLoader", ".", "getProjectFile", "(", "project", ",", "vers...
This method retrieves the uploaded project zip file from DB. A temporary file is created to hold the content of the uploaded zip file. This temporary file is provided in the ProjectFileHandler instance and the caller of this method should call method {@ProjectFileHandler.deleteLocalFile} to delete the temporary file. @param version - latest version is used if value is -1 @return ProjectFileHandler - null if can't find project zip file based on project name and version
[ "This", "method", "retrieves", "the", "uploaded", "project", "zip", "file", "from", "DB", ".", "A", "temporary", "file", "is", "created", "to", "hold", "the", "content", "of", "the", "uploaded", "zip", "file", ".", "This", "temporary", "file", "is", "provi...
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/project/ProjectManager.java#L503-L506
OpenLiberty/open-liberty
dev/com.ibm.ws.cdi.weld/src/com/ibm/ws/cdi/impl/weld/WebSphereCDIDeploymentImpl.java
WebSphereCDIDeploymentImpl.makeWiring
private void makeWiring(WebSphereBeanDeploymentArchive wireFromBda, WebSphereBeanDeploymentArchive wireToBda, ClassLoader wireToBdaCL, ClassLoader wireFromBdaCL) { while (wireFromBdaCL != null) { if (wireFromBdaCL == wireToBdaCL) { wireFromBda.addBeanDeploymentArchive(wireToBda); break; } else { wireFromBdaCL = wireFromBdaCL.getParent(); } } //if we are here, it means the wireToBdaCL is root classloader, loading java.xx classes. All other bdas should be accessible to this new bda. if (wireFromBdaCL == wireToBdaCL) { wireFromBda.addBeanDeploymentArchive(wireToBda); } }
java
private void makeWiring(WebSphereBeanDeploymentArchive wireFromBda, WebSphereBeanDeploymentArchive wireToBda, ClassLoader wireToBdaCL, ClassLoader wireFromBdaCL) { while (wireFromBdaCL != null) { if (wireFromBdaCL == wireToBdaCL) { wireFromBda.addBeanDeploymentArchive(wireToBda); break; } else { wireFromBdaCL = wireFromBdaCL.getParent(); } } //if we are here, it means the wireToBdaCL is root classloader, loading java.xx classes. All other bdas should be accessible to this new bda. if (wireFromBdaCL == wireToBdaCL) { wireFromBda.addBeanDeploymentArchive(wireToBda); } }
[ "private", "void", "makeWiring", "(", "WebSphereBeanDeploymentArchive", "wireFromBda", ",", "WebSphereBeanDeploymentArchive", "wireToBda", ",", "ClassLoader", "wireToBdaCL", ",", "ClassLoader", "wireFromBdaCL", ")", "{", "while", "(", "wireFromBdaCL", "!=", "null", ")", ...
Make a wiring from the wireFromBda to the wireToBda if the wireFromBda's classloader is the descendant of the wireToBda's classloader @param wireFromBda @param wireToBda @param wireToBdaCL @param wireFromBdaCL
[ "Make", "a", "wiring", "from", "the", "wireFromBda", "to", "the", "wireToBda", "if", "the", "wireFromBda", "s", "classloader", "is", "the", "descendant", "of", "the", "wireToBda", "s", "classloader" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.cdi.weld/src/com/ibm/ws/cdi/impl/weld/WebSphereCDIDeploymentImpl.java#L428-L441
citrusframework/citrus
modules/citrus-zookeeper/src/main/java/com/consol/citrus/zookeeper/server/ZooServer.java
ZooServer.getServerFactory
public ServerCnxnFactory getServerFactory() { if (serverFactory == null) { try { serverFactory = new NIOServerCnxnFactory(); serverFactory.configure(new InetSocketAddress(port), 5000); } catch (IOException e) { throw new CitrusRuntimeException("Failed to create default zookeeper server factory", e); } } return serverFactory; }
java
public ServerCnxnFactory getServerFactory() { if (serverFactory == null) { try { serverFactory = new NIOServerCnxnFactory(); serverFactory.configure(new InetSocketAddress(port), 5000); } catch (IOException e) { throw new CitrusRuntimeException("Failed to create default zookeeper server factory", e); } } return serverFactory; }
[ "public", "ServerCnxnFactory", "getServerFactory", "(", ")", "{", "if", "(", "serverFactory", "==", "null", ")", "{", "try", "{", "serverFactory", "=", "new", "NIOServerCnxnFactory", "(", ")", ";", "serverFactory", ".", "configure", "(", "new", "InetSocketAddres...
Gets the value of the serverFactory property. @return the serverFactory
[ "Gets", "the", "value", "of", "the", "serverFactory", "property", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-zookeeper/src/main/java/com/consol/citrus/zookeeper/server/ZooServer.java#L58-L69
GeoLatte/geolatte-common
src/main/java/org/geolatte/common/dataformats/json/jackson/JsonMapper.java
JsonMapper.fromJson
public synchronized <T> T fromJson(String jsonString, Class<T> clazz) throws JsonException { if (jsonString == null) { return null; } Reader reader = new StringReader(jsonString); try { return mapper.readValue(reader, clazz); } catch (JsonParseException e) { throw new JsonException(e.getMessage(), e); } catch (JsonMappingException e) { throw new JsonException(e.getMessage(), e); } catch (IOException e) { throw new JsonException(e.getMessage(), e); } }
java
public synchronized <T> T fromJson(String jsonString, Class<T> clazz) throws JsonException { if (jsonString == null) { return null; } Reader reader = new StringReader(jsonString); try { return mapper.readValue(reader, clazz); } catch (JsonParseException e) { throw new JsonException(e.getMessage(), e); } catch (JsonMappingException e) { throw new JsonException(e.getMessage(), e); } catch (IOException e) { throw new JsonException(e.getMessage(), e); } }
[ "public", "synchronized", "<", "T", ">", "T", "fromJson", "(", "String", "jsonString", ",", "Class", "<", "T", ">", "clazz", ")", "throws", "JsonException", "{", "if", "(", "jsonString", "==", "null", ")", "{", "return", "null", ";", "}", "Reader", "re...
Converts a given string into an object of the given class. @param clazz The class to which the returned object should belong @param jsonString the jsonstring representing the object to be parsed @param <T> the type of the returned object @return an instantiated object of class T corresponding to the given jsonstring @throws JsonException If deserialization failed or if the object of class T could for some reason not be constructed.
[ "Converts", "a", "given", "string", "into", "an", "object", "of", "the", "given", "class", "." ]
train
https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/jackson/JsonMapper.java#L150-L165
deeplearning4j/deeplearning4j
datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkUtils.java
SparkUtils.writeAnalysisHTMLToFile
public static void writeAnalysisHTMLToFile(String outputPath, DataAnalysis dataAnalysis, JavaSparkContext sc) { try { String analysisAsHtml = HtmlAnalysis.createHtmlAnalysisString(dataAnalysis); writeStringToFile(outputPath, analysisAsHtml, sc); } catch (Exception e) { throw new RuntimeException("Error generating or writing HTML analysis file (normalized data)", e); } }
java
public static void writeAnalysisHTMLToFile(String outputPath, DataAnalysis dataAnalysis, JavaSparkContext sc) { try { String analysisAsHtml = HtmlAnalysis.createHtmlAnalysisString(dataAnalysis); writeStringToFile(outputPath, analysisAsHtml, sc); } catch (Exception e) { throw new RuntimeException("Error generating or writing HTML analysis file (normalized data)", e); } }
[ "public", "static", "void", "writeAnalysisHTMLToFile", "(", "String", "outputPath", ",", "DataAnalysis", "dataAnalysis", ",", "JavaSparkContext", "sc", ")", "{", "try", "{", "String", "analysisAsHtml", "=", "HtmlAnalysis", ".", "createHtmlAnalysisString", "(", "dataAn...
Write a DataAnalysis to HDFS (or locally) as a HTML file @param outputPath Output path @param dataAnalysis Analysis to generate HTML file for @param sc Spark context
[ "Write", "a", "DataAnalysis", "to", "HDFS", "(", "or", "locally", ")", "as", "a", "HTML", "file" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-spark/src/main/java/org/datavec/spark/transform/utils/SparkUtils.java#L238-L245
exoplatform/jcr
exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java
GroovyScript2RestLoader.addScript
@POST @Consumes({"script/groovy"}) @Path("add/{repository}/{workspace}/{path:.*}") public Response addScript(InputStream stream, @Context UriInfo uriInfo, @PathParam("repository") String repository, @PathParam("workspace") String workspace, @PathParam("path") String path) { Session ses = null; try { ses = sessionProviderService.getSessionProvider(null).getSession(workspace, repositoryService.getRepository(repository)); Node node = (Node)ses.getItem(getPath(path)); createScript(node, getName(path), false, stream); ses.save(); URI location = uriInfo.getBaseUriBuilder().path(getClass(), "getScript").build(repository, workspace, path); return Response.created(location).build(); } catch (PathNotFoundException e) { String msg = "Path " + path + " does not exists"; LOG.error(msg); return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build(); } catch (Exception e) { LOG.error(e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()) .type(MediaType.TEXT_PLAIN).build(); } finally { if (ses != null) { ses.logout(); } } }
java
@POST @Consumes({"script/groovy"}) @Path("add/{repository}/{workspace}/{path:.*}") public Response addScript(InputStream stream, @Context UriInfo uriInfo, @PathParam("repository") String repository, @PathParam("workspace") String workspace, @PathParam("path") String path) { Session ses = null; try { ses = sessionProviderService.getSessionProvider(null).getSession(workspace, repositoryService.getRepository(repository)); Node node = (Node)ses.getItem(getPath(path)); createScript(node, getName(path), false, stream); ses.save(); URI location = uriInfo.getBaseUriBuilder().path(getClass(), "getScript").build(repository, workspace, path); return Response.created(location).build(); } catch (PathNotFoundException e) { String msg = "Path " + path + " does not exists"; LOG.error(msg); return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build(); } catch (Exception e) { LOG.error(e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()) .type(MediaType.TEXT_PLAIN).build(); } finally { if (ses != null) { ses.logout(); } } }
[ "@", "POST", "@", "Consumes", "(", "{", "\"script/groovy\"", "}", ")", "@", "Path", "(", "\"add/{repository}/{workspace}/{path:.*}\"", ")", "public", "Response", "addScript", "(", "InputStream", "stream", ",", "@", "Context", "UriInfo", "uriInfo", ",", "@", "Pat...
This method is useful for clients that can send script in request body without form-data. At required to set specific Content-type header 'script/groovy'. @param stream the stream that contains groovy source code @param uriInfo see javax.ws.rs.core.UriInfo @param repository repository name @param workspace workspace name @param path path to resource to be created @return Response with status 'created' @request {code} "stream" : the input stream that contains groovy source code {code} @LevelAPI Provisional
[ "This", "method", "is", "useful", "for", "clients", "that", "can", "send", "script", "in", "request", "body", "without", "form", "-", "data", ".", "At", "required", "to", "set", "specific", "Content", "-", "type", "header", "script", "/", "groovy", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java#L742-L779
reactor/reactor-netty
src/main/java/reactor/netty/udp/UdpServer.java
UdpServer.doOnBound
public final UdpServer doOnBound(Consumer<? super Connection> doOnBound) { Objects.requireNonNull(doOnBound, "doOnBound"); return new UdpServerDoOn(this, null, doOnBound, null); }
java
public final UdpServer doOnBound(Consumer<? super Connection> doOnBound) { Objects.requireNonNull(doOnBound, "doOnBound"); return new UdpServerDoOn(this, null, doOnBound, null); }
[ "public", "final", "UdpServer", "doOnBound", "(", "Consumer", "<", "?", "super", "Connection", ">", "doOnBound", ")", "{", "Objects", ".", "requireNonNull", "(", "doOnBound", ",", "\"doOnBound\"", ")", ";", "return", "new", "UdpServerDoOn", "(", "this", ",", ...
Setup a callback called when {@link io.netty.channel.Channel} is bound. @param doOnBound a consumer observing server started event @return a new {@link UdpServer}
[ "Setup", "a", "callback", "called", "when", "{", "@link", "io", ".", "netty", ".", "channel", ".", "Channel", "}", "is", "bound", "." ]
train
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/udp/UdpServer.java#L194-L197
BeholderTAF/beholder-selenium
src/main/java/br/ufmg/dcc/saotome/beholder/selenium/listener/ScreenshotListener.java
ScreenshotListener.createFile
private File createFile(ITestResult tr, File parentFolder) { String path; if (tr != null) { // tr is null only on tests purpose path = String.format("%s%c%s.png", parentFolder.getAbsolutePath(), File.separatorChar, tr.getName(), getDateSuffix()); } else { path = String.format("%s%ctest_%d.png", parentFolder.getAbsolutePath(), File.separatorChar, System.currentTimeMillis()); } return new File(path); }
java
private File createFile(ITestResult tr, File parentFolder) { String path; if (tr != null) { // tr is null only on tests purpose path = String.format("%s%c%s.png", parentFolder.getAbsolutePath(), File.separatorChar, tr.getName(), getDateSuffix()); } else { path = String.format("%s%ctest_%d.png", parentFolder.getAbsolutePath(), File.separatorChar, System.currentTimeMillis()); } return new File(path); }
[ "private", "File", "createFile", "(", "ITestResult", "tr", ",", "File", "parentFolder", ")", "{", "String", "path", ";", "if", "(", "tr", "!=", "null", ")", "{", "// tr is null only on tests purpose", "path", "=", "String", ".", "format", "(", "\"%s%c%s.png\""...
Generate the file to save the screenshot taken. @param tr Test Result @param parentFolder Screenshot Folder @return Screenshot Folder
[ "Generate", "the", "file", "to", "save", "the", "screenshot", "taken", "." ]
train
https://github.com/BeholderTAF/beholder-selenium/blob/8dc999e74a9c3f5c09e4e68ea0ef5634cdb760ee/src/main/java/br/ufmg/dcc/saotome/beholder/selenium/listener/ScreenshotListener.java#L133-L144
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/Hierarchy.java
Hierarchy.isMonitorWait
public static boolean isMonitorWait(String methodName, String methodSig) { return "wait".equals(methodName) && ("()V".equals(methodSig) || "(J)V".equals(methodSig) || "(JI)V".equals(methodSig)); }
java
public static boolean isMonitorWait(String methodName, String methodSig) { return "wait".equals(methodName) && ("()V".equals(methodSig) || "(J)V".equals(methodSig) || "(JI)V".equals(methodSig)); }
[ "public", "static", "boolean", "isMonitorWait", "(", "String", "methodName", ",", "String", "methodSig", ")", "{", "return", "\"wait\"", ".", "equals", "(", "methodName", ")", "&&", "(", "\"()V\"", ".", "equals", "(", "methodSig", ")", "||", "\"(J)V\"", ".",...
Determine if method whose name and signature is specified is a monitor wait operation. @param methodName name of the method @param methodSig signature of the method @return true if the method is a monitor wait, false if not
[ "Determine", "if", "method", "whose", "name", "and", "signature", "is", "specified", "is", "a", "monitor", "wait", "operation", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/Hierarchy.java#L151-L153
facebookarchive/hadoop-20
src/core/org/apache/hadoop/fs/FileUtil.java
FileUtil.chmod
public static int chmod(String filename, String perm ) throws IOException, InterruptedException { return chmod(filename, perm, false); }
java
public static int chmod(String filename, String perm ) throws IOException, InterruptedException { return chmod(filename, perm, false); }
[ "public", "static", "int", "chmod", "(", "String", "filename", ",", "String", "perm", ")", "throws", "IOException", ",", "InterruptedException", "{", "return", "chmod", "(", "filename", ",", "perm", ",", "false", ")", ";", "}" ]
Change the permissions on a filename. @param filename the name of the file to change @param perm the permission string @return the exit code from the command @throws IOException @throws InterruptedException
[ "Change", "the", "permissions", "on", "a", "filename", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/fs/FileUtil.java#L741-L744
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/LocalVariable.java
LocalVariable.store
private Statement store(final Expression expr, final Optional<Label> firstVarInstruction) { expr.checkAssignableTo(resultType()); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { expr.gen(adapter); if (firstVarInstruction.isPresent()) { adapter.mark(firstVarInstruction.get()); } adapter.visitVarInsn(resultType().getOpcode(Opcodes.ISTORE), index()); } }; }
java
private Statement store(final Expression expr, final Optional<Label> firstVarInstruction) { expr.checkAssignableTo(resultType()); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { expr.gen(adapter); if (firstVarInstruction.isPresent()) { adapter.mark(firstVarInstruction.get()); } adapter.visitVarInsn(resultType().getOpcode(Opcodes.ISTORE), index()); } }; }
[ "private", "Statement", "store", "(", "final", "Expression", "expr", ",", "final", "Optional", "<", "Label", ">", "firstVarInstruction", ")", "{", "expr", ".", "checkAssignableTo", "(", "resultType", "(", ")", ")", ";", "return", "new", "Statement", "(", ")"...
Writes the value at the top of the stack to the local variable.
[ "Writes", "the", "value", "at", "the", "top", "of", "the", "stack", "to", "the", "local", "variable", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/LocalVariable.java#L146-L158
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.repairCategories
public void repairCategories(CmsDbContext dbc, CmsUUID projectId, CmsResource resource) throws CmsException { CmsObject cms = OpenCms.initCmsObject(new CmsObject(getSecurityManager(), dbc.getRequestContext())); cms.getRequestContext().setSiteRoot(""); cms.getRequestContext().setCurrentProject(readProject(dbc, projectId)); CmsCategoryService.getInstance().repairRelations(cms, resource); }
java
public void repairCategories(CmsDbContext dbc, CmsUUID projectId, CmsResource resource) throws CmsException { CmsObject cms = OpenCms.initCmsObject(new CmsObject(getSecurityManager(), dbc.getRequestContext())); cms.getRequestContext().setSiteRoot(""); cms.getRequestContext().setCurrentProject(readProject(dbc, projectId)); CmsCategoryService.getInstance().repairRelations(cms, resource); }
[ "public", "void", "repairCategories", "(", "CmsDbContext", "dbc", ",", "CmsUUID", "projectId", ",", "CmsResource", "resource", ")", "throws", "CmsException", "{", "CmsObject", "cms", "=", "OpenCms", ".", "initCmsObject", "(", "new", "CmsObject", "(", "getSecurityM...
Repairs broken categories.<p> @param dbc the database context @param projectId the project id @param resource the resource to repair the categories for @throws CmsException if something goes wrong
[ "Repairs", "broken", "categories", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L8371-L8377
knowm/XChange
xchange-bitmarket/src/main/java/org/knowm/xchange/bitmarket/BitMarketAdapters.java
BitMarketAdapters.adaptTicker
public static Ticker adaptTicker(BitMarketTicker bitMarketTicker, CurrencyPair currencyPair) { BigDecimal bid = bitMarketTicker.getBid(); BigDecimal ask = bitMarketTicker.getAsk(); BigDecimal high = bitMarketTicker.getHigh(); BigDecimal low = bitMarketTicker.getLow(); BigDecimal volume = bitMarketTicker.getVolume(); BigDecimal vwap = bitMarketTicker.getVwap(); BigDecimal last = bitMarketTicker.getLast(); return new Ticker.Builder() .currencyPair(currencyPair) .last(last) .bid(bid) .ask(ask) .high(high) .low(low) .volume(volume) .vwap(vwap) .build(); }
java
public static Ticker adaptTicker(BitMarketTicker bitMarketTicker, CurrencyPair currencyPair) { BigDecimal bid = bitMarketTicker.getBid(); BigDecimal ask = bitMarketTicker.getAsk(); BigDecimal high = bitMarketTicker.getHigh(); BigDecimal low = bitMarketTicker.getLow(); BigDecimal volume = bitMarketTicker.getVolume(); BigDecimal vwap = bitMarketTicker.getVwap(); BigDecimal last = bitMarketTicker.getLast(); return new Ticker.Builder() .currencyPair(currencyPair) .last(last) .bid(bid) .ask(ask) .high(high) .low(low) .volume(volume) .vwap(vwap) .build(); }
[ "public", "static", "Ticker", "adaptTicker", "(", "BitMarketTicker", "bitMarketTicker", ",", "CurrencyPair", "currencyPair", ")", "{", "BigDecimal", "bid", "=", "bitMarketTicker", ".", "getBid", "(", ")", ";", "BigDecimal", "ask", "=", "bitMarketTicker", ".", "get...
Adapts BitMarket ticker to Ticker. @param bitMarketTicker @param currencyPair @return
[ "Adapts", "BitMarket", "ticker", "to", "Ticker", "." ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-bitmarket/src/main/java/org/knowm/xchange/bitmarket/BitMarketAdapters.java#L67-L87
riversun/d6
src/main/java/org/riversun/d6/core/D6Crud.java
D6Crud.execInsertIgnoreDuplicate
public boolean execInsertIgnoreDuplicate(D6Model[] modelObjects) { final D6Inex includeExcludeColumnNames = null; return execInsert(modelObjects, includeExcludeColumnNames, true); }
java
public boolean execInsertIgnoreDuplicate(D6Model[] modelObjects) { final D6Inex includeExcludeColumnNames = null; return execInsert(modelObjects, includeExcludeColumnNames, true); }
[ "public", "boolean", "execInsertIgnoreDuplicate", "(", "D6Model", "[", "]", "modelObjects", ")", "{", "final", "D6Inex", "includeExcludeColumnNames", "=", "null", ";", "return", "execInsert", "(", "modelObjects", ",", "includeExcludeColumnNames", ",", "true", ")", "...
Insert the specified model object into the DB ignoring duplicated entry @param modelObjects @return true:DB operation success false:failure
[ "Insert", "the", "specified", "model", "object", "into", "the", "DB", "ignoring", "duplicated", "entry" ]
train
https://github.com/riversun/d6/blob/2798bd876b9380dbfea8182d11ad306cb1b0e114/src/main/java/org/riversun/d6/core/D6Crud.java#L489-L492
UrielCh/ovh-java-sdk
ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java
ApiOvhEmailpro.service_domain_domainName_PUT
public void service_domain_domainName_PUT(String service, String domainName, OvhDomain body) throws IOException { String qPath = "/email/pro/{service}/domain/{domainName}"; StringBuilder sb = path(qPath, service, domainName); exec(qPath, "PUT", sb.toString(), body); }
java
public void service_domain_domainName_PUT(String service, String domainName, OvhDomain body) throws IOException { String qPath = "/email/pro/{service}/domain/{domainName}"; StringBuilder sb = path(qPath, service, domainName); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "service_domain_domainName_PUT", "(", "String", "service", ",", "String", "domainName", ",", "OvhDomain", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/email/pro/{service}/domain/{domainName}\"", ";", "StringBuilder", "sb", "="...
Alter this object properties REST: PUT /email/pro/{service}/domain/{domainName} @param body [required] New object properties @param service [required] The internal name of your pro organization @param domainName [required] Domain name API beta
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java#L874-L878
alkacon/opencms-core
src/org/opencms/file/wrapper/CmsResourceWrapperXmlPage.java
CmsResourceWrapperXmlPage.getResourceForElement
private CmsResource getResourceForElement(CmsResource xmlPage, String path, int length) { CmsWrappedResource wrap = new CmsWrappedResource(xmlPage); wrap.setRootPath(path); int plainId; try { plainId = OpenCms.getResourceManager().getResourceType( CmsResourceTypePlain.getStaticTypeName()).getTypeId(); } catch (CmsLoaderException e) { // this should really never happen plainId = CmsResourceTypePlain.getStaticTypeId(); } wrap.setTypeId(plainId); wrap.setFolder(false); wrap.setLength(length); return wrap.getResource(); }
java
private CmsResource getResourceForElement(CmsResource xmlPage, String path, int length) { CmsWrappedResource wrap = new CmsWrappedResource(xmlPage); wrap.setRootPath(path); int plainId; try { plainId = OpenCms.getResourceManager().getResourceType( CmsResourceTypePlain.getStaticTypeName()).getTypeId(); } catch (CmsLoaderException e) { // this should really never happen plainId = CmsResourceTypePlain.getStaticTypeId(); } wrap.setTypeId(plainId); wrap.setFolder(false); wrap.setLength(length); return wrap.getResource(); }
[ "private", "CmsResource", "getResourceForElement", "(", "CmsResource", "xmlPage", ",", "String", "path", ",", "int", "length", ")", "{", "CmsWrappedResource", "wrap", "=", "new", "CmsWrappedResource", "(", "xmlPage", ")", ";", "wrap", ".", "setRootPath", "(", "p...
Returns a virtual resource for an element inside a locale.<p> A new (virtual) resource is created with the given path and length. The new created resource uses the values of the origin resource of the xml page where it is possible.<p> @param xmlPage the xml page resource with the element to create a virtual resource @param path the full path to set for the resource @param length the length of the element content @return a new created virtual {@link CmsResource}
[ "Returns", "a", "virtual", "resource", "for", "an", "element", "inside", "a", "locale", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/wrapper/CmsResourceWrapperXmlPage.java#L1018-L1035
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/WaitFor.java
WaitFor.httpPing
public static StartCondition httpPing(final int internalHttpPort) { return new StartCondition() { @Override public StartConditionCheck build(DockerRule currentRule) { String exposedPort = currentRule.getExposedContainerPort(Integer.toString(internalHttpPort)); String pingUrl = String.format("http://%s:%s/", currentRule.getDockerHost(), exposedPort); log.debug("new wait for condition - http ping port: {}, url: '{}'", internalHttpPort, pingUrl); return new HttpPingChecker(pingUrl, null, null); } }; }
java
public static StartCondition httpPing(final int internalHttpPort) { return new StartCondition() { @Override public StartConditionCheck build(DockerRule currentRule) { String exposedPort = currentRule.getExposedContainerPort(Integer.toString(internalHttpPort)); String pingUrl = String.format("http://%s:%s/", currentRule.getDockerHost(), exposedPort); log.debug("new wait for condition - http ping port: {}, url: '{}'", internalHttpPort, pingUrl); return new HttpPingChecker(pingUrl, null, null); } }; }
[ "public", "static", "StartCondition", "httpPing", "(", "final", "int", "internalHttpPort", ")", "{", "return", "new", "StartCondition", "(", ")", "{", "@", "Override", "public", "StartConditionCheck", "build", "(", "DockerRule", "currentRule", ")", "{", "String", ...
Wait for http endpoint availability under given <b>internal</b> container port. Given port MUST be exposed (with {@link DockerRuleBuilder#expose(String, String)} or {@link DockerRuleBuilder#publishAllPorts(boolean)}) (reachable from the test code point of view). <p> Side note: Internal port is required for convenience - rule will find matching external port or, report error at startup when given internal port was not exposed. @param internalHttpPort Http port to scan for availability. Port is scanned with HTTP HEAD method until response with error code 2xx or 3xx is returned or until timeout. Port MUST be exposed for wait to work and given port number must be internal (as seen on container, not as on host) port number.
[ "Wait", "for", "http", "endpoint", "availability", "under", "given", "<b", ">", "internal<", "/", "b", ">", "container", "port", ".", "Given", "port", "MUST", "be", "exposed", "(", "with", "{", "@link", "DockerRuleBuilder#expose", "(", "String", "String", ")...
train
https://github.com/tdomzal/junit-docker-rule/blob/5a0ba2fd095d201530d3f9e614bc5e88d0afaeb2/src/main/java/pl/domzal/junit/docker/rule/WaitFor.java#L119-L129
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/ST_AddPoint.java
ST_AddPoint.insertVertexInMultipoint
private static Geometry insertVertexInMultipoint(Geometry g, Point vertexPoint) { ArrayList<Point> geoms = new ArrayList<Point>(); for (int i = 0; i < g.getNumGeometries(); i++) { Point geom = (Point) g.getGeometryN(i); geoms.add(geom); } geoms.add(FACTORY.createPoint(new Coordinate(vertexPoint.getX(), vertexPoint.getY()))); return FACTORY.createMultiPoint(GeometryFactory.toPointArray(geoms)); }
java
private static Geometry insertVertexInMultipoint(Geometry g, Point vertexPoint) { ArrayList<Point> geoms = new ArrayList<Point>(); for (int i = 0; i < g.getNumGeometries(); i++) { Point geom = (Point) g.getGeometryN(i); geoms.add(geom); } geoms.add(FACTORY.createPoint(new Coordinate(vertexPoint.getX(), vertexPoint.getY()))); return FACTORY.createMultiPoint(GeometryFactory.toPointArray(geoms)); }
[ "private", "static", "Geometry", "insertVertexInMultipoint", "(", "Geometry", "g", ",", "Point", "vertexPoint", ")", "{", "ArrayList", "<", "Point", ">", "geoms", "=", "new", "ArrayList", "<", "Point", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0"...
Adds a Point into a MultiPoint geometry. @param g @param vertexPoint @return
[ "Adds", "a", "Point", "into", "a", "MultiPoint", "geometry", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/ST_AddPoint.java#L135-L143
facebookarchive/hadoop-20
src/core/org/apache/hadoop/metrics/MetricsServlet.java
MetricsServlet.makeMap
Map<String, Map<String, List<TagsMetricsPair>>> makeMap( Collection<MetricsContext> contexts) throws IOException { Map<String, Map<String, List<TagsMetricsPair>>> map = new TreeMap<String, Map<String, List<TagsMetricsPair>>>(); for (MetricsContext context : contexts) { Map<String, List<TagsMetricsPair>> records = new TreeMap<String, List<TagsMetricsPair>>(); map.put(context.getContextName(), records); for (Map.Entry<String, Collection<OutputRecord>> r : context.getAllRecords().entrySet()) { List<TagsMetricsPair> metricsAndTags = new ArrayList<TagsMetricsPair>(); records.put(r.getKey(), metricsAndTags); for (OutputRecord outputRecord : r.getValue()) { TagMap tagMap = outputRecord.getTagsCopy(); MetricMap metricMap = outputRecord.getMetricsCopy(); metricsAndTags.add(new TagsMetricsPair(tagMap, metricMap)); } } } return map; }
java
Map<String, Map<String, List<TagsMetricsPair>>> makeMap( Collection<MetricsContext> contexts) throws IOException { Map<String, Map<String, List<TagsMetricsPair>>> map = new TreeMap<String, Map<String, List<TagsMetricsPair>>>(); for (MetricsContext context : contexts) { Map<String, List<TagsMetricsPair>> records = new TreeMap<String, List<TagsMetricsPair>>(); map.put(context.getContextName(), records); for (Map.Entry<String, Collection<OutputRecord>> r : context.getAllRecords().entrySet()) { List<TagsMetricsPair> metricsAndTags = new ArrayList<TagsMetricsPair>(); records.put(r.getKey(), metricsAndTags); for (OutputRecord outputRecord : r.getValue()) { TagMap tagMap = outputRecord.getTagsCopy(); MetricMap metricMap = outputRecord.getMetricsCopy(); metricsAndTags.add(new TagsMetricsPair(tagMap, metricMap)); } } } return map; }
[ "Map", "<", "String", ",", "Map", "<", "String", ",", "List", "<", "TagsMetricsPair", ">", ">", ">", "makeMap", "(", "Collection", "<", "MetricsContext", ">", "contexts", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Map", "<", "String",...
Collects all metric data, and returns a map: contextName -> recordName -> [ (tag->tagValue), (metric->metricValue) ]. The values are either String or Number. The final value is implemented as a list of TagsMetricsPair.
[ "Collects", "all", "metric", "data", "and", "returns", "a", "map", ":", "contextName", "-", ">", "recordName", "-", ">", "[", "(", "tag", "-", ">", "tagValue", ")", "(", "metric", "-", ">", "metricValue", ")", "]", ".", "The", "values", "are", "eithe...
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/metrics/MetricsServlet.java#L75-L98
OpenLiberty/open-liberty
dev/com.ibm.ws.security.openidconnect.clients.common/src/com/ibm/ws/security/openidconnect/token/JsonTokenUtil.java
JsonTokenUtil.validateTokenString
public static void validateTokenString(String tokenString, String alg, @Sensitive Key key, long secondsClockSkew, boolean forSignatureOnly) throws InvalidJwtException { // alg is HS256 or RS256 which is consistent with AlgorithmIdentifiers AlgorithmConstraints algorithmConstraints = new AlgorithmConstraints(ConstraintType.WHITELIST, alg); JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder() .setSkipAllValidators() .setDisableRequireSignature() .setSkipSignatureVerification() .build(); JwtContext jwtContext = firstPassJwtConsumer.process(tokenString); JwtConsumerBuilder secondBuilder = new JwtConsumerBuilder() .setVerificationKey(key) .setJwsAlgorithmConstraints(algorithmConstraints) .setRelaxVerificationKeyValidation() // relaxes hs256 key length reqmt. to be consistent w. old net.oauth behavior .setSkipDefaultAudienceValidation(); if (forSignatureOnly) { secondBuilder.setSkipAllValidators(); } else { if (secondsClockSkew > Integer.MAX_VALUE) { // before downcasting, truncate max clock skew to 68 years if it's greater than that. secondsClockSkew = Integer.MAX_VALUE; } secondBuilder = secondBuilder.setAllowedClockSkewInSeconds((int) secondsClockSkew); } JwtConsumer secondPassJwtConsumer = secondBuilder.build(); secondPassJwtConsumer.processContext(jwtContext); }
java
public static void validateTokenString(String tokenString, String alg, @Sensitive Key key, long secondsClockSkew, boolean forSignatureOnly) throws InvalidJwtException { // alg is HS256 or RS256 which is consistent with AlgorithmIdentifiers AlgorithmConstraints algorithmConstraints = new AlgorithmConstraints(ConstraintType.WHITELIST, alg); JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder() .setSkipAllValidators() .setDisableRequireSignature() .setSkipSignatureVerification() .build(); JwtContext jwtContext = firstPassJwtConsumer.process(tokenString); JwtConsumerBuilder secondBuilder = new JwtConsumerBuilder() .setVerificationKey(key) .setJwsAlgorithmConstraints(algorithmConstraints) .setRelaxVerificationKeyValidation() // relaxes hs256 key length reqmt. to be consistent w. old net.oauth behavior .setSkipDefaultAudienceValidation(); if (forSignatureOnly) { secondBuilder.setSkipAllValidators(); } else { if (secondsClockSkew > Integer.MAX_VALUE) { // before downcasting, truncate max clock skew to 68 years if it's greater than that. secondsClockSkew = Integer.MAX_VALUE; } secondBuilder = secondBuilder.setAllowedClockSkewInSeconds((int) secondsClockSkew); } JwtConsumer secondPassJwtConsumer = secondBuilder.build(); secondPassJwtConsumer.processContext(jwtContext); }
[ "public", "static", "void", "validateTokenString", "(", "String", "tokenString", ",", "String", "alg", ",", "@", "Sensitive", "Key", "key", ",", "long", "secondsClockSkew", ",", "boolean", "forSignatureOnly", ")", "throws", "InvalidJwtException", "{", "// alg is HS2...
check Signature, iat, and exp only, which is what the old net.oauth code used to do. Will throw an exception if the token fails to validate. @param tokenString @param alg @param key @param secondsClockSkew @param forSignatureOnly @throws InvalidJwtException
[ "check", "Signature", "iat", "and", "exp", "only", "which", "is", "what", "the", "old", "net", ".", "oauth", "code", "used", "to", "do", ".", "Will", "throw", "an", "exception", "if", "the", "token", "fails", "to", "validate", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.openidconnect.clients.common/src/com/ibm/ws/security/openidconnect/token/JsonTokenUtil.java#L350-L381
JakeWharton/ActionBarSherlock
actionbarsherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.java
FloatEvaluator.evaluate
public Float evaluate(float fraction, Number startValue, Number endValue) { float startFloat = startValue.floatValue(); return startFloat + fraction * (endValue.floatValue() - startFloat); }
java
public Float evaluate(float fraction, Number startValue, Number endValue) { float startFloat = startValue.floatValue(); return startFloat + fraction * (endValue.floatValue() - startFloat); }
[ "public", "Float", "evaluate", "(", "float", "fraction", ",", "Number", "startValue", ",", "Number", "endValue", ")", "{", "float", "startFloat", "=", "startValue", ".", "floatValue", "(", ")", ";", "return", "startFloat", "+", "fraction", "*", "(", "endValu...
This function returns the result of linearly interpolating the start and end values, with <code>fraction</code> representing the proportion between the start and end values. The calculation is a simple parametric calculation: <code>result = x0 + t * (v1 - v0)</code>, where <code>x0</code> is <code>startValue</code>, <code>x1</code> is <code>endValue</code>, and <code>t</code> is <code>fraction</code>. @param fraction The fraction from the starting to the ending values @param startValue The start value; should be of type <code>float</code> or <code>Float</code> @param endValue The end value; should be of type <code>float</code> or <code>Float</code> @return A linear interpolation between the start and end values, given the <code>fraction</code> parameter.
[ "This", "function", "returns", "the", "result", "of", "linearly", "interpolating", "the", "start", "and", "end", "values", "with", "<code", ">", "fraction<", "/", "code", ">", "representing", "the", "proportion", "between", "the", "start", "and", "end", "value...
train
https://github.com/JakeWharton/ActionBarSherlock/blob/2c71339e756bcc0b1424c4525680549ba3a2dc97/actionbarsherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/FloatEvaluator.java#L38-L41
mercadopago/dx-java
src/main/java/com/mercadopago/core/MPCoreUtils.java
MPCoreUtils.getResourceFromJson
public static <T> T getResourceFromJson(Class clazz, JsonObject jsonEntity) { return (T) gson.fromJson(jsonEntity, clazz); }
java
public static <T> T getResourceFromJson(Class clazz, JsonObject jsonEntity) { return (T) gson.fromJson(jsonEntity, clazz); }
[ "public", "static", "<", "T", ">", "T", "getResourceFromJson", "(", "Class", "clazz", ",", "JsonObject", "jsonEntity", ")", "{", "return", "(", "T", ")", "gson", ".", "fromJson", "(", "jsonEntity", ",", "clazz", ")", ";", "}" ]
Static method that transforms a Json Object in a MP Resource. @param clazz Java Class type of the resource @param jsonEntity JsonObject to be transformed @param <T> @return
[ "Static", "method", "that", "transforms", "a", "Json", "Object", "in", "a", "MP", "Resource", "." ]
train
https://github.com/mercadopago/dx-java/blob/9df65a6bfb4db0c1fddd7699a5b109643961b03f/src/main/java/com/mercadopago/core/MPCoreUtils.java#L70-L72
facebook/fresco
drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java
GenericDraweeHierarchy.setChildDrawableAtIndex
private void setChildDrawableAtIndex(int index, @Nullable Drawable drawable) { if (drawable == null) { mFadeDrawable.setDrawable(index, null); return; } drawable = WrappingUtils.maybeApplyLeafRounding(drawable, mRoundingParams, mResources); getParentDrawableAtIndex(index).setDrawable(drawable); }
java
private void setChildDrawableAtIndex(int index, @Nullable Drawable drawable) { if (drawable == null) { mFadeDrawable.setDrawable(index, null); return; } drawable = WrappingUtils.maybeApplyLeafRounding(drawable, mRoundingParams, mResources); getParentDrawableAtIndex(index).setDrawable(drawable); }
[ "private", "void", "setChildDrawableAtIndex", "(", "int", "index", ",", "@", "Nullable", "Drawable", "drawable", ")", "{", "if", "(", "drawable", "==", "null", ")", "{", "mFadeDrawable", ".", "setDrawable", "(", "index", ",", "null", ")", ";", "return", ";...
Sets the drawable at the specified index while keeping the old scale type and rounding. In case the given drawable is null, scale type gets cleared too.
[ "Sets", "the", "drawable", "at", "the", "specified", "index", "while", "keeping", "the", "old", "scale", "type", "and", "rounding", ".", "In", "case", "the", "given", "drawable", "is", "null", "scale", "type", "gets", "cleared", "too", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java#L341-L348
recruit-mp/android-RMP-Appirater
library/src/main/java/jp/co/recruit_mp/android/rmp_appirater/RmpAppirater.java
RmpAppirater.setReminderClickDate
public static void setReminderClickDate(Context context, Date reminderClickDate) { final long reminderClickDateMills = ((reminderClickDate != null) ? reminderClickDate.getTime() : 0); SharedPreferences prefs = getSharedPreferences(context); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putLong(PREF_KEY_REMINDER_CLICK_DATE, reminderClickDateMills); prefsEditor.commit(); }
java
public static void setReminderClickDate(Context context, Date reminderClickDate) { final long reminderClickDateMills = ((reminderClickDate != null) ? reminderClickDate.getTime() : 0); SharedPreferences prefs = getSharedPreferences(context); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putLong(PREF_KEY_REMINDER_CLICK_DATE, reminderClickDateMills); prefsEditor.commit(); }
[ "public", "static", "void", "setReminderClickDate", "(", "Context", "context", ",", "Date", "reminderClickDate", ")", "{", "final", "long", "reminderClickDateMills", "=", "(", "(", "reminderClickDate", "!=", "null", ")", "?", "reminderClickDate", ".", "getTime", "...
Modify internal value. <p/> If you use this method, you might need to have a good understanding of this class code. @param context Context @param reminderClickDate Date of "Remind me later" button clicked.
[ "Modify", "internal", "value", ".", "<p", "/", ">", "If", "you", "use", "this", "method", "you", "might", "need", "to", "have", "a", "good", "understanding", "of", "this", "class", "code", "." ]
train
https://github.com/recruit-mp/android-RMP-Appirater/blob/14fcdf110dfb97120303f39aab1de9393e84b90a/library/src/main/java/jp/co/recruit_mp/android/rmp_appirater/RmpAppirater.java#L377-L386
blackfizz/EazeGraph
EazeGraphLibrary/src/main/java/org/eazegraph/lib/utils/Utils.java
Utils.calculatePointDiff
public static void calculatePointDiff(Point2D _P1, Point2D _P2, Point2D _Result, float _Multiplier) { float diffX = _P2.getX() - _P1.getX(); float diffY = _P2.getY() - _P1.getY(); _Result.setX(_P1.getX() + (diffX * _Multiplier)); _Result.setY(_P1.getY() + (diffY * _Multiplier)); }
java
public static void calculatePointDiff(Point2D _P1, Point2D _P2, Point2D _Result, float _Multiplier) { float diffX = _P2.getX() - _P1.getX(); float diffY = _P2.getY() - _P1.getY(); _Result.setX(_P1.getX() + (diffX * _Multiplier)); _Result.setY(_P1.getY() + (diffY * _Multiplier)); }
[ "public", "static", "void", "calculatePointDiff", "(", "Point2D", "_P1", ",", "Point2D", "_P2", ",", "Point2D", "_Result", ",", "float", "_Multiplier", ")", "{", "float", "diffX", "=", "_P2", ".", "getX", "(", ")", "-", "_P1", ".", "getX", "(", ")", ";...
Calculates the middle point between two points and multiplies its coordinates with the given smoothness _Mulitplier. @param _P1 First point @param _P2 Second point @param _Result Resulting point @param _Multiplier Smoothness multiplier
[ "Calculates", "the", "middle", "point", "between", "two", "points", "and", "multiplies", "its", "coordinates", "with", "the", "given", "smoothness", "_Mulitplier", "." ]
train
https://github.com/blackfizz/EazeGraph/blob/ce5e68ecc70e154f83bbb2fcce1a970db125c1e6/EazeGraphLibrary/src/main/java/org/eazegraph/lib/utils/Utils.java#L58-L63
vkostyukov/la4j
src/main/java/org/la4j/matrix/dense/Basic1DMatrix.java
Basic1DMatrix.fromBinary
public static Basic1DMatrix fromBinary(byte[] array) { ByteBuffer buffer = ByteBuffer.wrap(array); if (buffer.get() != MATRIX_TAG) { throw new IllegalArgumentException("Can not decode Basic1DMatrix from the given byte array."); } int rows = buffer.getInt(); int columns = buffer.getInt(); int capacity = rows * columns; double[] values = new double[capacity]; for (int i = 0; i < capacity; i++) { values[i] = buffer.getDouble(); } return new Basic1DMatrix(rows, columns, values); }
java
public static Basic1DMatrix fromBinary(byte[] array) { ByteBuffer buffer = ByteBuffer.wrap(array); if (buffer.get() != MATRIX_TAG) { throw new IllegalArgumentException("Can not decode Basic1DMatrix from the given byte array."); } int rows = buffer.getInt(); int columns = buffer.getInt(); int capacity = rows * columns; double[] values = new double[capacity]; for (int i = 0; i < capacity; i++) { values[i] = buffer.getDouble(); } return new Basic1DMatrix(rows, columns, values); }
[ "public", "static", "Basic1DMatrix", "fromBinary", "(", "byte", "[", "]", "array", ")", "{", "ByteBuffer", "buffer", "=", "ByteBuffer", ".", "wrap", "(", "array", ")", ";", "if", "(", "buffer", ".", "get", "(", ")", "!=", "MATRIX_TAG", ")", "{", "throw...
Decodes {@link Basic1DMatrix} from the given byte {@code array}. @param array the byte array representing a matrix @return a decoded matrix
[ "Decodes", "{", "@link", "Basic1DMatrix", "}", "from", "the", "given", "byte", "{", "@code", "array", "}", "." ]
train
https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/matrix/dense/Basic1DMatrix.java#L201-L218
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/services/JiraService.java
JiraService.fixJiraIssueTransitionId
private void fixJiraIssueTransitionId(Map<String, Object> properties) { if (properties != null) { Object jiraIssueTransitionId = properties.get(JIRA_ISSUE_TRANSITION_ID_PROP); if (jiraIssueTransitionId instanceof String) { if (((String)jiraIssueTransitionId).trim().isEmpty()) { properties.put(JIRA_ISSUE_TRANSITION_ID_PROP, null); } else { properties.put(JIRA_ISSUE_TRANSITION_ID_PROP, Integer.valueOf((String)jiraIssueTransitionId)); } } } }
java
private void fixJiraIssueTransitionId(Map<String, Object> properties) { if (properties != null) { Object jiraIssueTransitionId = properties.get(JIRA_ISSUE_TRANSITION_ID_PROP); if (jiraIssueTransitionId instanceof String) { if (((String)jiraIssueTransitionId).trim().isEmpty()) { properties.put(JIRA_ISSUE_TRANSITION_ID_PROP, null); } else { properties.put(JIRA_ISSUE_TRANSITION_ID_PROP, Integer.valueOf((String)jiraIssueTransitionId)); } } } }
[ "private", "void", "fixJiraIssueTransitionId", "(", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "if", "(", "properties", "!=", "null", ")", "{", "Object", "jiraIssueTransitionId", "=", "properties", ".", "get", "(", "JIRA_ISSUE_TRANSITION_I...
Make sure jiraIssueTransitionId is an integer and not an empty string. @param properties the Map holding the properties
[ "Make", "sure", "jiraIssueTransitionId", "is", "an", "integer", "and", "not", "an", "empty", "string", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/services/JiraService.java#L119-L131
azkaban/azkaban
azkaban-hadoop-security-plugin/src/main/java/azkaban/security/HadoopSecurityManager_H_2_0.java
HadoopSecurityManager_H_2_0.prefetchToken
@Override public void prefetchToken(final File tokenFile, final Props props, final Logger logger) throws HadoopSecurityManagerException { final String userToProxy = props.getString(JobProperties.USER_TO_PROXY); logger.info("Getting hadoop tokens based on props for " + userToProxy); doPrefetch(tokenFile, props, logger, userToProxy); }
java
@Override public void prefetchToken(final File tokenFile, final Props props, final Logger logger) throws HadoopSecurityManagerException { final String userToProxy = props.getString(JobProperties.USER_TO_PROXY); logger.info("Getting hadoop tokens based on props for " + userToProxy); doPrefetch(tokenFile, props, logger, userToProxy); }
[ "@", "Override", "public", "void", "prefetchToken", "(", "final", "File", "tokenFile", ",", "final", "Props", "props", ",", "final", "Logger", "logger", ")", "throws", "HadoopSecurityManagerException", "{", "final", "String", "userToProxy", "=", "props", ".", "g...
/* Gets hadoop tokens for a user to run mapred/hive jobs on a secured cluster
[ "/", "*", "Gets", "hadoop", "tokens", "for", "a", "user", "to", "run", "mapred", "/", "hive", "jobs", "on", "a", "secured", "cluster" ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-hadoop-security-plugin/src/main/java/azkaban/security/HadoopSecurityManager_H_2_0.java#L468-L475
kuujo/vertigo
core/src/main/java/net/kuujo/vertigo/cluster/manager/impl/ClusterListenerFactory.java
ClusterListenerFactory.createClusterListener
public ClusterListener createClusterListener(boolean localOnly) { if (localOnly) return new NoClusterListener(); HazelcastInstance hazelcast = getHazelcastInstance(vertx); if (hazelcast != null) { return new HazelcastClusterListener(hazelcast, vertx); } else { return new NoClusterListener(); } }
java
public ClusterListener createClusterListener(boolean localOnly) { if (localOnly) return new NoClusterListener(); HazelcastInstance hazelcast = getHazelcastInstance(vertx); if (hazelcast != null) { return new HazelcastClusterListener(hazelcast, vertx); } else { return new NoClusterListener(); } }
[ "public", "ClusterListener", "createClusterListener", "(", "boolean", "localOnly", ")", "{", "if", "(", "localOnly", ")", "return", "new", "NoClusterListener", "(", ")", ";", "HazelcastInstance", "hazelcast", "=", "getHazelcastInstance", "(", "vertx", ")", ";", "i...
Creates a cluster listener. @param localOnly Indicates whether to force the cluster to be local only. @return A new cluster listener.
[ "Creates", "a", "cluster", "listener", "." ]
train
https://github.com/kuujo/vertigo/blob/c5869dbc5fff89eb5262e83f7a81719b01a5ba6f/core/src/main/java/net/kuujo/vertigo/cluster/manager/impl/ClusterListenerFactory.java#L67-L75
ontop/ontop
core/model/src/main/java/it/unibz/inf/ontop/datalog/impl/DatalogTools.java
DatalogTools.foldBooleanConditions
public Expression foldBooleanConditions(List<Function> booleanAtoms) { if (booleanAtoms.length() == 0) return TRUE_EQ; Expression firstBooleanAtom = convertOrCastIntoBooleanAtom( booleanAtoms.head()); return booleanAtoms.tail().foldLeft(new F2<Expression, Function, Expression>() { @Override public Expression f(Expression previousAtom, Function currentAtom) { return termFactory.getFunctionAND(previousAtom, currentAtom); } }, firstBooleanAtom); }
java
public Expression foldBooleanConditions(List<Function> booleanAtoms) { if (booleanAtoms.length() == 0) return TRUE_EQ; Expression firstBooleanAtom = convertOrCastIntoBooleanAtom( booleanAtoms.head()); return booleanAtoms.tail().foldLeft(new F2<Expression, Function, Expression>() { @Override public Expression f(Expression previousAtom, Function currentAtom) { return termFactory.getFunctionAND(previousAtom, currentAtom); } }, firstBooleanAtom); }
[ "public", "Expression", "foldBooleanConditions", "(", "List", "<", "Function", ">", "booleanAtoms", ")", "{", "if", "(", "booleanAtoms", ".", "length", "(", ")", "==", "0", ")", "return", "TRUE_EQ", ";", "Expression", "firstBooleanAtom", "=", "convertOrCastIntoB...
Folds a list of boolean atoms into one AND(AND(...)) boolean atom.
[ "Folds", "a", "list", "of", "boolean", "atoms", "into", "one", "AND", "(", "AND", "(", "...", "))", "boolean", "atom", "." ]
train
https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/core/model/src/main/java/it/unibz/inf/ontop/datalog/impl/DatalogTools.java#L69-L81
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/ScreenSteps.java
ScreenSteps.startVideoCapture
@Conditioned @Et("Je commence la capture vidéo dans '(.*)'[\\.|\\?]") @And("I start video capture in '(.*)'[\\.|\\?]") public void startVideoCapture(String screenName, List<GherkinStepCondition> conditions) throws IOException, AWTException { logger.debug("I start video capture in [{}].", screenName); screenService.startVideoCapture(screenName); }
java
@Conditioned @Et("Je commence la capture vidéo dans '(.*)'[\\.|\\?]") @And("I start video capture in '(.*)'[\\.|\\?]") public void startVideoCapture(String screenName, List<GherkinStepCondition> conditions) throws IOException, AWTException { logger.debug("I start video capture in [{}].", screenName); screenService.startVideoCapture(screenName); }
[ "@", "Conditioned", "@", "Et", "(", "\"Je commence la capture vidéo dans '(.*)'[\\\\.|\\\\?]\")", "", "@", "And", "(", "\"I start video capture in '(.*)'[\\\\.|\\\\?]\"", ")", "public", "void", "startVideoCapture", "(", "String", "screenName", ",", "List", "<", "GherkinStep...
I start video capture and add to DOWNLOAD_FILES_FOLDER folder. @param screenName name of video file. @param conditions list of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}). @throws IOException if file or directory is wrong. @throws AWTException if configuration video file is wrong.
[ "I", "start", "video", "capture", "and", "add", "to", "DOWNLOAD_FILES_FOLDER", "folder", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/ScreenSteps.java#L116-L122
ironjacamar/ironjacamar
codegenerator/src/main/java/org/ironjacamar/codegenerator/code/MbeanImplCodeGen.java
MbeanImplCodeGen.writeConstructor
void writeConstructor(Definition def, Writer out, int indent) throws IOException { writeSimpleMethodSignature(out, indent, " * Default constructor", "public " + getClassName(def) + "()"); writeLeftCurlyBracket(out, indent); writeWithIndent(out, indent + 1, "this.mbeanServer = null;\n"); writeWithIndent(out, indent + 1, "this.objectName = \"" + def.getDefaultValue() + ",class=HelloWorld\";\n"); writeWithIndent(out, indent + 1, "this.registered = false;\n\n"); writeRightCurlyBracket(out, indent); writeEol(out); }
java
void writeConstructor(Definition def, Writer out, int indent) throws IOException { writeSimpleMethodSignature(out, indent, " * Default constructor", "public " + getClassName(def) + "()"); writeLeftCurlyBracket(out, indent); writeWithIndent(out, indent + 1, "this.mbeanServer = null;\n"); writeWithIndent(out, indent + 1, "this.objectName = \"" + def.getDefaultValue() + ",class=HelloWorld\";\n"); writeWithIndent(out, indent + 1, "this.registered = false;\n\n"); writeRightCurlyBracket(out, indent); writeEol(out); }
[ "void", "writeConstructor", "(", "Definition", "def", ",", "Writer", "out", ",", "int", "indent", ")", "throws", "IOException", "{", "writeSimpleMethodSignature", "(", "out", ",", "indent", ",", "\" * Default constructor\"", ",", "\"public \"", "+", "getClassName", ...
Output Constructor @param def definition @param out Writer @param indent space number @throws IOException ioException
[ "Output", "Constructor" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/MbeanImplCodeGen.java#L72-L83
wuman/orientdb-android
core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java
OUser.allow
public ORole allow(final String iResource, final int iOperation) { if (roles == null || roles.isEmpty()) throw new OSecurityAccessException(document.getDatabase().getName(), "User '" + document.field("name") + "' has no role defined"); final ORole role = checkIfAllowed(iResource, iOperation); if (role == null) throw new OSecurityAccessException(document.getDatabase().getName(), "User '" + document.field("name") + "' has no the permission to execute the operation '" + ORole.permissionToString(iOperation) + "' against the resource: " + iResource); return role; }
java
public ORole allow(final String iResource, final int iOperation) { if (roles == null || roles.isEmpty()) throw new OSecurityAccessException(document.getDatabase().getName(), "User '" + document.field("name") + "' has no role defined"); final ORole role = checkIfAllowed(iResource, iOperation); if (role == null) throw new OSecurityAccessException(document.getDatabase().getName(), "User '" + document.field("name") + "' has no the permission to execute the operation '" + ORole.permissionToString(iOperation) + "' against the resource: " + iResource); return role; }
[ "public", "ORole", "allow", "(", "final", "String", "iResource", ",", "final", "int", "iOperation", ")", "{", "if", "(", "roles", "==", "null", "||", "roles", ".", "isEmpty", "(", ")", ")", "throw", "new", "OSecurityAccessException", "(", "document", ".", ...
Checks if the user has the permission to access to the requested resource for the requested operation. @param iResource Requested resource @param iOperation Requested operation @return The role that has granted the permission if any, otherwise a OSecurityAccessException exception is raised @exception OSecurityAccessException
[ "Checks", "if", "the", "user", "has", "the", "permission", "to", "access", "to", "the", "requested", "resource", "for", "the", "requested", "operation", "." ]
train
https://github.com/wuman/orientdb-android/blob/ff9b17e4349f26168b2d0c4facb1a18cbfbe8cf0/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java#L98-L111
librato/librato-java
src/main/java/com/librato/metrics/client/Versions.java
Versions.getVersion
public static String getVersion(String path, Class<?> klass) { try { final InputStream in = klass.getClassLoader().getResourceAsStream(path); if (in != null) { try { final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = reader.readLine(); while (line != null) { if (line.startsWith("version")) { return line.split("=")[1]; } line = reader.readLine(); } } finally { in.close(); } } } catch (IOException e) { LOG.error("Could not read package version using path " + path + ":", e); } return "unknown"; }
java
public static String getVersion(String path, Class<?> klass) { try { final InputStream in = klass.getClassLoader().getResourceAsStream(path); if (in != null) { try { final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = reader.readLine(); while (line != null) { if (line.startsWith("version")) { return line.split("=")[1]; } line = reader.readLine(); } } finally { in.close(); } } } catch (IOException e) { LOG.error("Could not read package version using path " + path + ":", e); } return "unknown"; }
[ "public", "static", "String", "getVersion", "(", "String", "path", ",", "Class", "<", "?", ">", "klass", ")", "{", "try", "{", "final", "InputStream", "in", "=", "klass", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "(", "path", ")", ";",...
Attempts to get a version property from a specified resource @param path the path of the properties file resource @param klass the Class whose classloader will be used to load the resource @return the found version, "unknown" if it could not be found / determined
[ "Attempts", "to", "get", "a", "version", "property", "from", "a", "specified", "resource" ]
train
https://github.com/librato/librato-java/blob/bff7e776d4af5e978181db47f65e171ab67c1c77/src/main/java/com/librato/metrics/client/Versions.java#L29-L50
Azure/azure-sdk-for-java
datalakestore/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakestore/v2015_10_01_preview/implementation/AccountsInner.java
AccountsInner.beginUpdateAsync
public Observable<DataLakeStoreAccountInner> beginUpdateAsync(String resourceGroupName, String name, DataLakeStoreAccountInner parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, name, parameters).map(new Func1<ServiceResponse<DataLakeStoreAccountInner>, DataLakeStoreAccountInner>() { @Override public DataLakeStoreAccountInner call(ServiceResponse<DataLakeStoreAccountInner> response) { return response.body(); } }); }
java
public Observable<DataLakeStoreAccountInner> beginUpdateAsync(String resourceGroupName, String name, DataLakeStoreAccountInner parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, name, parameters).map(new Func1<ServiceResponse<DataLakeStoreAccountInner>, DataLakeStoreAccountInner>() { @Override public DataLakeStoreAccountInner call(ServiceResponse<DataLakeStoreAccountInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DataLakeStoreAccountInner", ">", "beginUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "name", ",", "DataLakeStoreAccountInner", "parameters", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", "resourceGroupName", ...
Updates the specified Data Lake Store account information. @param resourceGroupName The name of the Azure resource group that contains the Data Lake Store account. @param name The name of the Data Lake Store account to update. @param parameters Parameters supplied to update the Data Lake Store account. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DataLakeStoreAccountInner object
[ "Updates", "the", "specified", "Data", "Lake", "Store", "account", "information", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakestore/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakestore/v2015_10_01_preview/implementation/AccountsInner.java#L836-L843
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ServerConnectionPoliciesInner.java
ServerConnectionPoliciesInner.createOrUpdate
public ServerConnectionPolicyInner createOrUpdate(String resourceGroupName, String serverName, ServerConnectionType connectionType) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, connectionType).toBlocking().single().body(); }
java
public ServerConnectionPolicyInner createOrUpdate(String resourceGroupName, String serverName, ServerConnectionType connectionType) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, connectionType).toBlocking().single().body(); }
[ "public", "ServerConnectionPolicyInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "ServerConnectionType", "connectionType", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ...
Creates or updates the server's connection policy. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param connectionType The server connection type. Possible values include: 'Default', 'Proxy', 'Redirect' @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 ServerConnectionPolicyInner object if successful.
[ "Creates", "or", "updates", "the", "server", "s", "connection", "policy", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ServerConnectionPoliciesInner.java#L78-L80
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/lb/lbmetrictable_binding.java
lbmetrictable_binding.get
public static lbmetrictable_binding get(nitro_service service, String metrictable) throws Exception{ lbmetrictable_binding obj = new lbmetrictable_binding(); obj.set_metrictable(metrictable); lbmetrictable_binding response = (lbmetrictable_binding) obj.get_resource(service); return response; }
java
public static lbmetrictable_binding get(nitro_service service, String metrictable) throws Exception{ lbmetrictable_binding obj = new lbmetrictable_binding(); obj.set_metrictable(metrictable); lbmetrictable_binding response = (lbmetrictable_binding) obj.get_resource(service); return response; }
[ "public", "static", "lbmetrictable_binding", "get", "(", "nitro_service", "service", ",", "String", "metrictable", ")", "throws", "Exception", "{", "lbmetrictable_binding", "obj", "=", "new", "lbmetrictable_binding", "(", ")", ";", "obj", ".", "set_metrictable", "("...
Use this API to fetch lbmetrictable_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "lbmetrictable_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/lb/lbmetrictable_binding.java#L103-L108
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java
SDMath.setDiag
public SDVariable setDiag(String name, SDVariable in, SDVariable diag) { SDVariable ret = f().setDiag(in, diag); return updateVariableNameAndReference(ret, name); }
java
public SDVariable setDiag(String name, SDVariable in, SDVariable diag) { SDVariable ret = f().setDiag(in, diag); return updateVariableNameAndReference(ret, name); }
[ "public", "SDVariable", "setDiag", "(", "String", "name", ",", "SDVariable", "in", ",", "SDVariable", "diag", ")", "{", "SDVariable", "ret", "=", "f", "(", ")", ".", "setDiag", "(", "in", ",", "diag", ")", ";", "return", "updateVariableNameAndReference", "...
Set the diagonal value to the specified values<br> If input is<br> [ a, b, c]<br> [ d, e, f]<br> [ g, h, i]<br> and diag = [ 1, 2, 3] then output is<br> [ 1, b, c]<br> [ d, 2, f]<br> [ g, h, 3]<br> @param name Name of the output variable @param in Input variable @param diag Diagonal @return Output variable
[ "Set", "the", "diagonal", "value", "to", "the", "specified", "values<br", ">", "If", "input", "is<br", ">", "[", "a", "b", "c", "]", "<br", ">", "[", "d", "e", "f", "]", "<br", ">", "[", "g", "h", "i", "]", "<br", ">", "and", "diag", "=", "["...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java#L2073-L2076
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
FSNamesystem.addToInvalidates
private void addToInvalidates(Block b, boolean ackRequired) { StringBuilder sb = new StringBuilder(); for (Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(b); it.hasNext();) { DatanodeDescriptor node = it.next(); addToInvalidatesNoLog(b, node, ackRequired); sb.append(node.getName()); sb.append(' '); } if (isInitialized && !isInSafeMode()) { // do not log in startup phase NameNode.stateChangeLog.info("BLOCK* NameSystem.addToInvalidates: " + b.getBlockName() + " is added to invalidSet of " + sb); } }
java
private void addToInvalidates(Block b, boolean ackRequired) { StringBuilder sb = new StringBuilder(); for (Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(b); it.hasNext();) { DatanodeDescriptor node = it.next(); addToInvalidatesNoLog(b, node, ackRequired); sb.append(node.getName()); sb.append(' '); } if (isInitialized && !isInSafeMode()) { // do not log in startup phase NameNode.stateChangeLog.info("BLOCK* NameSystem.addToInvalidates: " + b.getBlockName() + " is added to invalidSet of " + sb); } }
[ "private", "void", "addToInvalidates", "(", "Block", "b", ",", "boolean", "ackRequired", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "Iterator", "<", "DatanodeDescriptor", ">", "it", "=", "blocksMap", ".", "nodeIt...
Adds block to list of blocks which will be invalidated on all its datanodes.
[ "Adds", "block", "to", "list", "of", "blocks", "which", "will", "be", "invalidated", "on", "all", "its", "datanodes", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java#L3441-L3455
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/VMath.java
VMath.almostEquals
public static boolean almostEquals(final double[] m1, final double[] m2, final double maxdelta) { if(m1 == m2) { return true; } if(m1 == null || m2 == null) { return false; } final int rowdim = m1.length; if(rowdim != m2.length) { return false; } for(int i = 0; i < rowdim; i++) { if(Math.abs(m1[i] - m2[i]) > maxdelta) { return false; } } return true; }
java
public static boolean almostEquals(final double[] m1, final double[] m2, final double maxdelta) { if(m1 == m2) { return true; } if(m1 == null || m2 == null) { return false; } final int rowdim = m1.length; if(rowdim != m2.length) { return false; } for(int i = 0; i < rowdim; i++) { if(Math.abs(m1[i] - m2[i]) > maxdelta) { return false; } } return true; }
[ "public", "static", "boolean", "almostEquals", "(", "final", "double", "[", "]", "m1", ",", "final", "double", "[", "]", "m2", ",", "final", "double", "maxdelta", ")", "{", "if", "(", "m1", "==", "m2", ")", "{", "return", "true", ";", "}", "if", "(...
Compare two matrices with a delta parameter to take numerical errors into account. @param m1 Input matrix @param m2 other matrix to compare with @param maxdelta maximum delta allowed @return true if delta smaller than maximum
[ "Compare", "two", "matrices", "with", "a", "delta", "parameter", "to", "take", "numerical", "errors", "into", "account", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/linearalgebra/VMath.java#L1771-L1788
OpenLiberty/open-liberty
dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/ThreadPoolController.java
ThreadPoolController.getSmallestValidPoolSize
private Integer getSmallestValidPoolSize(Integer poolSize, Double forecast) { Integer smallestPoolSize = threadStats.firstKey(); Integer nextPoolSize = threadStats.higherKey(smallestPoolSize); Integer pruneSize = -1; boolean validSmallData = false; while (!validSmallData && nextPoolSize != null) { ThroughputDistribution smallestPoolSizeStats = getThroughputDistribution(smallestPoolSize, false);; // prune data that is too old or outside believable range if (pruneData(smallestPoolSizeStats, forecast)) { pruneSize = smallestPoolSize; smallestPoolSize = nextPoolSize; nextPoolSize = threadStats.higherKey(smallestPoolSize); if (pruneSize > hangBufferPoolSize && pruneSize > coreThreads) { threadStats.remove(pruneSize); } } else { validSmallData = true; } } return smallestPoolSize; }
java
private Integer getSmallestValidPoolSize(Integer poolSize, Double forecast) { Integer smallestPoolSize = threadStats.firstKey(); Integer nextPoolSize = threadStats.higherKey(smallestPoolSize); Integer pruneSize = -1; boolean validSmallData = false; while (!validSmallData && nextPoolSize != null) { ThroughputDistribution smallestPoolSizeStats = getThroughputDistribution(smallestPoolSize, false);; // prune data that is too old or outside believable range if (pruneData(smallestPoolSizeStats, forecast)) { pruneSize = smallestPoolSize; smallestPoolSize = nextPoolSize; nextPoolSize = threadStats.higherKey(smallestPoolSize); if (pruneSize > hangBufferPoolSize && pruneSize > coreThreads) { threadStats.remove(pruneSize); } } else { validSmallData = true; } } return smallestPoolSize; }
[ "private", "Integer", "getSmallestValidPoolSize", "(", "Integer", "poolSize", ",", "Double", "forecast", ")", "{", "Integer", "smallestPoolSize", "=", "threadStats", ".", "firstKey", "(", ")", ";", "Integer", "nextPoolSize", "=", "threadStats", ".", "higherKey", "...
Returns the smallest valid poolSize in the current historical dataset. @param poolSize - current poolSize @param forecast - expected throughput at current poolSize @return - smallest valid poolSize found
[ "Returns", "the", "smallest", "valid", "poolSize", "in", "the", "current", "historical", "dataset", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/ThreadPoolController.java#L1609-L1629
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/super_src/org/opencms/relations/CmsCategory.java
CmsCategory.getCategoryPath
public static String getCategoryPath(String rootPath, String baseFolder) throws Exception { String base; if (rootPath.startsWith(CmsCategoryService.CENTRALIZED_REPOSITORY)) { base = CmsCategoryService.CENTRALIZED_REPOSITORY; } else { base = baseFolder; if (!base.endsWith("/")) { base += "/"; } if (!base.startsWith("/")) { base = "/" + base; } int pos = rootPath.indexOf(base); if (pos < 0) { throw new Exception("Invalid category location \"" + rootPath + "\"."); } base = rootPath.substring(0, pos + base.length()); } return rootPath.substring(base.length()); }
java
public static String getCategoryPath(String rootPath, String baseFolder) throws Exception { String base; if (rootPath.startsWith(CmsCategoryService.CENTRALIZED_REPOSITORY)) { base = CmsCategoryService.CENTRALIZED_REPOSITORY; } else { base = baseFolder; if (!base.endsWith("/")) { base += "/"; } if (!base.startsWith("/")) { base = "/" + base; } int pos = rootPath.indexOf(base); if (pos < 0) { throw new Exception("Invalid category location \"" + rootPath + "\"."); } base = rootPath.substring(0, pos + base.length()); } return rootPath.substring(base.length()); }
[ "public", "static", "String", "getCategoryPath", "(", "String", "rootPath", ",", "String", "baseFolder", ")", "throws", "Exception", "{", "String", "base", ";", "if", "(", "rootPath", ".", "startsWith", "(", "CmsCategoryService", ".", "CENTRALIZED_REPOSITORY", ")"...
Returns the category path for the given root path.<p> @param rootPath the root path @param baseFolder the categories base folder name @return the category path @throws Exception if the root path does not match the given base folder
[ "Returns", "the", "category", "path", "for", "the", "given", "root", "path", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/super_src/org/opencms/relations/CmsCategory.java#L114-L134
js-lib-com/commons
src/main/java/js/converter/EnumsConverter.java
EnumsConverter.asObject
@SuppressWarnings("rawtypes") @Override public <T> T asObject(String string, Class<T> valueType) throws IllegalArgumentException { if(string.isEmpty()) { return null; } // at this point value type is guaranteed to be enumeration if(Types.isKindOf(valueType, OrdinalEnum.class)) { return valueType.getEnumConstants()[Integer.parseInt(string)]; } return (T)Enum.valueOf((Class)valueType, string); }
java
@SuppressWarnings("rawtypes") @Override public <T> T asObject(String string, Class<T> valueType) throws IllegalArgumentException { if(string.isEmpty()) { return null; } // at this point value type is guaranteed to be enumeration if(Types.isKindOf(valueType, OrdinalEnum.class)) { return valueType.getEnumConstants()[Integer.parseInt(string)]; } return (T)Enum.valueOf((Class)valueType, string); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "@", "Override", "public", "<", "T", ">", "T", "asObject", "(", "String", "string", ",", "Class", "<", "T", ">", "valueType", ")", "throws", "IllegalArgumentException", "{", "if", "(", "string", ".", "isEm...
Create enumeration constant for given string and enumeration type. @throws IllegalArgumentException string argument is not a valid constant for given enumeration type. @throws NumberFormatException if string argument is not a valid numeric value and value type implements {@link OrdinalEnum}. @throws IndexOutOfBoundsException if value type implements {@link OrdinalEnum}, string argument is a valid number but is not in the range accepted by target enumeration.
[ "Create", "enumeration", "constant", "for", "given", "string", "and", "enumeration", "type", "." ]
train
https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/converter/EnumsConverter.java#L34-L46
hal/elemento
core/src/main/java/org/jboss/gwt/elemento/core/BodyObserver.java
BodyObserver.addAttachObserver
static void addAttachObserver(HTMLElement element, ObserverCallback callback) { if (!ready) { startObserving(); } attachObservers.add(createObserver(element, callback, ATTACH_UID_KEY)); }
java
static void addAttachObserver(HTMLElement element, ObserverCallback callback) { if (!ready) { startObserving(); } attachObservers.add(createObserver(element, callback, ATTACH_UID_KEY)); }
[ "static", "void", "addAttachObserver", "(", "HTMLElement", "element", ",", "ObserverCallback", "callback", ")", "{", "if", "(", "!", "ready", ")", "{", "startObserving", "(", ")", ";", "}", "attachObservers", ".", "add", "(", "createObserver", "(", "element", ...
Check if the observer is already started, if not it will start it, then register and callback for when the element is attached to the dom.
[ "Check", "if", "the", "observer", "is", "already", "started", "if", "not", "it", "will", "start", "it", "then", "register", "and", "callback", "for", "when", "the", "element", "is", "attached", "to", "the", "dom", "." ]
train
https://github.com/hal/elemento/blob/26da2d5a1fe2ec55b779737dbaeda25a942eee61/core/src/main/java/org/jboss/gwt/elemento/core/BodyObserver.java#L100-L105
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/detect/AnnotationIssues.java
AnnotationIssues.clearAssumptions
public static void clearAssumptions(Map<Integer, Integer> assumptionTill, int pc) { Iterator<Integer> it = assumptionTill.values().iterator(); while (it.hasNext()) { if (it.next().intValue() <= pc) { it.remove(); } } }
java
public static void clearAssumptions(Map<Integer, Integer> assumptionTill, int pc) { Iterator<Integer> it = assumptionTill.values().iterator(); while (it.hasNext()) { if (it.next().intValue() <= pc) { it.remove(); } } }
[ "public", "static", "void", "clearAssumptions", "(", "Map", "<", "Integer", ",", "Integer", ">", "assumptionTill", ",", "int", "pc", ")", "{", "Iterator", "<", "Integer", ">", "it", "=", "assumptionTill", ".", "values", "(", ")", ".", "iterator", "(", ")...
the map is keyed by register, and value by when an assumption holds to a byte offset if we have passed when the assumption holds, clear the item from the map @param assumptionTill the map of assumptions @param pc // * the current pc
[ "the", "map", "is", "keyed", "by", "register", "and", "value", "by", "when", "an", "assumption", "holds", "to", "a", "byte", "offset", "if", "we", "have", "passed", "when", "the", "assumption", "holds", "clear", "the", "item", "from", "the", "map" ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/AnnotationIssues.java#L396-L403
apache/incubator-heron
eco-heron-examples/src/java/org/apache/heron/examples/eco/StatefulRandomIntSpout.java
StatefulRandomIntSpout.open
@Override public void open(Map<String, Object> map, TopologyContext ctx, SpoutOutputCollector collector) { spoutOutputCollector = collector; }
java
@Override public void open(Map<String, Object> map, TopologyContext ctx, SpoutOutputCollector collector) { spoutOutputCollector = collector; }
[ "@", "Override", "public", "void", "open", "(", "Map", "<", "String", ",", "Object", ">", "map", ",", "TopologyContext", "ctx", ",", "SpoutOutputCollector", "collector", ")", "{", "spoutOutputCollector", "=", "collector", ";", "}" ]
These three methods are required to extend the BaseRichSpout abstract class
[ "These", "three", "methods", "are", "required", "to", "extend", "the", "BaseRichSpout", "abstract", "class" ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/eco-heron-examples/src/java/org/apache/heron/examples/eco/StatefulRandomIntSpout.java#L61-L64
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/internal/DefaultURLRewriter.java
DefaultURLRewriter.getAjaxUrl
public AjaxUrlInfo getAjaxUrl(ServletContext servletContext, ServletRequest request, Object nameable) { HttpServletRequest req = (HttpServletRequest) request; // the default behavior is to set the parameter as the nameable's name or null String name = null; if (nameable instanceof INameable) name = ((INameable) nameable).getObjectName(); String path = req.getServletPath(); int idx = path.lastIndexOf('/'); if (idx != -1) { path = "/" + path.substring(1, idx); } path = req.getContextPath() + path; return new AjaxUrlInfo(path,name); }
java
public AjaxUrlInfo getAjaxUrl(ServletContext servletContext, ServletRequest request, Object nameable) { HttpServletRequest req = (HttpServletRequest) request; // the default behavior is to set the parameter as the nameable's name or null String name = null; if (nameable instanceof INameable) name = ((INameable) nameable).getObjectName(); String path = req.getServletPath(); int idx = path.lastIndexOf('/'); if (idx != -1) { path = "/" + path.substring(1, idx); } path = req.getContextPath() + path; return new AjaxUrlInfo(path,name); }
[ "public", "AjaxUrlInfo", "getAjaxUrl", "(", "ServletContext", "servletContext", ",", "ServletRequest", "request", ",", "Object", "nameable", ")", "{", "HttpServletRequest", "req", "=", "(", "HttpServletRequest", ")", "request", ";", "// the default behavior is to set the ...
This method will get the prefix for all URLs that are used for AJAX processing @param servletContext the current ServletContext. @param request the current ServletRequest. @param nameable the INamable object that will handle the request
[ "This", "method", "will", "get", "the", "prefix", "for", "all", "URLs", "that", "are", "used", "for", "AJAX", "processing" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/internal/DefaultURLRewriter.java#L51-L67
elastic/elasticsearch-hadoop
mr/src/main/java/org/elasticsearch/hadoop/serialization/bulk/AbstractBulkFactory.java
AbstractBulkFactory.getMetadataExtractorOrFallback
protected FieldExtractor getMetadataExtractorOrFallback(Metadata meta, FieldExtractor fallbackExtractor) { if (metaExtractor != null) { FieldExtractor metaFE = metaExtractor.get(meta); if (metaFE != null) { return metaFE; } } return fallbackExtractor; }
java
protected FieldExtractor getMetadataExtractorOrFallback(Metadata meta, FieldExtractor fallbackExtractor) { if (metaExtractor != null) { FieldExtractor metaFE = metaExtractor.get(meta); if (metaFE != null) { return metaFE; } } return fallbackExtractor; }
[ "protected", "FieldExtractor", "getMetadataExtractorOrFallback", "(", "Metadata", "meta", ",", "FieldExtractor", "fallbackExtractor", ")", "{", "if", "(", "metaExtractor", "!=", "null", ")", "{", "FieldExtractor", "metaFE", "=", "metaExtractor", ".", "get", "(", "me...
Get the extractor for a given field, trying first one from a MetadataExtractor, and failing that, falling back to the provided 'static' one
[ "Get", "the", "extractor", "for", "a", "given", "field", "trying", "first", "one", "from", "a", "MetadataExtractor", "and", "failing", "that", "falling", "back", "to", "the", "provided", "static", "one" ]
train
https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/mr/src/main/java/org/elasticsearch/hadoop/serialization/bulk/AbstractBulkFactory.java#L491-L499
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/constraint/CAmong.java
CAmong.getGroup
public int getGroup(Node n, List<Collection<Node>> grps) { int i = 0; for (Collection<Node> pGrp : grps) { if (pGrp.contains(n)) { return i; } i++; } return -1; }
java
public int getGroup(Node n, List<Collection<Node>> grps) { int i = 0; for (Collection<Node> pGrp : grps) { if (pGrp.contains(n)) { return i; } i++; } return -1; }
[ "public", "int", "getGroup", "(", "Node", "n", ",", "List", "<", "Collection", "<", "Node", ">", ">", "grps", ")", "{", "int", "i", "=", "0", ";", "for", "(", "Collection", "<", "Node", ">", "pGrp", ":", "grps", ")", "{", "if", "(", "pGrp", "."...
Get the group the node belong to. @param n the node @return the group identifier, {@code -1} if the node does not belong to a group
[ "Get", "the", "group", "the", "node", "belong", "to", "." ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/constraint/CAmong.java#L181-L190
lamydev/Android-Notification
core/src/zemin/notification/NotificationBoard.java
NotificationBoard.setInitialTouchArea
public void setInitialTouchArea(int l, int t, int r, int b) { mContentView.setTouchToOpen(l, t, r, b); }
java
public void setInitialTouchArea(int l, int t, int r, int b) { mContentView.setTouchToOpen(l, t, r, b); }
[ "public", "void", "setInitialTouchArea", "(", "int", "l", ",", "int", "t", ",", "int", "r", ",", "int", "b", ")", "{", "mContentView", ".", "setTouchToOpen", "(", "l", ",", "t", ",", "r", ",", "b", ")", ";", "}" ]
Set the touch area where the user can touch to pull the board down. @param l @param t @param r @param b
[ "Set", "the", "touch", "area", "where", "the", "user", "can", "touch", "to", "pull", "the", "board", "down", "." ]
train
https://github.com/lamydev/Android-Notification/blob/6d6571d2862cb6edbacf9a78125418f7d621c3f8/core/src/zemin/notification/NotificationBoard.java#L544-L546
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapreduce/lib/output/FileOutputCommitter.java
FileOutputCommitter.getFinalPath
private Path getFinalPath(Path jobOutputDir, Path taskOutput, Path taskOutputPath) throws IOException { URI taskOutputUri = taskOutput.toUri(); URI relativePath = taskOutputPath.toUri().relativize(taskOutputUri); if (taskOutputUri == relativePath) { throw new IOException("Can not get the relative path: base = " + taskOutputPath + " child = " + taskOutput); } if (relativePath.getPath().length() > 0) { return new Path(jobOutputDir, relativePath.getPath()); } else { return jobOutputDir; } }
java
private Path getFinalPath(Path jobOutputDir, Path taskOutput, Path taskOutputPath) throws IOException { URI taskOutputUri = taskOutput.toUri(); URI relativePath = taskOutputPath.toUri().relativize(taskOutputUri); if (taskOutputUri == relativePath) { throw new IOException("Can not get the relative path: base = " + taskOutputPath + " child = " + taskOutput); } if (relativePath.getPath().length() > 0) { return new Path(jobOutputDir, relativePath.getPath()); } else { return jobOutputDir; } }
[ "private", "Path", "getFinalPath", "(", "Path", "jobOutputDir", ",", "Path", "taskOutput", ",", "Path", "taskOutputPath", ")", "throws", "IOException", "{", "URI", "taskOutputUri", "=", "taskOutput", ".", "toUri", "(", ")", ";", "URI", "relativePath", "=", "ta...
Find the final name of a given output file, given the job output directory and the work directory. @param jobOutputDir the job's output directory @param taskOutput the specific task output file @param taskOutputPath the job's work directory @return the final path for the specific output file @throws IOException
[ "Find", "the", "final", "name", "of", "a", "given", "output", "file", "given", "the", "job", "output", "directory", "and", "the", "work", "directory", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapreduce/lib/output/FileOutputCommitter.java#L248-L261
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/query/FieldCriteria.java
FieldCriteria.buildNotLessCriteria
static FieldCriteria buildNotLessCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, NOT_LESS, anAlias); }
java
static FieldCriteria buildNotLessCriteria(Object anAttribute, Object aValue, UserAlias anAlias) { return new FieldCriteria(anAttribute, aValue, NOT_LESS, anAlias); }
[ "static", "FieldCriteria", "buildNotLessCriteria", "(", "Object", "anAttribute", ",", "Object", "aValue", ",", "UserAlias", "anAlias", ")", "{", "return", "new", "FieldCriteria", "(", "anAttribute", ",", "aValue", ",", "NOT_LESS", ",", "anAlias", ")", ";", "}" ]
static FieldCriteria buildNotLessCriteria(Object anAttribute, Object aValue, String anAlias)
[ "static", "FieldCriteria", "buildNotLessCriteria", "(", "Object", "anAttribute", "Object", "aValue", "String", "anAlias", ")" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/FieldCriteria.java#L63-L66
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscCompilationJobsInner.java
DscCompilationJobsInner.getStream
public JobStreamInner getStream(String resourceGroupName, String automationAccountName, UUID jobId, String jobStreamId) { return getStreamWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId, jobStreamId).toBlocking().single().body(); }
java
public JobStreamInner getStream(String resourceGroupName, String automationAccountName, UUID jobId, String jobStreamId) { return getStreamWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId, jobStreamId).toBlocking().single().body(); }
[ "public", "JobStreamInner", "getStream", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "UUID", "jobId", ",", "String", "jobStreamId", ")", "{", "return", "getStreamWithServiceResponseAsync", "(", "resourceGroupName", ",", "automationAcco...
Retrieve the job stream identified by job stream id. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param jobId The job id. @param jobStreamId The job stream id. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the JobStreamInner object if successful.
[ "Retrieve", "the", "job", "stream", "identified", "by", "job", "stream", "id", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/DscCompilationJobsInner.java#L530-L532
beangle/beangle3
struts/s2/src/main/java/org/beangle/struts2/view/component/Component.java
Component.findString
protected String findString(String expr, String field, String errorMsg) { if (expr == null) { throw fieldError(field, errorMsg, null); } else { return findString(expr); } }
java
protected String findString(String expr, String field, String errorMsg) { if (expr == null) { throw fieldError(field, errorMsg, null); } else { return findString(expr); } }
[ "protected", "String", "findString", "(", "String", "expr", ",", "String", "field", ",", "String", "errorMsg", ")", "{", "if", "(", "expr", "==", "null", ")", "{", "throw", "fieldError", "(", "field", ",", "errorMsg", ",", "null", ")", ";", "}", "else"...
Evaluates the OGNL stack to find a String value. <p/> If the given expression is <tt>null</tt/> a error is logged and a <code>RuntimeException</code> is thrown constructed with a messaged based on the given field and errorMsg paramter. @param expr OGNL expression. @param field field name used when throwing <code>RuntimeException</code>. @param errorMsg error message used when throwing <code>RuntimeException</code> . @return the String value found. @throws StrutsException is thrown in case of expression is <tt>null</tt>.
[ "Evaluates", "the", "OGNL", "stack", "to", "find", "a", "String", "value", ".", "<p", "/", ">", "If", "the", "given", "expression", "is", "<tt", ">", "null<", "/", "tt", "/", ">", "a", "error", "is", "logged", "and", "a", "<code", ">", "RuntimeExcept...
train
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/struts/s2/src/main/java/org/beangle/struts2/view/component/Component.java#L184-L190
netty/netty
codec-http2/src/main/java/io/netty/handler/codec/http2/HttpConversionUtil.java
HttpConversionUtil.toHttpResponse
public static HttpResponse toHttpResponse(final int streamId, final Http2Headers http2Headers, final boolean validateHttpHeaders) throws Http2Exception { final HttpResponseStatus status = parseStatus(http2Headers.status()); // HTTP/2 does not define a way to carry the version or reason phrase that is included in an // HTTP/1.1 status line. final HttpResponse msg = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status, validateHttpHeaders); try { addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, true); } catch (final Http2Exception e) { throw e; } catch (final Throwable t) { throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error"); } return msg; }
java
public static HttpResponse toHttpResponse(final int streamId, final Http2Headers http2Headers, final boolean validateHttpHeaders) throws Http2Exception { final HttpResponseStatus status = parseStatus(http2Headers.status()); // HTTP/2 does not define a way to carry the version or reason phrase that is included in an // HTTP/1.1 status line. final HttpResponse msg = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status, validateHttpHeaders); try { addHttp2ToHttpHeaders(streamId, http2Headers, msg.headers(), msg.protocolVersion(), false, true); } catch (final Http2Exception e) { throw e; } catch (final Throwable t) { throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error"); } return msg; }
[ "public", "static", "HttpResponse", "toHttpResponse", "(", "final", "int", "streamId", ",", "final", "Http2Headers", "http2Headers", ",", "final", "boolean", "validateHttpHeaders", ")", "throws", "Http2Exception", "{", "final", "HttpResponseStatus", "status", "=", "pa...
Create a new object to contain the response data. @param streamId The stream associated with the response @param http2Headers The initial set of HTTP/2 headers to create the response with @param validateHttpHeaders <ul> <li>{@code true} to validate HTTP headers in the http-codec</li> <li>{@code false} not to validate HTTP headers in the http-codec</li> </ul> @return A new response object which represents headers for a chunked response @throws Http2Exception see {@link #addHttp2ToHttpHeaders(int, Http2Headers, HttpHeaders, HttpVersion, boolean, boolean)}
[ "Create", "a", "new", "object", "to", "contain", "the", "response", "data", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/HttpConversionUtil.java#L312-L327
actorapp/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/encryption/KeyManagerActor.java
KeyManagerActor.fetchUserPreKey
private Promise<PublicKey> fetchUserPreKey(final int uid, final int keyGroupId) { return pickUserGroup(uid, keyGroupId) .flatMap(new Function<Tuple2<UserKeysGroup, UserKeys>, Promise<PublicKey>>() { @Override public Promise<PublicKey> apply(final Tuple2<UserKeysGroup, UserKeys> keyGroups) { return api(new RequestLoadPrePublicKeys(new ApiUserOutPeer(uid, getUser(uid).getAccessHash()), keyGroupId)) .map(new Function<ResponsePublicKeys, PublicKey>() { @Override public PublicKey apply(ResponsePublicKeys response) { if (response.getPublicKey().size() == 0) { throw new RuntimeException("User doesn't have pre keys"); } ApiEncryptionKey key = response.getPublicKey().get(0); ApiEncryptionKeySignature sig = null; for (ApiEncryptionKeySignature s : response.getSignatures()) { if (s.getKeyId() == key.getKeyId() && "Ed25519".equals(s.getSignatureAlg())) { sig = s; break; } } if (sig == null) { throw new RuntimeException("Unable to find public key on server"); } byte[] keyHash = RatchetKeySignature.hashForSignature(key.getKeyId(), key.getKeyAlg(), key.getKeyMaterial()); if (!Curve25519.verifySignature(keyGroups.getT1().getIdentityKey().getPublicKey(), keyHash, sig.getSignature())) { throw new RuntimeException("Key signature does not isMatch"); } return new PublicKey(key.getKeyId(), key.getKeyAlg(), key.getKeyMaterial()); } }); } }); }
java
private Promise<PublicKey> fetchUserPreKey(final int uid, final int keyGroupId) { return pickUserGroup(uid, keyGroupId) .flatMap(new Function<Tuple2<UserKeysGroup, UserKeys>, Promise<PublicKey>>() { @Override public Promise<PublicKey> apply(final Tuple2<UserKeysGroup, UserKeys> keyGroups) { return api(new RequestLoadPrePublicKeys(new ApiUserOutPeer(uid, getUser(uid).getAccessHash()), keyGroupId)) .map(new Function<ResponsePublicKeys, PublicKey>() { @Override public PublicKey apply(ResponsePublicKeys response) { if (response.getPublicKey().size() == 0) { throw new RuntimeException("User doesn't have pre keys"); } ApiEncryptionKey key = response.getPublicKey().get(0); ApiEncryptionKeySignature sig = null; for (ApiEncryptionKeySignature s : response.getSignatures()) { if (s.getKeyId() == key.getKeyId() && "Ed25519".equals(s.getSignatureAlg())) { sig = s; break; } } if (sig == null) { throw new RuntimeException("Unable to find public key on server"); } byte[] keyHash = RatchetKeySignature.hashForSignature(key.getKeyId(), key.getKeyAlg(), key.getKeyMaterial()); if (!Curve25519.verifySignature(keyGroups.getT1().getIdentityKey().getPublicKey(), keyHash, sig.getSignature())) { throw new RuntimeException("Key signature does not isMatch"); } return new PublicKey(key.getKeyId(), key.getKeyAlg(), key.getKeyMaterial()); } }); } }); }
[ "private", "Promise", "<", "PublicKey", ">", "fetchUserPreKey", "(", "final", "int", "uid", ",", "final", "int", "keyGroupId", ")", "{", "return", "pickUserGroup", "(", "uid", ",", "keyGroupId", ")", ".", "flatMap", "(", "new", "Function", "<", "Tuple2", "...
Fetching user's random pre key @param uid User's id @param keyGroupId User's key group id
[ "Fetching", "user", "s", "random", "pre", "key" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/encryption/KeyManagerActor.java#L391-L428
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/refer/DependencyResolver.java
DependencyResolver.getRequired
public <T> List<T> getRequired(Class<T> type, String name) throws ReferenceException { Object locator = find(name); if (locator == null) throw new ReferenceException(null, name); return _references.getRequired(type, locator); }
java
public <T> List<T> getRequired(Class<T> type, String name) throws ReferenceException { Object locator = find(name); if (locator == null) throw new ReferenceException(null, name); return _references.getRequired(type, locator); }
[ "public", "<", "T", ">", "List", "<", "T", ">", "getRequired", "(", "Class", "<", "T", ">", "type", ",", "String", "name", ")", "throws", "ReferenceException", "{", "Object", "locator", "=", "find", "(", "name", ")", ";", "if", "(", "locator", "==", ...
Gets all required dependencies by their name. At least one dependency must present. If no dependencies was found it throws a ReferenceException @param type the Class type that defined the type of the result. @param name the dependency name to locate. @return a list with found dependencies. @throws ReferenceException when no single component reference is found
[ "Gets", "all", "required", "dependencies", "by", "their", "name", ".", "At", "least", "one", "dependency", "must", "present", ".", "If", "no", "dependencies", "was", "found", "it", "throws", "a", "ReferenceException" ]
train
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/refer/DependencyResolver.java#L213-L219