repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapper.java
DefaultIncrementalAttributesMapper.lookupAttributes
public static Attributes lookupAttributes(LdapOperations ldapOperations, Name dn, String[] attributes) { return loopForAllAttributeValues(ldapOperations, dn, attributes).getCollectedAttributes(); }
java
public static Attributes lookupAttributes(LdapOperations ldapOperations, Name dn, String[] attributes) { return loopForAllAttributeValues(ldapOperations, dn, attributes).getCollectedAttributes(); }
[ "public", "static", "Attributes", "lookupAttributes", "(", "LdapOperations", "ldapOperations", ",", "Name", "dn", ",", "String", "[", "]", "attributes", ")", "{", "return", "loopForAllAttributeValues", "(", "ldapOperations", ",", "dn", ",", "attributes", ")", ".",...
Lookup all values for the specified attributes, looping through the results incrementally if necessary. @param ldapOperations The instance to use for performing the actual lookup. @param dn The distinguished name of the object to find. @param attributes names of the attributes to request. @return an Attributes instance, populated with all found values for the requested attributes. Never <code>null</code>, though the actual attributes may not be set if they was not set on the requested object.
[ "Lookup", "all", "values", "for", "the", "specified", "attributes", "looping", "through", "the", "results", "incrementally", "if", "necessary", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapper.java#L304-L306
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerFactoryBean.java
ConverterManagerFactoryBean.getObject
public Object getObject() throws Exception { if (converterConfigList==null) { throw new FactoryBeanNotInitializedException("converterConfigList has not been set"); } ConverterManagerImpl result = new ConverterManagerImpl(); for (ConverterConfig converterConfig : converterConfigList) { if (converterConfig.fromClasses==null || converterConfig.toClasses==null || converterConfig.converter==null) { throw new FactoryBeanNotInitializedException( String.format("All of fromClasses, toClasses and converter must be specified in bean %1$s", converterConfig.toString())); } for (Class<?> fromClass : converterConfig.fromClasses) { for (Class<?> toClass : converterConfig.toClasses) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Adding converter from %1$s to %2$s", fromClass, toClass)); } result.addConverter(fromClass, converterConfig.syntax, toClass, converterConfig.converter); } } } return result; }
java
public Object getObject() throws Exception { if (converterConfigList==null) { throw new FactoryBeanNotInitializedException("converterConfigList has not been set"); } ConverterManagerImpl result = new ConverterManagerImpl(); for (ConverterConfig converterConfig : converterConfigList) { if (converterConfig.fromClasses==null || converterConfig.toClasses==null || converterConfig.converter==null) { throw new FactoryBeanNotInitializedException( String.format("All of fromClasses, toClasses and converter must be specified in bean %1$s", converterConfig.toString())); } for (Class<?> fromClass : converterConfig.fromClasses) { for (Class<?> toClass : converterConfig.toClasses) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Adding converter from %1$s to %2$s", fromClass, toClass)); } result.addConverter(fromClass, converterConfig.syntax, toClass, converterConfig.converter); } } } return result; }
[ "public", "Object", "getObject", "(", ")", "throws", "Exception", "{", "if", "(", "converterConfigList", "==", "null", ")", "{", "throw", "new", "FactoryBeanNotInitializedException", "(", "\"converterConfigList has not been set\"", ")", ";", "}", "ConverterManagerImpl",...
Creates a ConverterManagerImpl populating it with Converter instances from the converterConfigList property. @return The newly created {@link org.springframework.ldap.odm.typeconversion.ConverterManager}. @throws ClassNotFoundException Thrown if any of the classes to be converted to or from cannot be found. @see org.springframework.beans.factory.FactoryBean#getObject()
[ "Creates", "a", "ConverterManagerImpl", "populating", "it", "with", "Converter", "instances", "from", "the", "converterConfigList", "property", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerFactoryBean.java#L169-L194
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/core/DirContextAdapter.java
DirContextAdapter.setAttribute
public void setAttribute(Attribute attribute) { if (!updateMode) { originalAttrs.put(attribute); } else { updatedAttrs.put(attribute); } }
java
public void setAttribute(Attribute attribute) { if (!updateMode) { originalAttrs.put(attribute); } else { updatedAttrs.put(attribute); } }
[ "public", "void", "setAttribute", "(", "Attribute", "attribute", ")", "{", "if", "(", "!", "updateMode", ")", "{", "originalAttrs", ".", "put", "(", "attribute", ")", ";", "}", "else", "{", "updatedAttrs", ".", "put", "(", "attribute", ")", ";", "}", "...
Set the supplied attribute. @param attribute the attribute to set.
[ "Set", "the", "supplied", "attribute", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/core/DirContextAdapter.java#L812-L819
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/pool/DelegatingLdapContext.java
DelegatingLdapContext.getInnermostDelegateLdapContext
public LdapContext getInnermostDelegateLdapContext() { final LdapContext delegateLdapContext = this.getDelegateLdapContext(); if (delegateLdapContext instanceof DelegatingLdapContext) { return ((DelegatingLdapContext)delegateLdapContext).getInnermostDelegateLdapContext(); } return delegateLdapContext; }
java
public LdapContext getInnermostDelegateLdapContext() { final LdapContext delegateLdapContext = this.getDelegateLdapContext(); if (delegateLdapContext instanceof DelegatingLdapContext) { return ((DelegatingLdapContext)delegateLdapContext).getInnermostDelegateLdapContext(); } return delegateLdapContext; }
[ "public", "LdapContext", "getInnermostDelegateLdapContext", "(", ")", "{", "final", "LdapContext", "delegateLdapContext", "=", "this", ".", "getDelegateLdapContext", "(", ")", ";", "if", "(", "delegateLdapContext", "instanceof", "DelegatingLdapContext", ")", "{", "retur...
Recursivley inspect delegates until a non-delegating ldap context is found. @return The innermost (real) DirContext that is being delegated to.
[ "Recursivley", "inspect", "delegates", "until", "a", "non", "-", "delegating", "ldap", "context", "is", "found", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/pool/DelegatingLdapContext.java#L74-L82
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/pool2/factory/PooledContextSource.java
PooledContextSource.getContext
protected DirContext getContext(DirContextType dirContextType) { final DirContext dirContext; try { dirContext = (DirContext) this.keyedObjectPool.borrowObject(dirContextType); } catch (Exception e) { throw new DataAccessResourceFailureException("Failed to borrow DirContext from pool.", e); } if (dirContext instanceof LdapContext) { return new DelegatingLdapContext(this.keyedObjectPool, (LdapContext) dirContext, dirContextType); } return new DelegatingDirContext(this.keyedObjectPool, dirContext, dirContextType); }
java
protected DirContext getContext(DirContextType dirContextType) { final DirContext dirContext; try { dirContext = (DirContext) this.keyedObjectPool.borrowObject(dirContextType); } catch (Exception e) { throw new DataAccessResourceFailureException("Failed to borrow DirContext from pool.", e); } if (dirContext instanceof LdapContext) { return new DelegatingLdapContext(this.keyedObjectPool, (LdapContext) dirContext, dirContextType); } return new DelegatingDirContext(this.keyedObjectPool, dirContext, dirContextType); }
[ "protected", "DirContext", "getContext", "(", "DirContextType", "dirContextType", ")", "{", "final", "DirContext", "dirContext", ";", "try", "{", "dirContext", "=", "(", "DirContext", ")", "this", ".", "keyedObjectPool", ".", "borrowObject", "(", "dirContextType", ...
Gets a DirContext of the specified type from the keyed object pool. @param dirContextType The type of context to return. @return A wrapped DirContext of the specified type. @throws DataAccessResourceFailureException If retrieving the object from the pool throws an exception
[ "Gets", "a", "DirContext", "of", "the", "specified", "type", "from", "the", "keyed", "object", "pool", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/pool2/factory/PooledContextSource.java#L257-L271
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/support/LdapEncoder.java
LdapEncoder.filterEncode
public static String filterEncode(String value) { if (value == null) return null; // make buffer roomy StringBuilder encodedValue = new StringBuilder(value.length() * 2); int length = value.length(); for (int i = 0; i < length; i++) { char c = value.charAt(i); if (c < FILTER_ESCAPE_TABLE.length) { encodedValue.append(FILTER_ESCAPE_TABLE[c]); } else { // default: add the char encodedValue.append(c); } } return encodedValue.toString(); }
java
public static String filterEncode(String value) { if (value == null) return null; // make buffer roomy StringBuilder encodedValue = new StringBuilder(value.length() * 2); int length = value.length(); for (int i = 0; i < length; i++) { char c = value.charAt(i); if (c < FILTER_ESCAPE_TABLE.length) { encodedValue.append(FILTER_ESCAPE_TABLE[c]); } else { // default: add the char encodedValue.append(c); } } return encodedValue.toString(); }
[ "public", "static", "String", "filterEncode", "(", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "return", "null", ";", "// make buffer roomy\r", "StringBuilder", "encodedValue", "=", "new", "StringBuilder", "(", "value", ".", "length", "...
Escape a value for use in a filter. @param value the value to escape. @return a properly escaped representation of the supplied value.
[ "Escape", "a", "value", "for", "use", "in", "a", "filter", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java#L99-L122
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/support/LdapEncoder.java
LdapEncoder.nameEncode
public static String nameEncode(String value) { if (value == null) return null; // make buffer roomy StringBuilder encodedValue = new StringBuilder(value.length() * 2); int length = value.length(); int last = length - 1; for (int i = 0; i < length; i++) { char c = value.charAt(i); // space first or last if (c == ' ' && (i == 0 || i == last)) { encodedValue.append("\\ "); continue; } if (c < NAME_ESCAPE_TABLE.length) { // check in table for escapes String esc = NAME_ESCAPE_TABLE[c]; if (esc != null) { encodedValue.append(esc); continue; } } // default: add the char encodedValue.append(c); } return encodedValue.toString(); }
java
public static String nameEncode(String value) { if (value == null) return null; // make buffer roomy StringBuilder encodedValue = new StringBuilder(value.length() * 2); int length = value.length(); int last = length - 1; for (int i = 0; i < length; i++) { char c = value.charAt(i); // space first or last if (c == ' ' && (i == 0 || i == last)) { encodedValue.append("\\ "); continue; } if (c < NAME_ESCAPE_TABLE.length) { // check in table for escapes String esc = NAME_ESCAPE_TABLE[c]; if (esc != null) { encodedValue.append(esc); continue; } } // default: add the char encodedValue.append(c); } return encodedValue.toString(); }
[ "public", "static", "String", "nameEncode", "(", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "return", "null", ";", "// make buffer roomy\r", "StringBuilder", "encodedValue", "=", "new", "StringBuilder", "(", "value", ".", "length", "("...
LDAP Encodes a value for use with a DN. Escapes for LDAP, not JNDI! <br>Escapes:<br> ' ' [space] - "\ " [if first or last] <br> '#' [hash] - "\#" <br> ',' [comma] - "\," <br> ';' [semicolon] - "\;" <br> '= [equals] - "\=" <br> '+' [plus] - "\+" <br> '&lt;' [less than] - "\&lt;" <br> '&gt;' [greater than] - "\&gt;" <br> '"' [double quote] - "\"" <br> '\' [backslash] - "\\" <br> @param value the value to escape. @return The escaped value.
[ "LDAP", "Encodes", "a", "value", "for", "use", "with", "a", "DN", ".", "Escapes", "for", "LDAP", "not", "JNDI!" ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java#L137-L174
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/support/LdapEncoder.java
LdapEncoder.nameDecode
static public String nameDecode(String value) throws BadLdapGrammarException { if (value == null) return null; // make buffer same size StringBuilder decoded = new StringBuilder(value.length()); int i = 0; while (i < value.length()) { char currentChar = value.charAt(i); if (currentChar == '\\') { if (value.length() <= i + 1) { // Ending with a single backslash is not allowed throw new BadLdapGrammarException( "Unexpected end of value " + "unterminated '\\'"); } else { char nextChar = value.charAt(i + 1); if (nextChar == ',' || nextChar == '=' || nextChar == '+' || nextChar == '<' || nextChar == '>' || nextChar == '#' || nextChar == ';' || nextChar == '\\' || nextChar == '\"' || nextChar == ' ') { // Normal backslash escape decoded.append(nextChar); i += 2; } else { if (value.length() <= i + 2) { throw new BadLdapGrammarException( "Unexpected end of value " + "expected special or hex, found '" + nextChar + "'"); } else { // This should be a hex value String hexString = "" + nextChar + value.charAt(i + 2); decoded.append((char) Integer.parseInt(hexString, HEX)); i += 3; } } } } else { // This character wasn't escaped - just append it decoded.append(currentChar); i++; } } return decoded.toString(); }
java
static public String nameDecode(String value) throws BadLdapGrammarException { if (value == null) return null; // make buffer same size StringBuilder decoded = new StringBuilder(value.length()); int i = 0; while (i < value.length()) { char currentChar = value.charAt(i); if (currentChar == '\\') { if (value.length() <= i + 1) { // Ending with a single backslash is not allowed throw new BadLdapGrammarException( "Unexpected end of value " + "unterminated '\\'"); } else { char nextChar = value.charAt(i + 1); if (nextChar == ',' || nextChar == '=' || nextChar == '+' || nextChar == '<' || nextChar == '>' || nextChar == '#' || nextChar == ';' || nextChar == '\\' || nextChar == '\"' || nextChar == ' ') { // Normal backslash escape decoded.append(nextChar); i += 2; } else { if (value.length() <= i + 2) { throw new BadLdapGrammarException( "Unexpected end of value " + "expected special or hex, found '" + nextChar + "'"); } else { // This should be a hex value String hexString = "" + nextChar + value.charAt(i + 2); decoded.append((char) Integer.parseInt(hexString, HEX)); i += 3; } } } } else { // This character wasn't escaped - just append it decoded.append(currentChar); i++; } } return decoded.toString(); }
[ "static", "public", "String", "nameDecode", "(", "String", "value", ")", "throws", "BadLdapGrammarException", "{", "if", "(", "value", "==", "null", ")", "return", "null", ";", "// make buffer same size\r", "StringBuilder", "decoded", "=", "new", "StringBuilder", ...
Decodes a value. Converts escaped chars to ordinary chars. @param value Trimmed value, so no leading an trailing blanks, except an escaped space last. @return The decoded value as a string. @throws BadLdapGrammarException
[ "Decodes", "a", "value", ".", "Converts", "escaped", "chars", "to", "ordinary", "chars", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java#L185-L237
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/support/LdapEncoder.java
LdapEncoder.printBase64Binary
public static String printBase64Binary(byte[] val) { Assert.notNull(val, "val must not be null!"); String encoded = DatatypeConverter.printBase64Binary(val); int length = encoded.length(); StringBuilder sb = new StringBuilder(length + length / RFC2849_MAX_BASE64_CHARS_PER_LINE); for (int i = 0, len = length; i < len; i++) { sb.append(encoded.charAt(i)); if ((i + 1) % RFC2849_MAX_BASE64_CHARS_PER_LINE == 0) { sb.append('\n'); sb.append(' '); } } return sb.toString(); }
java
public static String printBase64Binary(byte[] val) { Assert.notNull(val, "val must not be null!"); String encoded = DatatypeConverter.printBase64Binary(val); int length = encoded.length(); StringBuilder sb = new StringBuilder(length + length / RFC2849_MAX_BASE64_CHARS_PER_LINE); for (int i = 0, len = length; i < len; i++) { sb.append(encoded.charAt(i)); if ((i + 1) % RFC2849_MAX_BASE64_CHARS_PER_LINE == 0) { sb.append('\n'); sb.append(' '); } } return sb.toString(); }
[ "public", "static", "String", "printBase64Binary", "(", "byte", "[", "]", "val", ")", "{", "Assert", ".", "notNull", "(", "val", ",", "\"val must not be null!\"", ")", ";", "String", "encoded", "=", "DatatypeConverter", ".", "printBase64Binary", "(", "val", ")...
Converts an array of bytes into a Base64 encoded string according to the rules for converting LDAP Attributes in RFC2849. @param val @return A string containing a lexical representation of base64Binary wrapped around 76 characters. @throws IllegalArgumentException if <tt>val</tt> is null.
[ "Converts", "an", "array", "of", "bytes", "into", "a", "Base64", "encoded", "string", "according", "to", "the", "rules", "for", "converting", "LDAP", "Attributes", "in", "RFC2849", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java#L247-L266
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/support/LdapEncoder.java
LdapEncoder.parseBase64Binary
public static byte[] parseBase64Binary(String val) { Assert.notNull(val, "val must not be null!"); int length = val.length(); StringBuilder sb = new StringBuilder(length); for (int i = 0, len = length; i < len; i++) { char c = val.charAt(i); if(c == '\n'){ if(i + 1 < len && val.charAt(i + 1) == ' ') { i++; } continue; } sb.append(c); } return DatatypeConverter.parseBase64Binary(sb.toString()); }
java
public static byte[] parseBase64Binary(String val) { Assert.notNull(val, "val must not be null!"); int length = val.length(); StringBuilder sb = new StringBuilder(length); for (int i = 0, len = length; i < len; i++) { char c = val.charAt(i); if(c == '\n'){ if(i + 1 < len && val.charAt(i + 1) == ' ') { i++; } continue; } sb.append(c); } return DatatypeConverter.parseBase64Binary(sb.toString()); }
[ "public", "static", "byte", "[", "]", "parseBase64Binary", "(", "String", "val", ")", "{", "Assert", ".", "notNull", "(", "val", ",", "\"val must not be null!\"", ")", ";", "int", "length", "=", "val", ".", "length", "(", ")", ";", "StringBuilder", "sb", ...
Converts the Base64 encoded string argument into an array of bytes. @param val @return An array of bytes represented by the string argument. @throws IllegalArgumentException if <tt>val</tt> is null or does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:base64Binary.
[ "Converts", "the", "Base64", "encoded", "string", "argument", "into", "an", "array", "of", "bytes", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java#L276-L297
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/control/AbstractFallbackRequestAndResponseControlDirContextProcessor.java
AbstractFallbackRequestAndResponseControlDirContextProcessor.invokeMethod
protected Object invokeMethod(String method, Class<?> clazz, Object control) { Method actualMethod = ReflectionUtils.findMethod(clazz, method); return ReflectionUtils.invokeMethod(actualMethod, control); }
java
protected Object invokeMethod(String method, Class<?> clazz, Object control) { Method actualMethod = ReflectionUtils.findMethod(clazz, method); return ReflectionUtils.invokeMethod(actualMethod, control); }
[ "protected", "Object", "invokeMethod", "(", "String", "method", ",", "Class", "<", "?", ">", "clazz", ",", "Object", "control", ")", "{", "Method", "actualMethod", "=", "ReflectionUtils", ".", "findMethod", "(", "clazz", ",", "method", ")", ";", "return", ...
Utility method for invoking a method on a Control. @param method name of method to invoke @param clazz Class of the object that the method should be invoked on @param control Instance that the method should be invoked on @return the invocation result, if any
[ "Utility", "method", "for", "invoking", "a", "method", "on", "a", "Control", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/control/AbstractFallbackRequestAndResponseControlDirContextProcessor.java#L147-L150
train
spring-projects/spring-ldap
samples/user-admin/src/main/java/org/springframework/ldap/samples/useradmin/service/UserService.java
UserService.findAllMembers
public Set<User> findAllMembers(Iterable<Name> absoluteIds) { return Sets.newLinkedHashSet(userRepo.findAll(toRelativeIds(absoluteIds))); }
java
public Set<User> findAllMembers(Iterable<Name> absoluteIds) { return Sets.newLinkedHashSet(userRepo.findAll(toRelativeIds(absoluteIds))); }
[ "public", "Set", "<", "User", ">", "findAllMembers", "(", "Iterable", "<", "Name", ">", "absoluteIds", ")", "{", "return", "Sets", ".", "newLinkedHashSet", "(", "userRepo", ".", "findAll", "(", "toRelativeIds", "(", "absoluteIds", ")", ")", ")", ";", "}" ]
This method expects absolute DNs of group members. In order to find the actual users the DNs need to have the base LDAP path removed. @param absoluteIds @return
[ "This", "method", "expects", "absolute", "DNs", "of", "group", "members", ".", "In", "order", "to", "find", "the", "actual", "users", "the", "DNs", "need", "to", "have", "the", "base", "LDAP", "path", "removed", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/samples/user-admin/src/main/java/org/springframework/ldap/samples/useradmin/service/UserService.java#L99-L101
train
spring-projects/spring-ldap
samples/user-admin/src/main/java/org/springframework/ldap/samples/useradmin/service/UserService.java
UserService.updateUserStandard
private User updateUserStandard(LdapName originalId, User existingUser) { User savedUser = userRepo.save(existingUser); if(!originalId.equals(savedUser.getId())) { // The user has moved - we need to update group references. LdapName oldMemberDn = toAbsoluteDn(originalId); LdapName newMemberDn = toAbsoluteDn(savedUser.getId()); Collection<Group> groups = groupRepo.findByMember(oldMemberDn); updateGroupReferences(groups, oldMemberDn, newMemberDn); } return savedUser; }
java
private User updateUserStandard(LdapName originalId, User existingUser) { User savedUser = userRepo.save(existingUser); if(!originalId.equals(savedUser.getId())) { // The user has moved - we need to update group references. LdapName oldMemberDn = toAbsoluteDn(originalId); LdapName newMemberDn = toAbsoluteDn(savedUser.getId()); Collection<Group> groups = groupRepo.findByMember(oldMemberDn); updateGroupReferences(groups, oldMemberDn, newMemberDn); } return savedUser; }
[ "private", "User", "updateUserStandard", "(", "LdapName", "originalId", ",", "User", "existingUser", ")", "{", "User", "savedUser", "=", "userRepo", ".", "save", "(", "existingUser", ")", ";", "if", "(", "!", "originalId", ".", "equals", "(", "savedUser", "....
Update the user and - if its id changed - update all group references to the user. @param originalId the original id of the user. @param existingUser the user, populated with new data @return the updated entry
[ "Update", "the", "user", "and", "-", "if", "its", "id", "changed", "-", "update", "all", "group", "references", "to", "the", "user", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/samples/user-admin/src/main/java/org/springframework/ldap/samples/useradmin/service/UserService.java#L141-L153
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorder.java
ModifyAttributesOperationRecorder.getCompensatingModificationItem
protected ModificationItem getCompensatingModificationItem( Attributes originalAttributes, ModificationItem modificationItem) { Attribute modificationAttribute = modificationItem.getAttribute(); Attribute originalAttribute = originalAttributes .get(modificationAttribute.getID()); if (modificationItem.getModificationOp() == DirContext.REMOVE_ATTRIBUTE) { if (modificationAttribute.size() == 0) { // If the modification attribute size it means that the // Attribute should be removed entirely - we should store a // ModificationItem to restore all present values for rollback. return new ModificationItem(DirContext.ADD_ATTRIBUTE, (Attribute) originalAttribute.clone()); } else { // The rollback modification will be to re-add the removed // attribute values. return new ModificationItem(DirContext.ADD_ATTRIBUTE, (Attribute) modificationAttribute.clone()); } } else if (modificationItem.getModificationOp() == DirContext.REPLACE_ATTRIBUTE) { if (originalAttribute != null) { return new ModificationItem(DirContext.REPLACE_ATTRIBUTE, (Attribute) originalAttribute.clone()); } else { // The attribute doesn't previously exist - the rollback // operation will be to remove the attribute. return new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(modificationAttribute.getID())); } } else { // An ADD_ATTRIBUTE operation if (originalAttribute == null) { // The attribute doesn't previously exist - the rollback // operation will be to remove the attribute. return new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(modificationAttribute.getID())); } else { // The attribute does exist before - we should store the // previous value and it should be used for replacing in // rollback. return new ModificationItem(DirContext.REPLACE_ATTRIBUTE, (Attribute) originalAttribute.clone()); } } }
java
protected ModificationItem getCompensatingModificationItem( Attributes originalAttributes, ModificationItem modificationItem) { Attribute modificationAttribute = modificationItem.getAttribute(); Attribute originalAttribute = originalAttributes .get(modificationAttribute.getID()); if (modificationItem.getModificationOp() == DirContext.REMOVE_ATTRIBUTE) { if (modificationAttribute.size() == 0) { // If the modification attribute size it means that the // Attribute should be removed entirely - we should store a // ModificationItem to restore all present values for rollback. return new ModificationItem(DirContext.ADD_ATTRIBUTE, (Attribute) originalAttribute.clone()); } else { // The rollback modification will be to re-add the removed // attribute values. return new ModificationItem(DirContext.ADD_ATTRIBUTE, (Attribute) modificationAttribute.clone()); } } else if (modificationItem.getModificationOp() == DirContext.REPLACE_ATTRIBUTE) { if (originalAttribute != null) { return new ModificationItem(DirContext.REPLACE_ATTRIBUTE, (Attribute) originalAttribute.clone()); } else { // The attribute doesn't previously exist - the rollback // operation will be to remove the attribute. return new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(modificationAttribute.getID())); } } else { // An ADD_ATTRIBUTE operation if (originalAttribute == null) { // The attribute doesn't previously exist - the rollback // operation will be to remove the attribute. return new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(modificationAttribute.getID())); } else { // The attribute does exist before - we should store the // previous value and it should be used for replacing in // rollback. return new ModificationItem(DirContext.REPLACE_ATTRIBUTE, (Attribute) originalAttribute.clone()); } } }
[ "protected", "ModificationItem", "getCompensatingModificationItem", "(", "Attributes", "originalAttributes", ",", "ModificationItem", "modificationItem", ")", "{", "Attribute", "modificationAttribute", "=", "modificationItem", ".", "getAttribute", "(", ")", ";", "Attribute", ...
Get a ModificationItem to use for rollback of the supplied modification. @param originalAttributes All Attributes of the target DN that are affected of any of the ModificationItems. @param modificationItem the ModificationItem to create a rollback item for. @return A ModificationItem to use for rollback of the supplied ModificationItem.
[ "Get", "a", "ModificationItem", "to", "use", "for", "rollback", "of", "the", "supplied", "modification", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorder.java#L119-L163
train
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/support/ListComparator.java
ListComparator.compare
public int compare(Object o1, Object o2) { List list1 = (List) o1; List list2 = (List) o2; for (int i = 0; i < list1.size(); i++) { if (list2.size() > i) { Comparable component1 = (Comparable) list1.get(i); Comparable component2 = (Comparable) list2.get(i); int componentsCompared = component1.compareTo(component2); if (componentsCompared != 0) { return componentsCompared; } } else { // First instance has more components, so that instance is // greater. return 1; } } // All components so far are equal - if the other instance has // more components it is greater otherwise they are equal. if (list2.size() > list1.size()) { return -1; } else { return 0; } }
java
public int compare(Object o1, Object o2) { List list1 = (List) o1; List list2 = (List) o2; for (int i = 0; i < list1.size(); i++) { if (list2.size() > i) { Comparable component1 = (Comparable) list1.get(i); Comparable component2 = (Comparable) list2.get(i); int componentsCompared = component1.compareTo(component2); if (componentsCompared != 0) { return componentsCompared; } } else { // First instance has more components, so that instance is // greater. return 1; } } // All components so far are equal - if the other instance has // more components it is greater otherwise they are equal. if (list2.size() > list1.size()) { return -1; } else { return 0; } }
[ "public", "int", "compare", "(", "Object", "o1", ",", "Object", "o2", ")", "{", "List", "list1", "=", "(", "List", ")", "o1", ";", "List", "list2", "=", "(", "List", ")", "o2", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "list1", "....
Compare two lists of Comparable objects. @param o1 the first object to be compared. @param o2 the second object to be compared. @throws ClassCastException if any of the lists contains an object that is not Comparable.
[ "Compare", "two", "lists", "of", "Comparable", "objects", "." ]
15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/support/ListComparator.java#L38-L66
train
p6spy/p6spy
src/main/java/com/p6spy/engine/common/PreparedStatementInformation.java
PreparedStatementInformation.getSqlWithValues
@Override public String getSqlWithValues() { final StringBuilder sb = new StringBuilder(); final String statementQuery = getStatementQuery(); // iterate over the characters in the query replacing the parameter placeholders // with the actual values int currentParameter = 0; for( int pos = 0; pos < statementQuery.length(); pos ++) { char character = statementQuery.charAt(pos); if( statementQuery.charAt(pos) == '?' && currentParameter <= parameterValues.size()) { // replace with parameter value Value value = parameterValues.get(currentParameter); sb.append(value != null ? value.toString() : new Value().toString()); currentParameter++; } else { sb.append(character); } } return sb.toString(); }
java
@Override public String getSqlWithValues() { final StringBuilder sb = new StringBuilder(); final String statementQuery = getStatementQuery(); // iterate over the characters in the query replacing the parameter placeholders // with the actual values int currentParameter = 0; for( int pos = 0; pos < statementQuery.length(); pos ++) { char character = statementQuery.charAt(pos); if( statementQuery.charAt(pos) == '?' && currentParameter <= parameterValues.size()) { // replace with parameter value Value value = parameterValues.get(currentParameter); sb.append(value != null ? value.toString() : new Value().toString()); currentParameter++; } else { sb.append(character); } } return sb.toString(); }
[ "@", "Override", "public", "String", "getSqlWithValues", "(", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "final", "String", "statementQuery", "=", "getStatementQuery", "(", ")", ";", "// iterate over the characters in the q...
Generates the query for the prepared statement with all parameter placeholders replaced with the actual parameter values @return the SQL
[ "Generates", "the", "query", "for", "the", "prepared", "statement", "with", "all", "parameter", "placeholders", "replaced", "with", "the", "actual", "parameter", "values" ]
c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2
https://github.com/p6spy/p6spy/blob/c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2/src/main/java/com/p6spy/engine/common/PreparedStatementInformation.java#L43-L64
train
p6spy/p6spy
src/main/java/com/p6spy/engine/common/P6LogQuery.java
P6LogQuery.doLogElapsed
protected static void doLogElapsed(int connectionId, long timeElapsedNanos, Category category, String prepared, String sql, String url) { doLog(connectionId, timeElapsedNanos, category, prepared, sql, url); }
java
protected static void doLogElapsed(int connectionId, long timeElapsedNanos, Category category, String prepared, String sql, String url) { doLog(connectionId, timeElapsedNanos, category, prepared, sql, url); }
[ "protected", "static", "void", "doLogElapsed", "(", "int", "connectionId", ",", "long", "timeElapsedNanos", ",", "Category", "category", ",", "String", "prepared", ",", "String", "sql", ",", "String", "url", ")", "{", "doLog", "(", "connectionId", ",", "timeEl...
this is an internal method called by logElapsed
[ "this", "is", "an", "internal", "method", "called", "by", "logElapsed" ]
c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2
https://github.com/p6spy/p6spy/blob/c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2/src/main/java/com/p6spy/engine/common/P6LogQuery.java#L90-L92
train
p6spy/p6spy
src/main/java/com/p6spy/engine/common/P6LogQuery.java
P6LogQuery.doLog
protected static void doLog(int connectionId, long elapsedNanos, Category category, String prepared, String sql, String url) { // give it one more try if not initialized yet if (logger == null) { initialize(); if (logger == null) { return; } } final String format = P6SpyOptions.getActiveInstance().getDateformat(); final String stringNow; if (format == null) { stringNow = Long.toString(System.currentTimeMillis()); } else { stringNow = new SimpleDateFormat(format).format(new java.util.Date()).trim(); } logger.logSQL(connectionId, stringNow, TimeUnit.NANOSECONDS.toMillis(elapsedNanos), category, prepared, sql, url); final boolean stackTrace = P6SpyOptions.getActiveInstance().getStackTrace(); if (stackTrace) { final String stackTraceClass = P6SpyOptions.getActiveInstance().getStackTraceClass(); Exception e = new Exception(); if (stackTraceClass != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String stack = sw.toString(); if (stack.indexOf(stackTraceClass) == -1) { e = null; } } if (e != null) { logger.logException(e); } } }
java
protected static void doLog(int connectionId, long elapsedNanos, Category category, String prepared, String sql, String url) { // give it one more try if not initialized yet if (logger == null) { initialize(); if (logger == null) { return; } } final String format = P6SpyOptions.getActiveInstance().getDateformat(); final String stringNow; if (format == null) { stringNow = Long.toString(System.currentTimeMillis()); } else { stringNow = new SimpleDateFormat(format).format(new java.util.Date()).trim(); } logger.logSQL(connectionId, stringNow, TimeUnit.NANOSECONDS.toMillis(elapsedNanos), category, prepared, sql, url); final boolean stackTrace = P6SpyOptions.getActiveInstance().getStackTrace(); if (stackTrace) { final String stackTraceClass = P6SpyOptions.getActiveInstance().getStackTraceClass(); Exception e = new Exception(); if (stackTraceClass != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String stack = sw.toString(); if (stack.indexOf(stackTraceClass) == -1) { e = null; } } if (e != null) { logger.logException(e); } } }
[ "protected", "static", "void", "doLog", "(", "int", "connectionId", ",", "long", "elapsedNanos", ",", "Category", "category", ",", "String", "prepared", ",", "String", "sql", ",", "String", "url", ")", "{", "// give it one more try if not initialized yet", "if", "...
Writes log information provided. @param connectionId @param elapsedNanos @param category @param prepared @param sql @param url
[ "Writes", "log", "information", "provided", "." ]
c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2
https://github.com/p6spy/p6spy/blob/c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2/src/main/java/com/p6spy/engine/common/P6LogQuery.java#L104-L140
train
p6spy/p6spy
src/main/java/com/p6spy/engine/common/P6LogQuery.java
P6LogQuery.meetsThresholdRequirement
private static boolean meetsThresholdRequirement(long timeTaken) { final P6LogLoadableOptions opts = P6LogOptions.getActiveInstance(); long executionThreshold = null != opts ? opts.getExecutionThreshold() : 0; return executionThreshold <= 0 || TimeUnit.NANOSECONDS.toMillis(timeTaken) > executionThreshold; }
java
private static boolean meetsThresholdRequirement(long timeTaken) { final P6LogLoadableOptions opts = P6LogOptions.getActiveInstance(); long executionThreshold = null != opts ? opts.getExecutionThreshold() : 0; return executionThreshold <= 0 || TimeUnit.NANOSECONDS.toMillis(timeTaken) > executionThreshold; }
[ "private", "static", "boolean", "meetsThresholdRequirement", "(", "long", "timeTaken", ")", "{", "final", "P6LogLoadableOptions", "opts", "=", "P6LogOptions", ".", "getActiveInstance", "(", ")", ";", "long", "executionThreshold", "=", "null", "!=", "opts", "?", "o...
on whether on not it has taken greater than x amount of time.
[ "on", "whether", "on", "not", "it", "has", "taken", "greater", "than", "x", "amount", "of", "time", "." ]
c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2
https://github.com/p6spy/p6spy/blob/c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2/src/main/java/com/p6spy/engine/common/P6LogQuery.java#L213-L218
train
p6spy/p6spy
src/main/java/com/p6spy/engine/spy/P6DataSource.java
P6DataSource.bindDataSource
protected synchronized void bindDataSource() throws SQLException { // we'll check in the synchronized section again (to prevent unnecessary reinitialization) if (null != realDataSource) { return; } final P6SpyLoadableOptions options = P6SpyOptions.getActiveInstance(); // can be set when object is bound to JNDI, or // can be loaded from spy.properties if (rdsName == null) { rdsName = options.getRealDataSource(); } if (rdsName == null) { throw new SQLException("P6DataSource: no value for Real Data Source Name, cannot perform jndi lookup"); } // setup environment for the JNDI lookup Hashtable<String, String> env = null; String factory; if ((factory = options.getJNDIContextFactory()) != null) { env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, factory); String url = options.getJNDIContextProviderURL(); if (url != null) { env.put(Context.PROVIDER_URL, url); } String custom = options.getJNDIContextCustom(); if( custom != null ) { env.putAll(parseDelimitedString(custom)); } } // lookup the real data source InitialContext ctx; try { if (env != null) { ctx = new InitialContext(env); } else { ctx = new InitialContext(); } realDataSource = (CommonDataSource) ctx.lookup(rdsName); } catch (NamingException e) { throw new SQLException("P6DataSource: naming exception during jndi lookup of Real Data Source Name of '" + rdsName + "'. " + e.getMessage(), e); } // Set any properties that the spy.properties file contains // that are supported by set methods in this class Map<String, String> props = parseDelimitedString(options.getRealDataSourceProperties()); if (props != null) { setDataSourceProperties(props); } if (realDataSource == null) { throw new SQLException("P6DataSource: jndi lookup for Real Data Source Name of '" + rdsName + "' failed, cannot bind named data source."); } }
java
protected synchronized void bindDataSource() throws SQLException { // we'll check in the synchronized section again (to prevent unnecessary reinitialization) if (null != realDataSource) { return; } final P6SpyLoadableOptions options = P6SpyOptions.getActiveInstance(); // can be set when object is bound to JNDI, or // can be loaded from spy.properties if (rdsName == null) { rdsName = options.getRealDataSource(); } if (rdsName == null) { throw new SQLException("P6DataSource: no value for Real Data Source Name, cannot perform jndi lookup"); } // setup environment for the JNDI lookup Hashtable<String, String> env = null; String factory; if ((factory = options.getJNDIContextFactory()) != null) { env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, factory); String url = options.getJNDIContextProviderURL(); if (url != null) { env.put(Context.PROVIDER_URL, url); } String custom = options.getJNDIContextCustom(); if( custom != null ) { env.putAll(parseDelimitedString(custom)); } } // lookup the real data source InitialContext ctx; try { if (env != null) { ctx = new InitialContext(env); } else { ctx = new InitialContext(); } realDataSource = (CommonDataSource) ctx.lookup(rdsName); } catch (NamingException e) { throw new SQLException("P6DataSource: naming exception during jndi lookup of Real Data Source Name of '" + rdsName + "'. " + e.getMessage(), e); } // Set any properties that the spy.properties file contains // that are supported by set methods in this class Map<String, String> props = parseDelimitedString(options.getRealDataSourceProperties()); if (props != null) { setDataSourceProperties(props); } if (realDataSource == null) { throw new SQLException("P6DataSource: jndi lookup for Real Data Source Name of '" + rdsName + "' failed, cannot bind named data source."); } }
[ "protected", "synchronized", "void", "bindDataSource", "(", ")", "throws", "SQLException", "{", "// we'll check in the synchronized section again (to prevent unnecessary reinitialization)", "if", "(", "null", "!=", "realDataSource", ")", "{", "return", ";", "}", "final", "P...
Binds the JNDI DataSource to proxy. @throws SQLException
[ "Binds", "the", "JNDI", "DataSource", "to", "proxy", "." ]
c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2
https://github.com/p6spy/p6spy/blob/c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2/src/main/java/com/p6spy/engine/spy/P6DataSource.java#L100-L158
train
p6spy/p6spy
src/main/java/com/p6spy/engine/common/ResultSetInformation.java
ResultSetInformation.generateLogMessage
public void generateLogMessage() { if (lastRowLogged != currRow) { P6LogQuery.log(Category.RESULTSET, this); resultMap.clear(); lastRowLogged = currRow; } }
java
public void generateLogMessage() { if (lastRowLogged != currRow) { P6LogQuery.log(Category.RESULTSET, this); resultMap.clear(); lastRowLogged = currRow; } }
[ "public", "void", "generateLogMessage", "(", ")", "{", "if", "(", "lastRowLogged", "!=", "currRow", ")", "{", "P6LogQuery", ".", "log", "(", "Category", ".", "RESULTSET", ",", "this", ")", ";", "resultMap", ".", "clear", "(", ")", ";", "lastRowLogged", "...
Generates log message with column values accessed if the row's column values have not already been logged.
[ "Generates", "log", "message", "with", "column", "values", "accessed", "if", "the", "row", "s", "column", "values", "have", "not", "already", "been", "logged", "." ]
c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2
https://github.com/p6spy/p6spy/blob/c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2/src/main/java/com/p6spy/engine/common/ResultSetInformation.java#L45-L51
train
p6spy/p6spy
src/main/java/com/p6spy/engine/logging/P6LogOptions.java
P6LogOptions.setExclude
@Override public void setExclude(String exclude) { optionsRepository.setSet(String.class, EXCLUDE_LIST, exclude); // setting effective string optionsRepository.set(String.class, EXCLUDE, P6Util.joinNullSafe(optionsRepository.getSet(String.class, EXCLUDE_LIST), ",")); optionsRepository.setOrUnSet(Pattern.class, INCLUDE_EXCLUDE_PATTERN, computeIncludeExcludePattern(), defaults.get(INCLUDE_EXCLUDE_PATTERN)); }
java
@Override public void setExclude(String exclude) { optionsRepository.setSet(String.class, EXCLUDE_LIST, exclude); // setting effective string optionsRepository.set(String.class, EXCLUDE, P6Util.joinNullSafe(optionsRepository.getSet(String.class, EXCLUDE_LIST), ",")); optionsRepository.setOrUnSet(Pattern.class, INCLUDE_EXCLUDE_PATTERN, computeIncludeExcludePattern(), defaults.get(INCLUDE_EXCLUDE_PATTERN)); }
[ "@", "Override", "public", "void", "setExclude", "(", "String", "exclude", ")", "{", "optionsRepository", ".", "setSet", "(", "String", ".", "class", ",", "EXCLUDE_LIST", ",", "exclude", ")", ";", "// setting effective string", "optionsRepository", ".", "set", "...
JMX exposed API
[ "JMX", "exposed", "API" ]
c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2
https://github.com/p6spy/p6spy/blob/c3c0fecd6e26156eecf90a90901c3c1c8a7dbdf2/src/main/java/com/p6spy/engine/logging/P6LogOptions.java#L96-L102
train
h2oai/h2o-2
src/main/java/water/api/SetTimezone.java
SetTimezone.serve
@Override protected Response serve() { invoke(); String s = ParseTime.getTimezone().getID(); JsonObject response = new JsonObject(); response.addProperty("tz", s); return Response.done(response); }
java
@Override protected Response serve() { invoke(); String s = ParseTime.getTimezone().getID(); JsonObject response = new JsonObject(); response.addProperty("tz", s); return Response.done(response); }
[ "@", "Override", "protected", "Response", "serve", "(", ")", "{", "invoke", "(", ")", ";", "String", "s", "=", "ParseTime", ".", "getTimezone", "(", ")", ".", "getID", "(", ")", ";", "JsonObject", "response", "=", "new", "JsonObject", "(", ")", ";", ...
Reply value is the current setting
[ "Reply", "value", "is", "the", "current", "setting" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/api/SetTimezone.java#L44-L52
train
h2oai/h2o-2
src/main/java/water/RPC.java
RPC.get
@Override public V get() { // check priorities - FJ task can only block on a task with higher priority! Thread cThr = Thread.currentThread(); int priority = (cThr instanceof FJWThr) ? ((FJWThr)cThr)._priority : -1; // was hitting this (priority=1 but _dt.priority()=0 for DRemoteTask) - not clear who increased priority of FJWThr to 1... // assert _dt.priority() > priority || (_dt.priority() == priority && (_dt instanceof DRemoteTask || _dt instanceof MRTask2)) assert _dt.priority() > priority || ((_dt instanceof DRemoteTask || _dt instanceof MRTask2)) : "*** Attempting to block on task (" + _dt.getClass() + ") with equal or lower priority. Can lead to deadlock! " + _dt.priority() + " <= " + priority; if( _done ) return result(); // Fast-path shortcut // Use FJP ManagedBlock for this blocking-wait - so the FJP can spawn // another thread if needed. try { try { ForkJoinPool.managedBlock(this); } catch (InterruptedException e) { } } catch(Throwable t){ // catch and rethrow to preserve the stack trace! throw new RuntimeException(t); } if( _done ) return result(); // Fast-path shortcut assert isCancelled(); return null; }
java
@Override public V get() { // check priorities - FJ task can only block on a task with higher priority! Thread cThr = Thread.currentThread(); int priority = (cThr instanceof FJWThr) ? ((FJWThr)cThr)._priority : -1; // was hitting this (priority=1 but _dt.priority()=0 for DRemoteTask) - not clear who increased priority of FJWThr to 1... // assert _dt.priority() > priority || (_dt.priority() == priority && (_dt instanceof DRemoteTask || _dt instanceof MRTask2)) assert _dt.priority() > priority || ((_dt instanceof DRemoteTask || _dt instanceof MRTask2)) : "*** Attempting to block on task (" + _dt.getClass() + ") with equal or lower priority. Can lead to deadlock! " + _dt.priority() + " <= " + priority; if( _done ) return result(); // Fast-path shortcut // Use FJP ManagedBlock for this blocking-wait - so the FJP can spawn // another thread if needed. try { try { ForkJoinPool.managedBlock(this); } catch (InterruptedException e) { } } catch(Throwable t){ // catch and rethrow to preserve the stack trace! throw new RuntimeException(t); } if( _done ) return result(); // Fast-path shortcut assert isCancelled(); return null; }
[ "@", "Override", "public", "V", "get", "(", ")", "{", "// check priorities - FJ task can only block on a task with higher priority!", "Thread", "cThr", "=", "Thread", ".", "currentThread", "(", ")", ";", "int", "priority", "=", "(", "cThr", "instanceof", "FJWThr", "...
null for canceled tasks, including those where the target dies.
[ "null", "for", "canceled", "tasks", "including", "those", "where", "the", "target", "dies", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/RPC.java#L227-L250
train
h2oai/h2o-2
src/main/java/water/RPC.java
RPC.response
protected int response( AutoBuffer ab ) { assert _tasknum==ab.getTask(); if( _done ) return ab.close(); // Ignore duplicate response packet int flag = ab.getFlag(); // Must read flag also, to advance ab if( flag == SERVER_TCP_SEND ) return ab.close(); // Ignore UDP packet for a TCP reply assert flag == SERVER_UDP_SEND; synchronized(this) { // Install the answer under lock if( _done ) return ab.close(); // Ignore duplicate response packet UDPTimeOutThread.PENDING.remove(this); _dt.read(ab); // Read the answer (under lock?) _size_rez = ab.size(); // Record received size ab.close(); // Also finish the read (under lock?) _dt.onAck(); // One time only execute (before sending ACKACK) _done = true; // Only read one (of many) response packets ab._h2o.taskRemove(_tasknum); // Flag as task-completed, even if the result is null notifyAll(); // And notify in any case } doAllCompletions(); // Send all tasks needing completion to the work queues return 0; }
java
protected int response( AutoBuffer ab ) { assert _tasknum==ab.getTask(); if( _done ) return ab.close(); // Ignore duplicate response packet int flag = ab.getFlag(); // Must read flag also, to advance ab if( flag == SERVER_TCP_SEND ) return ab.close(); // Ignore UDP packet for a TCP reply assert flag == SERVER_UDP_SEND; synchronized(this) { // Install the answer under lock if( _done ) return ab.close(); // Ignore duplicate response packet UDPTimeOutThread.PENDING.remove(this); _dt.read(ab); // Read the answer (under lock?) _size_rez = ab.size(); // Record received size ab.close(); // Also finish the read (under lock?) _dt.onAck(); // One time only execute (before sending ACKACK) _done = true; // Only read one (of many) response packets ab._h2o.taskRemove(_tasknum); // Flag as task-completed, even if the result is null notifyAll(); // And notify in any case } doAllCompletions(); // Send all tasks needing completion to the work queues return 0; }
[ "protected", "int", "response", "(", "AutoBuffer", "ab", ")", "{", "assert", "_tasknum", "==", "ab", ".", "getTask", "(", ")", ";", "if", "(", "_done", ")", "return", "ab", ".", "close", "(", ")", ";", "// Ignore duplicate response packet", "int", "flag", ...
Install it as The Answer packet and wake up anybody waiting on an answer.
[ "Install", "it", "as", "The", "Answer", "packet", "and", "wake", "up", "anybody", "waiting", "on", "an", "answer", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/RPC.java#L544-L563
train
h2oai/h2o-2
src/main/java/hex/gbm/SharedTreeModelBuilder.java
ScoreBuildHistogram.accum_all
private void accum_all(Chunk chks[], Chunk wrks, int nnids[]) { final DHistogram hcs[][] = _hcs; // Sort the rows by NID, so we visit all the same NIDs in a row // Find the count of unique NIDs in this chunk int nh[] = new int[hcs.length+1]; for( int i : nnids ) if( i >= 0 ) nh[i+1]++; // Rollup the histogram of rows-per-NID in this chunk for( int i=0; i<hcs.length; i++ ) nh[i+1] += nh[i]; // Splat the rows into NID-groups int rows[] = new int[nnids.length]; for( int row=0; row<nnids.length; row++ ) if( nnids[row] >= 0 ) rows[nh[nnids[row]]++] = row; // rows[] has Chunk-local ROW-numbers now, in-order, grouped by NID. // nh[] lists the start of each new NID, and is indexed by NID+1. accum_all2(chks,wrks,nh,rows); }
java
private void accum_all(Chunk chks[], Chunk wrks, int nnids[]) { final DHistogram hcs[][] = _hcs; // Sort the rows by NID, so we visit all the same NIDs in a row // Find the count of unique NIDs in this chunk int nh[] = new int[hcs.length+1]; for( int i : nnids ) if( i >= 0 ) nh[i+1]++; // Rollup the histogram of rows-per-NID in this chunk for( int i=0; i<hcs.length; i++ ) nh[i+1] += nh[i]; // Splat the rows into NID-groups int rows[] = new int[nnids.length]; for( int row=0; row<nnids.length; row++ ) if( nnids[row] >= 0 ) rows[nh[nnids[row]]++] = row; // rows[] has Chunk-local ROW-numbers now, in-order, grouped by NID. // nh[] lists the start of each new NID, and is indexed by NID+1. accum_all2(chks,wrks,nh,rows); }
[ "private", "void", "accum_all", "(", "Chunk", "chks", "[", "]", ",", "Chunk", "wrks", ",", "int", "nnids", "[", "]", ")", "{", "final", "DHistogram", "hcs", "[", "]", "[", "]", "=", "_hcs", ";", "// Sort the rows by NID, so we visit all the same NIDs in a row"...
histograms once-per-NID, but requires pre-sorting the rows by NID.
[ "histograms", "once", "-", "per", "-", "NID", "but", "requires", "pre", "-", "sorting", "the", "rows", "by", "NID", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/gbm/SharedTreeModelBuilder.java#L546-L562
train
h2oai/h2o-2
src/main/java/hex/gbm/SharedTreeModelBuilder.java
ScoreBuildHistogram.accum_all2
private void accum_all2(Chunk chks[], Chunk wrks, int nh[], int[] rows) { final DHistogram hcs[][] = _hcs; // Local temp arrays, no atomic updates. int bins[] = new int [nbins]; double sums[] = new double[nbins]; double ssqs[] = new double[nbins]; // For All Columns for( int c=0; c<_ncols; c++) { // for all columns Chunk chk = chks[c]; // For All NIDs for( int n=0; n<hcs.length; n++ ) { final DRealHistogram rh = ((DRealHistogram)hcs[n][c]); if( rh==null ) continue; // Ignore untracked columns in this split final int lo = n==0 ? 0 : nh[n-1]; final int hi = nh[n]; float min = rh._min2; float max = rh._maxIn; // While most of the time we are limited to nbins, we allow more bins // in a few cases (top-level splits have few total bins across all // the (few) splits) so it's safe to bin more; also categoricals want // to split one bin-per-level no matter how many levels). if( rh._bins.length >= bins.length ) { // Grow bins if needed bins = new int [rh._bins.length]; sums = new double[rh._bins.length]; ssqs = new double[rh._bins.length]; } // Gather all the data for this set of rows, for 1 column and 1 split/NID // Gather min/max, sums and sum-squares. for( int xrow=lo; xrow<hi; xrow++ ) { int row = rows[xrow]; float col_data = (float)chk.at0(row); if( col_data < min ) min = col_data; if( col_data > max ) max = col_data; int b = rh.bin(col_data); // Compute bin# via linear interpolation bins[b]++; // Bump count in bin double resp = wrks.at0(row); sums[b] += resp; ssqs[b] += resp*resp; } // Add all the data into the Histogram (atomically add) rh.setMin(min); // Track actual lower/upper bound per-bin rh.setMax(max); for( int b=0; b<rh._bins.length; b++ ) { // Bump counts in bins if( bins[b] != 0 ) { Utils.AtomicIntArray.add(rh._bins,b,bins[b]); bins[b]=0; } if( ssqs[b] != 0 ) { rh.incr1(b,sums[b],ssqs[b]); sums[b]=ssqs[b]=0; } } } } }
java
private void accum_all2(Chunk chks[], Chunk wrks, int nh[], int[] rows) { final DHistogram hcs[][] = _hcs; // Local temp arrays, no atomic updates. int bins[] = new int [nbins]; double sums[] = new double[nbins]; double ssqs[] = new double[nbins]; // For All Columns for( int c=0; c<_ncols; c++) { // for all columns Chunk chk = chks[c]; // For All NIDs for( int n=0; n<hcs.length; n++ ) { final DRealHistogram rh = ((DRealHistogram)hcs[n][c]); if( rh==null ) continue; // Ignore untracked columns in this split final int lo = n==0 ? 0 : nh[n-1]; final int hi = nh[n]; float min = rh._min2; float max = rh._maxIn; // While most of the time we are limited to nbins, we allow more bins // in a few cases (top-level splits have few total bins across all // the (few) splits) so it's safe to bin more; also categoricals want // to split one bin-per-level no matter how many levels). if( rh._bins.length >= bins.length ) { // Grow bins if needed bins = new int [rh._bins.length]; sums = new double[rh._bins.length]; ssqs = new double[rh._bins.length]; } // Gather all the data for this set of rows, for 1 column and 1 split/NID // Gather min/max, sums and sum-squares. for( int xrow=lo; xrow<hi; xrow++ ) { int row = rows[xrow]; float col_data = (float)chk.at0(row); if( col_data < min ) min = col_data; if( col_data > max ) max = col_data; int b = rh.bin(col_data); // Compute bin# via linear interpolation bins[b]++; // Bump count in bin double resp = wrks.at0(row); sums[b] += resp; ssqs[b] += resp*resp; } // Add all the data into the Histogram (atomically add) rh.setMin(min); // Track actual lower/upper bound per-bin rh.setMax(max); for( int b=0; b<rh._bins.length; b++ ) { // Bump counts in bins if( bins[b] != 0 ) { Utils.AtomicIntArray.add(rh._bins,b,bins[b]); bins[b]=0; } if( ssqs[b] != 0 ) { rh.incr1(b,sums[b],ssqs[b]); sums[b]=ssqs[b]=0; } } } } }
[ "private", "void", "accum_all2", "(", "Chunk", "chks", "[", "]", ",", "Chunk", "wrks", ",", "int", "nh", "[", "]", ",", "int", "[", "]", "rows", ")", "{", "final", "DHistogram", "hcs", "[", "]", "[", "]", "=", "_hcs", ";", "// Local temp arrays, no a...
For all columns, for all NIDs, for all ROWS...
[ "For", "all", "columns", "for", "all", "NIDs", "for", "all", "ROWS", "..." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/gbm/SharedTreeModelBuilder.java#L565-L615
train
h2oai/h2o-2
src/main/java/water/api/StoreView.java
StoreView.setAndServe
public String setAndServe(String offset) { _offset.reset(); _offset.check(null,offset); _view .reset(); _view .check(null,"20"); _filter.reset(); return new Gson().toJson(serve()._response); }
java
public String setAndServe(String offset) { _offset.reset(); _offset.check(null,offset); _view .reset(); _view .check(null,"20"); _filter.reset(); return new Gson().toJson(serve()._response); }
[ "public", "String", "setAndServe", "(", "String", "offset", ")", "{", "_offset", ".", "reset", "(", ")", ";", "_offset", ".", "check", "(", "null", ",", "offset", ")", ";", "_view", ".", "reset", "(", ")", ";", "_view", ".", "check", "(", "null", "...
Used by tests
[ "Used", "by", "tests" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/api/StoreView.java#L73-L78
train
h2oai/h2o-2
src/main/java/water/Arguments.java
Arguments.addArgument
public int addArgument(String str, String next) { int i = commandLineArgs.length; int consumed = 1; commandLineArgs = Arrays.copyOf(commandLineArgs, i + 1); /* * Flags have a null string as val and flag of true; Binding have non-empty * name, a non-null val (possibly ""), and a flag of false; Plain strings * have an empty name, "", a non-null, non-empty val, and a flag of true; */ if( str.startsWith("-") ){ int startOffset = (str.startsWith("--"))? 2 : 1; String arg = ""; String opt; boolean flag = false; int eqPos = str.indexOf("="); if( eqPos > 0 || (next!=null && !next.startsWith("-"))){ if( eqPos > 0 ){ opt = str.substring(startOffset, eqPos); arg = str.substring(eqPos + 1); }else{ opt = str.substring(startOffset); arg = next; consumed = 2; } }else{ flag = true; opt = str.substring(startOffset); } commandLineArgs[i] = new Entry(opt, arg, flag, i); return consumed; }else{ commandLineArgs[i] = new Entry("", str, true, i); return consumed; } }
java
public int addArgument(String str, String next) { int i = commandLineArgs.length; int consumed = 1; commandLineArgs = Arrays.copyOf(commandLineArgs, i + 1); /* * Flags have a null string as val and flag of true; Binding have non-empty * name, a non-null val (possibly ""), and a flag of false; Plain strings * have an empty name, "", a non-null, non-empty val, and a flag of true; */ if( str.startsWith("-") ){ int startOffset = (str.startsWith("--"))? 2 : 1; String arg = ""; String opt; boolean flag = false; int eqPos = str.indexOf("="); if( eqPos > 0 || (next!=null && !next.startsWith("-"))){ if( eqPos > 0 ){ opt = str.substring(startOffset, eqPos); arg = str.substring(eqPos + 1); }else{ opt = str.substring(startOffset); arg = next; consumed = 2; } }else{ flag = true; opt = str.substring(startOffset); } commandLineArgs[i] = new Entry(opt, arg, flag, i); return consumed; }else{ commandLineArgs[i] = new Entry("", str, true, i); return consumed; } }
[ "public", "int", "addArgument", "(", "String", "str", ",", "String", "next", ")", "{", "int", "i", "=", "commandLineArgs", ".", "length", ";", "int", "consumed", "=", "1", ";", "commandLineArgs", "=", "Arrays", ".", "copyOf", "(", "commandLineArgs", ",", ...
Add a new argument to this command line. The argument will be parsed and add at the end of the list. Bindings have the following format "-name=value" if value is empty, the binding is treated as an option. Options have the form "-name". All other strings are treated as values. @param str a string
[ "Add", "a", "new", "argument", "to", "this", "command", "line", ".", "The", "argument", "will", "be", "parsed", "and", "add", "at", "the", "end", "of", "the", "list", ".", "Bindings", "have", "the", "following", "format", "-", "name", "=", "value", "if...
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Arguments.java#L133-L167
train
h2oai/h2o-2
src/main/java/water/Arguments.java
Arguments.extract
private int extract(Arg arg, Field[] fields) { int count = 0; for( Field field : fields ){ String name = field.getName(); Class cl = field.getType(); String opt = getValue(name); // optional value try{ if( cl.isPrimitive() ){ if( cl == Boolean.TYPE ){ boolean curval = field.getBoolean(arg); boolean xval = curval; if( opt != null ) xval = !curval; if( "1".equals(opt) || "true" .equals(opt) ) xval = true; if( "0".equals(opt) || "false".equals(opt) ) xval = false; if( opt != null ) field.setBoolean(arg, xval); }else if( opt == null || opt.length()==0 ) continue; else if( cl == Integer.TYPE ) field.setInt(arg, Integer.parseInt(opt)); else if( cl == Float.TYPE ) field.setFloat(arg, Float.parseFloat(opt)); else if( cl == Double.TYPE ) field.setDouble(arg, Double.parseDouble(opt)); else if( cl == Long.TYPE ) field.setLong(arg, Long.parseLong(opt)); else continue; count++; }else if( cl == String.class ){ if( opt != null ){ field.set(arg, opt); count++; } } } catch( Exception e ) { Log.err("Argument failed with ",e); } } Arrays.sort(commandLineArgs); for( int i = 0; i < commandLineArgs.length; i++ ) commandLineArgs[i].position = i; return count; }
java
private int extract(Arg arg, Field[] fields) { int count = 0; for( Field field : fields ){ String name = field.getName(); Class cl = field.getType(); String opt = getValue(name); // optional value try{ if( cl.isPrimitive() ){ if( cl == Boolean.TYPE ){ boolean curval = field.getBoolean(arg); boolean xval = curval; if( opt != null ) xval = !curval; if( "1".equals(opt) || "true" .equals(opt) ) xval = true; if( "0".equals(opt) || "false".equals(opt) ) xval = false; if( opt != null ) field.setBoolean(arg, xval); }else if( opt == null || opt.length()==0 ) continue; else if( cl == Integer.TYPE ) field.setInt(arg, Integer.parseInt(opt)); else if( cl == Float.TYPE ) field.setFloat(arg, Float.parseFloat(opt)); else if( cl == Double.TYPE ) field.setDouble(arg, Double.parseDouble(opt)); else if( cl == Long.TYPE ) field.setLong(arg, Long.parseLong(opt)); else continue; count++; }else if( cl == String.class ){ if( opt != null ){ field.set(arg, opt); count++; } } } catch( Exception e ) { Log.err("Argument failed with ",e); } } Arrays.sort(commandLineArgs); for( int i = 0; i < commandLineArgs.length; i++ ) commandLineArgs[i].position = i; return count; }
[ "private", "int", "extract", "(", "Arg", "arg", ",", "Field", "[", "]", "fields", ")", "{", "int", "count", "=", "0", ";", "for", "(", "Field", "field", ":", "fields", ")", "{", "String", "name", "=", "field", ".", "getName", "(", ")", ";", "Clas...
Extracts bindings and options; and sets appropriate fields in the CommandLineArgument object.
[ "Extracts", "bindings", "and", "options", ";", "and", "sets", "appropriate", "fields", "in", "the", "CommandLineArgument", "object", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Arguments.java#L181-L215
train
h2oai/h2o-2
src/main/java/water/Arguments.java
Arguments.parse
private void parse(String[] s) { commandLineArgs = new Entry[0]; for( int i = 0; i < s.length; ) { String next = (i+1<s.length)? s[i+1]: null; i += addArgument(s[i],next); } }
java
private void parse(String[] s) { commandLineArgs = new Entry[0]; for( int i = 0; i < s.length; ) { String next = (i+1<s.length)? s[i+1]: null; i += addArgument(s[i],next); } }
[ "private", "void", "parse", "(", "String", "[", "]", "s", ")", "{", "commandLineArgs", "=", "new", "Entry", "[", "0", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s", ".", "length", ";", ")", "{", "String", "next", "=", "(", "i...
Parse the command line arguments and extracts options. The current implementation allows the same command line instance to parse several argument lists, the results will be merged. @param s the array of arguments to be parsed
[ "Parse", "the", "command", "line", "arguments", "and", "extracts", "options", ".", "The", "current", "implementation", "allows", "the", "same", "command", "line", "instance", "to", "parse", "several", "argument", "lists", "the", "results", "will", "be", "merged"...
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Arguments.java#L238-L244
train
h2oai/h2o-2
src/main/java/water/Job.java
Job.progress
public float progress() { Freezable f = UKV.get(destination_key); if( f instanceof Progress ) return ((Progress) f).progress(); return 0; }
java
public float progress() { Freezable f = UKV.get(destination_key); if( f instanceof Progress ) return ((Progress) f).progress(); return 0; }
[ "public", "float", "progress", "(", ")", "{", "Freezable", "f", "=", "UKV", ".", "get", "(", "destination_key", ")", ";", "if", "(", "f", "instanceof", "Progress", ")", "return", "(", "(", "Progress", ")", "f", ")", ".", "progress", "(", ")", ";", ...
Return progress of this job. @return the value in interval &lt;0,1&gt; representing job progress.
[ "Return", "progress", "of", "this", "job", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Job.java#L130-L135
train
h2oai/h2o-2
src/main/java/water/Job.java
Job.all
public static Job[] all() { List list = UKV.get(LIST); Job[] jobs = new Job[list==null?0:list._jobs.length]; int j=0; for( int i=0; i<jobs.length; i++ ) { Job job = UKV.get(list._jobs[i]); if( job != null ) jobs[j++] = job; } if( j<jobs.length ) jobs = Arrays.copyOf(jobs,j); return jobs; }
java
public static Job[] all() { List list = UKV.get(LIST); Job[] jobs = new Job[list==null?0:list._jobs.length]; int j=0; for( int i=0; i<jobs.length; i++ ) { Job job = UKV.get(list._jobs[i]); if( job != null ) jobs[j++] = job; } if( j<jobs.length ) jobs = Arrays.copyOf(jobs,j); return jobs; }
[ "public", "static", "Job", "[", "]", "all", "(", ")", "{", "List", "list", "=", "UKV", ".", "get", "(", "LIST", ")", ";", "Job", "[", "]", "jobs", "=", "new", "Job", "[", "list", "==", "null", "?", "0", ":", "list", ".", "_jobs", ".", "length...
Returns a list of all jobs in a system. @return list of all jobs including running, done, cancelled, crashed jobs.
[ "Returns", "a", "list", "of", "all", "jobs", "in", "a", "system", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Job.java#L238-L248
train
h2oai/h2o-2
src/main/java/water/Job.java
Job.isRunning
public static boolean isRunning(Key job_key) { Job j = UKV.get(job_key); assert j!=null : "Job should be always in DKV!"; return j.isRunning(); }
java
public static boolean isRunning(Key job_key) { Job j = UKV.get(job_key); assert j!=null : "Job should be always in DKV!"; return j.isRunning(); }
[ "public", "static", "boolean", "isRunning", "(", "Key", "job_key", ")", "{", "Job", "j", "=", "UKV", ".", "get", "(", "job_key", ")", ";", "assert", "j", "!=", "null", ":", "\"Job should be always in DKV!\"", ";", "return", "j", ".", "isRunning", "(", ")...
Check if given job is running. @param job_key job key @return true if job is still running else returns false.
[ "Check", "if", "given", "job", "is", "running", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Job.java#L254-L258
train
h2oai/h2o-2
src/main/java/water/Job.java
Job.remove
public void remove() { end_time = System.currentTimeMillis(); if( state == JobState.RUNNING ) state = JobState.DONE; // Overwrite handle - copy end_time, state, msg replaceByJobHandle(); }
java
public void remove() { end_time = System.currentTimeMillis(); if( state == JobState.RUNNING ) state = JobState.DONE; // Overwrite handle - copy end_time, state, msg replaceByJobHandle(); }
[ "public", "void", "remove", "(", ")", "{", "end_time", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "state", "==", "JobState", ".", "RUNNING", ")", "state", "=", "JobState", ".", "DONE", ";", "// Overwrite handle - copy end_time, state, m...
Marks job as finished and records job end time.
[ "Marks", "job", "as", "finished", "and", "records", "job", "end", "time", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Job.java#L271-L277
train
h2oai/h2o-2
src/main/java/water/Job.java
Job.findJobByDest
public static Job findJobByDest(final Key destKey) { Job job = null; for( Job current : Job.all() ) { if( current.dest().equals(destKey) ) { job = current; break; } } return job; }
java
public static Job findJobByDest(final Key destKey) { Job job = null; for( Job current : Job.all() ) { if( current.dest().equals(destKey) ) { job = current; break; } } return job; }
[ "public", "static", "Job", "findJobByDest", "(", "final", "Key", "destKey", ")", "{", "Job", "job", "=", "null", ";", "for", "(", "Job", "current", ":", "Job", ".", "all", "(", ")", ")", "{", "if", "(", "current", ".", "dest", "(", ")", ".", "equ...
Finds a job with given dest key or returns null
[ "Finds", "a", "job", "with", "given", "dest", "key", "or", "returns", "null" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Job.java#L287-L296
train
h2oai/h2o-2
src/main/java/water/Job.java
Job.fork
public Job fork() { init(); H2OCountedCompleter task = new H2OCountedCompleter() { @Override public void compute2() { try { try { // Exec always waits till the end of computation Job.this.exec(); Job.this.remove(); } catch (Throwable t) { if(!(t instanceof ExpectedExceptionForDebug)) Log.err(t); Job.this.cancel(t); } } finally { tryComplete(); } } }; start(task); H2O.submitTask(task); return this; }
java
public Job fork() { init(); H2OCountedCompleter task = new H2OCountedCompleter() { @Override public void compute2() { try { try { // Exec always waits till the end of computation Job.this.exec(); Job.this.remove(); } catch (Throwable t) { if(!(t instanceof ExpectedExceptionForDebug)) Log.err(t); Job.this.cancel(t); } } finally { tryComplete(); } } }; start(task); H2O.submitTask(task); return this; }
[ "public", "Job", "fork", "(", ")", "{", "init", "(", ")", ";", "H2OCountedCompleter", "task", "=", "new", "H2OCountedCompleter", "(", ")", "{", "@", "Override", "public", "void", "compute2", "(", ")", "{", "try", "{", "try", "{", "// Exec always waits till...
Forks computation of this job. <p>The call does not block.</p> @return always returns this job.
[ "Forks", "computation", "of", "this", "job", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Job.java#L327-L349
train
h2oai/h2o-2
src/main/java/water/Job.java
Job.waitUntilJobEnded
public static void waitUntilJobEnded(Key jobkey, int pollingIntervalMillis) { while (true) { if (Job.isEnded(jobkey)) { return; } try { Thread.sleep (pollingIntervalMillis); } catch (Exception ignore) {} } }
java
public static void waitUntilJobEnded(Key jobkey, int pollingIntervalMillis) { while (true) { if (Job.isEnded(jobkey)) { return; } try { Thread.sleep (pollingIntervalMillis); } catch (Exception ignore) {} } }
[ "public", "static", "void", "waitUntilJobEnded", "(", "Key", "jobkey", ",", "int", "pollingIntervalMillis", ")", "{", "while", "(", "true", ")", "{", "if", "(", "Job", ".", "isEnded", "(", "jobkey", ")", ")", "{", "return", ";", "}", "try", "{", "Threa...
Block synchronously waiting for a job to end, success or not. @param jobkey Job to wait for. @param pollingIntervalMillis Polling interval sleep time.
[ "Block", "synchronously", "waiting", "for", "a", "job", "to", "end", "success", "or", "not", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Job.java#L374-L382
train
h2oai/h2o-2
src/main/java/water/Job.java
Job.hygiene
public static <T extends FrameJob> T hygiene(T job) { job.source = null; return job; }
java
public static <T extends FrameJob> T hygiene(T job) { job.source = null; return job; }
[ "public", "static", "<", "T", "extends", "FrameJob", ">", "T", "hygiene", "(", "T", "job", ")", "{", "job", ".", "source", "=", "null", ";", "return", "job", ";", "}" ]
Hygienic method to prevent accidental capture of non desired values.
[ "Hygienic", "method", "to", "prevent", "accidental", "capture", "of", "non", "desired", "values", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Job.java#L1073-L1076
train
h2oai/h2o-2
src/main/java/hex/singlenoderf/EntropyStatistic.java
EntropyStatistic.ltSplit
@Override protected Split ltSplit(int col, Data d, int[] dist, int distWeight, Random rand) { final int[] distL = new int[d.classes()], distR = dist.clone(); final double upperBoundReduction = upperBoundReduction(d.classes()); double maxReduction = -1; int bestSplit = -1; int totL = 0, totR = 0; // Totals in the distribution int classL = 0, classR = 0; // Count of non-zero classes in the left/right distributions for (int e: distR) { // All zeros for the left, but need to compute for the right totR += e; if( e != 0 ) classR++; } // For this one column, look at all his split points and find the one with the best gain. for (int i = 0; i < _columnDists[col].length - 1; ++i) { int [] cdis = _columnDists[col][i]; for (int j = 0; j < distL.length; ++j) { int v = cdis[j]; if( v == 0 ) continue; // No rows with this class totL += v; totR -= v; if( distL[j]== 0 ) classL++; // One-time transit from zero to non-zero for class j distL[j] += v; distR[j] -= v; if( distR[j]== 0 ) classR--; // One-time transit from non-zero to zero for class j } if (totL == 0) continue; // Totals are zero ==> this will not actually split anything if (totR == 0) continue; // Totals are zero ==> this will not actually split anything // Compute gain. // If the distribution has only 1 class, the gain will be zero. double eL = 0, eR = 0; if( classL > 1 ) for (int e: distL) eL += gain(e,totL); if( classR > 1 ) for (int e: distR) eR += gain(e,totR); double eReduction = upperBoundReduction - ( (eL * totL + eR * totR) / (totL + totR) ); if (eReduction == maxReduction) { // For now, don't break ties. Most ties are because we have several // splits with NO GAIN. This happens *billions* of times in a standard // covtype RF, because we have >100K leaves per tree (and 50 trees and // 54 columns per leave and however many bins per column), and most // leaves have no gain at most split points. //if (rand.nextInt(10)<2) bestSplit=i; } else if (eReduction > maxReduction) { bestSplit = i; maxReduction = eReduction; } } return bestSplit == -1 ? Split.impossible(Utils.maxIndex(dist,_random)) : Split.split(col,bestSplit,maxReduction); }
java
@Override protected Split ltSplit(int col, Data d, int[] dist, int distWeight, Random rand) { final int[] distL = new int[d.classes()], distR = dist.clone(); final double upperBoundReduction = upperBoundReduction(d.classes()); double maxReduction = -1; int bestSplit = -1; int totL = 0, totR = 0; // Totals in the distribution int classL = 0, classR = 0; // Count of non-zero classes in the left/right distributions for (int e: distR) { // All zeros for the left, but need to compute for the right totR += e; if( e != 0 ) classR++; } // For this one column, look at all his split points and find the one with the best gain. for (int i = 0; i < _columnDists[col].length - 1; ++i) { int [] cdis = _columnDists[col][i]; for (int j = 0; j < distL.length; ++j) { int v = cdis[j]; if( v == 0 ) continue; // No rows with this class totL += v; totR -= v; if( distL[j]== 0 ) classL++; // One-time transit from zero to non-zero for class j distL[j] += v; distR[j] -= v; if( distR[j]== 0 ) classR--; // One-time transit from non-zero to zero for class j } if (totL == 0) continue; // Totals are zero ==> this will not actually split anything if (totR == 0) continue; // Totals are zero ==> this will not actually split anything // Compute gain. // If the distribution has only 1 class, the gain will be zero. double eL = 0, eR = 0; if( classL > 1 ) for (int e: distL) eL += gain(e,totL); if( classR > 1 ) for (int e: distR) eR += gain(e,totR); double eReduction = upperBoundReduction - ( (eL * totL + eR * totR) / (totL + totR) ); if (eReduction == maxReduction) { // For now, don't break ties. Most ties are because we have several // splits with NO GAIN. This happens *billions* of times in a standard // covtype RF, because we have >100K leaves per tree (and 50 trees and // 54 columns per leave and however many bins per column), and most // leaves have no gain at most split points. //if (rand.nextInt(10)<2) bestSplit=i; } else if (eReduction > maxReduction) { bestSplit = i; maxReduction = eReduction; } } return bestSplit == -1 ? Split.impossible(Utils.maxIndex(dist,_random)) : Split.split(col,bestSplit,maxReduction); }
[ "@", "Override", "protected", "Split", "ltSplit", "(", "int", "col", ",", "Data", "d", ",", "int", "[", "]", "dist", ",", "int", "distWeight", ",", "Random", "rand", ")", "{", "final", "int", "[", "]", "distL", "=", "new", "int", "[", "d", ".", "...
LessThenEqual splits s
[ "LessThenEqual", "splits", "s" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/singlenoderf/EntropyStatistic.java#L31-L77
train
h2oai/h2o-2
src/main/java/water/util/UserSpecifiedNetwork.java
UserSpecifiedNetwork.inetAddressOnNetwork
public boolean inetAddressOnNetwork(InetAddress ia) { int i = (_o1 << 24) | (_o2 << 16) | (_o3 << 8) | (_o4 << 0); byte[] barr = ia.getAddress(); if (barr.length != 4) { return false; } int j = (((int)barr[0] & 0xff) << 24) | (((int)barr[1] & 0xff) << 16) | (((int)barr[2] & 0xff) << 8) | (((int)barr[3] & 0xff) << 0); // Do mask math in 64-bit to handle 32-bit wrapping cases. long mask1 = ((long)1 << (32 - _bits)); long mask2 = mask1 - 1; long mask3 = ~mask2; int mask4 = (int) (mask3 & 0xffffffff); if ((i & mask4) == (j & mask4)) { return true; } return false; }
java
public boolean inetAddressOnNetwork(InetAddress ia) { int i = (_o1 << 24) | (_o2 << 16) | (_o3 << 8) | (_o4 << 0); byte[] barr = ia.getAddress(); if (barr.length != 4) { return false; } int j = (((int)barr[0] & 0xff) << 24) | (((int)barr[1] & 0xff) << 16) | (((int)barr[2] & 0xff) << 8) | (((int)barr[3] & 0xff) << 0); // Do mask math in 64-bit to handle 32-bit wrapping cases. long mask1 = ((long)1 << (32 - _bits)); long mask2 = mask1 - 1; long mask3 = ~mask2; int mask4 = (int) (mask3 & 0xffffffff); if ((i & mask4) == (j & mask4)) { return true; } return false; }
[ "public", "boolean", "inetAddressOnNetwork", "(", "InetAddress", "ia", ")", "{", "int", "i", "=", "(", "_o1", "<<", "24", ")", "|", "(", "_o2", "<<", "16", ")", "|", "(", "_o3", "<<", "8", ")", "|", "(", "_o4", "<<", "0", ")", ";", "byte", "[",...
Test if an internet address lives on this user specified network. @param ia Address to test. @return true if the address is on the network; false otherwise.
[ "Test", "if", "an", "internet", "address", "lives", "on", "this", "user", "specified", "network", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/util/UserSpecifiedNetwork.java#L55-L82
train
h2oai/h2o-2
src/main/java/water/Lockable.java
Lockable.write_lock
public Lockable write_lock( Key job_key ) { Log.debug(Log.Tag.Sys.LOCKS,"write-lock "+_key+" by job "+job_key); return ((PriorWriteLock)new PriorWriteLock(job_key).invoke(_key))._old; }
java
public Lockable write_lock( Key job_key ) { Log.debug(Log.Tag.Sys.LOCKS,"write-lock "+_key+" by job "+job_key); return ((PriorWriteLock)new PriorWriteLock(job_key).invoke(_key))._old; }
[ "public", "Lockable", "write_lock", "(", "Key", "job_key", ")", "{", "Log", ".", "debug", "(", "Log", ".", "Tag", ".", "Sys", ".", "LOCKS", ",", "\"write-lock \"", "+", "_key", "+", "\" by job \"", "+", "job_key", ")", ";", "return", "(", "(", "PriorWr...
Write-lock 'this', returns OLD guy
[ "Write", "-", "lock", "this", "returns", "OLD", "guy" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Lockable.java#L58-L61
train
h2oai/h2o-2
src/main/java/water/Lockable.java
Lockable.delete_and_lock
public T delete_and_lock( Key job_key ) { Lockable old = write_lock(job_key); if( old != null ) { Log.debug(Log.Tag.Sys.LOCKS,"lock-then-clear "+_key+" by job "+job_key); old.delete_impl(new Futures()).blockForPending(); } return (T)this; }
java
public T delete_and_lock( Key job_key ) { Lockable old = write_lock(job_key); if( old != null ) { Log.debug(Log.Tag.Sys.LOCKS,"lock-then-clear "+_key+" by job "+job_key); old.delete_impl(new Futures()).blockForPending(); } return (T)this; }
[ "public", "T", "delete_and_lock", "(", "Key", "job_key", ")", "{", "Lockable", "old", "=", "write_lock", "(", "job_key", ")", ";", "if", "(", "old", "!=", "null", ")", "{", "Log", ".", "debug", "(", "Log", ".", "Tag", ".", "Sys", ".", "LOCKS", ",",...
Write-lock 'this', delete any old thing, returns NEW guy
[ "Write", "-", "lock", "this", "delete", "any", "old", "thing", "returns", "NEW", "guy" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Lockable.java#L63-L70
train
h2oai/h2o-2
src/main/java/water/Lockable.java
Lockable.delete
public static void delete( Key k, Key job_key ) { if( k == null ) return; Value val = DKV.get(k); if( val == null ) return; // Or just nothing there to delete if( !val.isLockable() ) UKV.remove(k); // Simple things being deleted else ((Lockable)val.get()).delete(job_key,0.0f); // Lockable being deleted }
java
public static void delete( Key k, Key job_key ) { if( k == null ) return; Value val = DKV.get(k); if( val == null ) return; // Or just nothing there to delete if( !val.isLockable() ) UKV.remove(k); // Simple things being deleted else ((Lockable)val.get()).delete(job_key,0.0f); // Lockable being deleted }
[ "public", "static", "void", "delete", "(", "Key", "k", ",", "Key", "job_key", ")", "{", "if", "(", "k", "==", "null", ")", "return", ";", "Value", "val", "=", "DKV", ".", "get", "(", "k", ")", ";", "if", "(", "val", "==", "null", ")", "return",...
Write-lock & delete 'k'. Will fail if 'k' is locked by anybody other than 'job_key'
[ "Write", "-", "lock", "&", "delete", "k", ".", "Will", "fail", "if", "k", "is", "locked", "by", "anybody", "other", "than", "job_key" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Lockable.java#L100-L106
train
h2oai/h2o-2
src/main/java/water/Lockable.java
Lockable.delete
public void delete( Key job_key, float dummy ) { if( _key != null ) { Log.debug(Log.Tag.Sys.LOCKS,"lock-then-delete "+_key+" by job "+job_key); new PriorWriteLock(job_key).invoke(_key); } Futures fs = new Futures(); delete_impl(fs); if( _key != null ) DKV.remove(_key,fs); // Delete self also fs.blockForPending(); }
java
public void delete( Key job_key, float dummy ) { if( _key != null ) { Log.debug(Log.Tag.Sys.LOCKS,"lock-then-delete "+_key+" by job "+job_key); new PriorWriteLock(job_key).invoke(_key); } Futures fs = new Futures(); delete_impl(fs); if( _key != null ) DKV.remove(_key,fs); // Delete self also fs.blockForPending(); }
[ "public", "void", "delete", "(", "Key", "job_key", ",", "float", "dummy", ")", "{", "if", "(", "_key", "!=", "null", ")", "{", "Log", ".", "debug", "(", "Log", ".", "Tag", ".", "Sys", ".", "LOCKS", ",", "\"lock-then-delete \"", "+", "_key", "+", "\...
Will fail if locked by anybody other than 'job_key'
[ "Will", "fail", "if", "locked", "by", "anybody", "other", "than", "job_key" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Lockable.java#L110-L119
train
h2oai/h2o-2
src/main/java/water/Lockable.java
Lockable.update
public void update( Key job_key ) { Log.debug(Log.Tag.Sys.LOCKS,"update write-locked "+_key+" by job "+job_key); new Update(job_key).invoke(_key); }
java
public void update( Key job_key ) { Log.debug(Log.Tag.Sys.LOCKS,"update write-locked "+_key+" by job "+job_key); new Update(job_key).invoke(_key); }
[ "public", "void", "update", "(", "Key", "job_key", ")", "{", "Log", ".", "debug", "(", "Log", ".", "Tag", ".", "Sys", ".", "LOCKS", ",", "\"update write-locked \"", "+", "_key", "+", "\" by job \"", "+", "job_key", ")", ";", "new", "Update", "(", "job_...
Atomically set a new version of self
[ "Atomically", "set", "a", "new", "version", "of", "self" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Lockable.java#L150-L153
train
h2oai/h2o-2
src/main/java/water/Lockable.java
Lockable.unlock
public void unlock( Key job_key ) { if( _key != null ) { Log.debug(Log.Tag.Sys.LOCKS,"unlock "+_key+" by job "+job_key); new Unlock(job_key).invoke(_key); } }
java
public void unlock( Key job_key ) { if( _key != null ) { Log.debug(Log.Tag.Sys.LOCKS,"unlock "+_key+" by job "+job_key); new Unlock(job_key).invoke(_key); } }
[ "public", "void", "unlock", "(", "Key", "job_key", ")", "{", "if", "(", "_key", "!=", "null", ")", "{", "Log", ".", "debug", "(", "Log", ".", "Tag", ".", "Sys", ".", "LOCKS", ",", "\"unlock \"", "+", "_key", "+", "\" by job \"", "+", "job_key", ")"...
Atomically set a new version of self & unlock.
[ "Atomically", "set", "a", "new", "version", "of", "self", "&", "unlock", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Lockable.java#L173-L178
train
h2oai/h2o-2
src/main/java/hex/gbm/DHistogram.java
DHistogram.initialHist
static public DHistogram[] initialHist(Frame fr, int ncols, int nbins, DHistogram hs[], int min_rows, boolean doGrpSplit, boolean isBinom) { Vec vecs[] = fr.vecs(); for( int c=0; c<ncols; c++ ) { Vec v = vecs[c]; final float minIn = (float)Math.max(v.min(),-Float.MAX_VALUE); // inclusive vector min final float maxIn = (float)Math.min(v.max(), Float.MAX_VALUE); // inclusive vector max final float maxEx = find_maxEx(maxIn,v.isInt()?1:0); // smallest exclusive max final long vlen = v.length(); hs[c] = v.naCnt()==vlen || v.min()==v.max() ? null : make(fr._names[c],nbins,(byte)(v.isEnum() ? 2 : (v.isInt()?1:0)),minIn,maxEx,vlen,min_rows,doGrpSplit,isBinom); } return hs; }
java
static public DHistogram[] initialHist(Frame fr, int ncols, int nbins, DHistogram hs[], int min_rows, boolean doGrpSplit, boolean isBinom) { Vec vecs[] = fr.vecs(); for( int c=0; c<ncols; c++ ) { Vec v = vecs[c]; final float minIn = (float)Math.max(v.min(),-Float.MAX_VALUE); // inclusive vector min final float maxIn = (float)Math.min(v.max(), Float.MAX_VALUE); // inclusive vector max final float maxEx = find_maxEx(maxIn,v.isInt()?1:0); // smallest exclusive max final long vlen = v.length(); hs[c] = v.naCnt()==vlen || v.min()==v.max() ? null : make(fr._names[c],nbins,(byte)(v.isEnum() ? 2 : (v.isInt()?1:0)),minIn,maxEx,vlen,min_rows,doGrpSplit,isBinom); } return hs; }
[ "static", "public", "DHistogram", "[", "]", "initialHist", "(", "Frame", "fr", ",", "int", "ncols", ",", "int", "nbins", ",", "DHistogram", "hs", "[", "]", ",", "int", "min_rows", ",", "boolean", "doGrpSplit", ",", "boolean", "isBinom", ")", "{", "Vec", ...
The initial histogram bins are setup from the Vec rollups.
[ "The", "initial", "histogram", "bins", "are", "setup", "from", "the", "Vec", "rollups", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/gbm/DHistogram.java#L187-L199
train
h2oai/h2o-2
src/main/java/hex/gbm/DHistogram.java
DHistogram.isConstantResponse
public boolean isConstantResponse() { double m = Double.NaN; for( int b=0; b<_bins.length; b++ ) { if( _bins[b] == 0 ) continue; if( var(b) > 1e-14 ) return false; double mean = mean(b); if( mean != m ) if( Double.isNaN(m) ) m=mean; else if(Math.abs(m - mean) > 1e-6) return false; } return true; }
java
public boolean isConstantResponse() { double m = Double.NaN; for( int b=0; b<_bins.length; b++ ) { if( _bins[b] == 0 ) continue; if( var(b) > 1e-14 ) return false; double mean = mean(b); if( mean != m ) if( Double.isNaN(m) ) m=mean; else if(Math.abs(m - mean) > 1e-6) return false; } return true; }
[ "public", "boolean", "isConstantResponse", "(", ")", "{", "double", "m", "=", "Double", ".", "NaN", ";", "for", "(", "int", "b", "=", "0", ";", "b", "<", "_bins", ".", "length", ";", "b", "++", ")", "{", "if", "(", "_bins", "[", "b", "]", "==",...
Check for a constant response variable
[ "Check", "for", "a", "constant", "response", "variable" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/gbm/DHistogram.java#L208-L219
train
h2oai/h2o-2
src/main/java/water/Paxos.java
Paxos.lockCloud
static void lockCloud() { if( _cloudLocked ) return; // Fast-path cutout synchronized(Paxos.class) { while( !_commonKnowledge ) try { Paxos.class.wait(); } catch( InterruptedException ie ) { } _cloudLocked = true; } }
java
static void lockCloud() { if( _cloudLocked ) return; // Fast-path cutout synchronized(Paxos.class) { while( !_commonKnowledge ) try { Paxos.class.wait(); } catch( InterruptedException ie ) { } _cloudLocked = true; } }
[ "static", "void", "lockCloud", "(", ")", "{", "if", "(", "_cloudLocked", ")", "return", ";", "// Fast-path cutout", "synchronized", "(", "Paxos", ".", "class", ")", "{", "while", "(", "!", "_commonKnowledge", ")", "try", "{", "Paxos", ".", "class", ".", ...
change cloud shape - the distributed writes will be in the wrong place.
[ "change", "cloud", "shape", "-", "the", "distributed", "writes", "will", "be", "in", "the", "wrong", "place", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Paxos.java#L117-L124
train
h2oai/h2o-2
src/main/java/hex/FrameExtractor.java
FrameExtractor.makeTemplates
protected Vec[][] makeTemplates() { Vec anyVec = dataset.anyVec(); final long[][] espcPerSplit = computeEspcPerSplit(anyVec._espc, anyVec.length()); final int num = dataset.numCols(); // number of columns in input frame final int nsplits = espcPerSplit.length; // number of splits final String[][] domains = dataset.domains(); // domains final boolean[] uuids = dataset.uuids(); final byte[] times = dataset.times(); Vec[][] t = new Vec[nsplits][/*num*/]; // resulting vectors for all for (int i=0; i<nsplits; i++) { // vectors for j-th split t[i] = new Vec(Vec.newKey(),espcPerSplit[i/*-th split*/]).makeZeros(num, domains, uuids, times); } return t; }
java
protected Vec[][] makeTemplates() { Vec anyVec = dataset.anyVec(); final long[][] espcPerSplit = computeEspcPerSplit(anyVec._espc, anyVec.length()); final int num = dataset.numCols(); // number of columns in input frame final int nsplits = espcPerSplit.length; // number of splits final String[][] domains = dataset.domains(); // domains final boolean[] uuids = dataset.uuids(); final byte[] times = dataset.times(); Vec[][] t = new Vec[nsplits][/*num*/]; // resulting vectors for all for (int i=0; i<nsplits; i++) { // vectors for j-th split t[i] = new Vec(Vec.newKey(),espcPerSplit[i/*-th split*/]).makeZeros(num, domains, uuids, times); } return t; }
[ "protected", "Vec", "[", "]", "[", "]", "makeTemplates", "(", ")", "{", "Vec", "anyVec", "=", "dataset", ".", "anyVec", "(", ")", ";", "final", "long", "[", "]", "[", "]", "espcPerSplit", "=", "computeEspcPerSplit", "(", "anyVec", ".", "_espc", ",", ...
Create a templates for vector composing output frame
[ "Create", "a", "templates", "for", "vector", "composing", "output", "frame" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/FrameExtractor.java#L103-L117
train
h2oai/h2o-2
src/main/java/water/parser/XlsParser.java
XlsParser.guessSetup
public static PSetupGuess guessSetup(byte [] bits){ InputStream is = new ByteArrayInputStream(bits); XlsParser p = new XlsParser(); CustomInspectDataOut dout = new CustomInspectDataOut(); try{p.streamParse(is, dout);}catch(Exception e){} return new PSetupGuess(new ParserSetup(ParserType.XLS,CsvParser.AUTO_SEP,dout._ncols, dout._header,dout._header?dout.data()[0]:null,false),dout._nlines,dout._invalidLines,dout.data(),dout._nlines > dout._invalidLines,null); }
java
public static PSetupGuess guessSetup(byte [] bits){ InputStream is = new ByteArrayInputStream(bits); XlsParser p = new XlsParser(); CustomInspectDataOut dout = new CustomInspectDataOut(); try{p.streamParse(is, dout);}catch(Exception e){} return new PSetupGuess(new ParserSetup(ParserType.XLS,CsvParser.AUTO_SEP,dout._ncols, dout._header,dout._header?dout.data()[0]:null,false),dout._nlines,dout._invalidLines,dout.data(),dout._nlines > dout._invalidLines,null); }
[ "public", "static", "PSetupGuess", "guessSetup", "(", "byte", "[", "]", "bits", ")", "{", "InputStream", "is", "=", "new", "ByteArrayInputStream", "(", "bits", ")", ";", "XlsParser", "p", "=", "new", "XlsParser", "(", ")", ";", "CustomInspectDataOut", "dout"...
Try to parse the bits as svm light format, return SVMParser instance if the input is in svm light format, null otherwise. @param bits @return SVMLightPArser instance or null
[ "Try", "to", "parse", "the", "bits", "as", "svm", "light", "format", "return", "SVMParser", "instance", "if", "the", "input", "is", "in", "svm", "light", "format", "null", "otherwise", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/parser/XlsParser.java#L49-L55
train
h2oai/h2o-2
src/main/java/hex/la/DMatrix.java
DMatrix.mmul
public static Frame mmul(Frame x, Frame y) { MatrixMulJob mmj = new MatrixMulJob(Key.make("mmul" + ++cnt),Key.make("mmulProgress"),x,y); mmj.fork()._fjtask.join(); DKV.remove(mmj._dstKey); // do not leave garbage in KV mmj._z.reloadVecs(); return mmj._z; }
java
public static Frame mmul(Frame x, Frame y) { MatrixMulJob mmj = new MatrixMulJob(Key.make("mmul" + ++cnt),Key.make("mmulProgress"),x,y); mmj.fork()._fjtask.join(); DKV.remove(mmj._dstKey); // do not leave garbage in KV mmj._z.reloadVecs(); return mmj._z; }
[ "public", "static", "Frame", "mmul", "(", "Frame", "x", ",", "Frame", "y", ")", "{", "MatrixMulJob", "mmj", "=", "new", "MatrixMulJob", "(", "Key", ".", "make", "(", "\"mmul\"", "+", "++", "cnt", ")", ",", "Key", ".", "make", "(", "\"mmulProgress\"", ...
to be invoked from R expression
[ "to", "be", "invoked", "from", "R", "expression" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/la/DMatrix.java#L247-L253
train
h2oai/h2o-2
src/main/java/water/DRemoteTask.java
DRemoteTask.invokeOnAllNodes
public T invokeOnAllNodes() { H2O cloud = H2O.CLOUD; Key[] args = new Key[cloud.size()]; String skey = "RunOnAll"+Key.rand(); for( int i = 0; i < args.length; ++i ) args[i] = Key.make(skey,(byte)0,Key.DFJ_INTERNAL_USER,cloud._memary[i]); invoke(args); for( Key arg : args ) DKV.remove(arg); return self(); }
java
public T invokeOnAllNodes() { H2O cloud = H2O.CLOUD; Key[] args = new Key[cloud.size()]; String skey = "RunOnAll"+Key.rand(); for( int i = 0; i < args.length; ++i ) args[i] = Key.make(skey,(byte)0,Key.DFJ_INTERNAL_USER,cloud._memary[i]); invoke(args); for( Key arg : args ) DKV.remove(arg); return self(); }
[ "public", "T", "invokeOnAllNodes", "(", ")", "{", "H2O", "cloud", "=", "H2O", ".", "CLOUD", ";", "Key", "[", "]", "args", "=", "new", "Key", "[", "cloud", ".", "size", "(", ")", "]", ";", "String", "skey", "=", "\"RunOnAll\"", "+", "Key", ".", "r...
Invokes the task on all nodes
[ "Invokes", "the", "task", "on", "all", "nodes" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/DRemoteTask.java#L44-L53
train
h2oai/h2o-2
src/main/java/water/DRemoteTask.java
DRemoteTask.block
@Override public boolean block() throws InterruptedException { while( !isDone() ) { try { get(); } catch(ExecutionException eex) { // skip the execution part Throwable tex = eex.getCause(); if( tex instanceof Error) throw ( Error)tex; if( tex instanceof DistributedException) throw ( DistributedException)tex; if( tex instanceof JobCancelledException) throw (JobCancelledException)tex; throw new RuntimeException(tex); } catch(CancellationException cex) { Log.errRTExcept(cex); } } return true; }
java
@Override public boolean block() throws InterruptedException { while( !isDone() ) { try { get(); } catch(ExecutionException eex) { // skip the execution part Throwable tex = eex.getCause(); if( tex instanceof Error) throw ( Error)tex; if( tex instanceof DistributedException) throw ( DistributedException)tex; if( tex instanceof JobCancelledException) throw (JobCancelledException)tex; throw new RuntimeException(tex); } catch(CancellationException cex) { Log.errRTExcept(cex); } } return true; }
[ "@", "Override", "public", "boolean", "block", "(", ")", "throws", "InterruptedException", "{", "while", "(", "!", "isDone", "(", ")", ")", "{", "try", "{", "get", "(", ")", ";", "}", "catch", "(", "ExecutionException", "eex", ")", "{", "// skip the exec...
deadlock is otherwise all threads would block on waits.
[ "deadlock", "is", "otherwise", "all", "threads", "would", "block", "on", "waits", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/DRemoteTask.java#L73-L86
train
h2oai/h2o-2
src/main/java/water/DRemoteTask.java
DRemoteTask.dcompute
private final void dcompute() {// Work to do the distribution // Split out the keys into disjointly-homed sets of keys. // Find the split point. First find the range of home-indices. H2O cloud = H2O.CLOUD; int lo=cloud._memary.length, hi=-1; for( Key k : _keys ) { int i = k.home(cloud); if( i<lo ) lo=i; if( i>hi ) hi=i; // lo <= home(keys) <= hi } // Classic fork/join, but on CPUs. // Split into 3 arrays of keys: lo keys, hi keys and self keys final ArrayList<Key> locals = new ArrayList<Key>(); final ArrayList<Key> lokeys = new ArrayList<Key>(); final ArrayList<Key> hikeys = new ArrayList<Key>(); int self_idx = cloud.nidx(H2O.SELF); int mid = (lo+hi)>>>1; // Mid-point for( Key k : _keys ) { int idx = k.home(cloud); if( idx == self_idx ) locals.add(k); else if( idx < mid ) lokeys.add(k); else hikeys.add(k); } // Launch off 2 tasks for the other sets of keys, and get a place-holder // for results to block on. _lo = remote_compute(lokeys); _hi = remote_compute(hikeys); // Setup for local recursion: just use the local keys. if( locals.size() != 0 ) { // Shortcut for no local work _local = clone(); // 'this' is completer for '_local', so awaits _local completion _local._is_local = true; _local._keys = locals.toArray(new Key[locals.size()]); // Keys, including local keys (if any) _local.init(); // One-time top-level init H2O.submitTask(_local); // Begin normal execution on a FJ thread } else { tryComplete(); // No local work, so just immediate tryComplete } }
java
private final void dcompute() {// Work to do the distribution // Split out the keys into disjointly-homed sets of keys. // Find the split point. First find the range of home-indices. H2O cloud = H2O.CLOUD; int lo=cloud._memary.length, hi=-1; for( Key k : _keys ) { int i = k.home(cloud); if( i<lo ) lo=i; if( i>hi ) hi=i; // lo <= home(keys) <= hi } // Classic fork/join, but on CPUs. // Split into 3 arrays of keys: lo keys, hi keys and self keys final ArrayList<Key> locals = new ArrayList<Key>(); final ArrayList<Key> lokeys = new ArrayList<Key>(); final ArrayList<Key> hikeys = new ArrayList<Key>(); int self_idx = cloud.nidx(H2O.SELF); int mid = (lo+hi)>>>1; // Mid-point for( Key k : _keys ) { int idx = k.home(cloud); if( idx == self_idx ) locals.add(k); else if( idx < mid ) lokeys.add(k); else hikeys.add(k); } // Launch off 2 tasks for the other sets of keys, and get a place-holder // for results to block on. _lo = remote_compute(lokeys); _hi = remote_compute(hikeys); // Setup for local recursion: just use the local keys. if( locals.size() != 0 ) { // Shortcut for no local work _local = clone(); // 'this' is completer for '_local', so awaits _local completion _local._is_local = true; _local._keys = locals.toArray(new Key[locals.size()]); // Keys, including local keys (if any) _local.init(); // One-time top-level init H2O.submitTask(_local); // Begin normal execution on a FJ thread } else { tryComplete(); // No local work, so just immediate tryComplete } }
[ "private", "final", "void", "dcompute", "(", ")", "{", "// Work to do the distribution", "// Split out the keys into disjointly-homed sets of keys.", "// Find the split point. First find the range of home-indices.", "H2O", "cloud", "=", "H2O", ".", "CLOUD", ";", "int", "lo", "...
Override to specify local work
[ "Override", "to", "specify", "local", "work" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/DRemoteTask.java#L104-L144
train
h2oai/h2o-2
src/main/java/water/DRemoteTask.java
DRemoteTask.donCompletion
private final void donCompletion( CountedCompleter caller ) { // Distributed completion assert _lo == null || _lo.isDone(); assert _hi == null || _hi.isDone(); // Fold up results from left & right subtrees if( _lo != null ) reduce2(_lo.get()); if( _hi != null ) reduce2(_hi.get()); if( _local != null ) reduce2(_local ); // Note: in theory (valid semantics) we could push these "over the wire" // and block for them as we're blocking for the top-level initial split. // However, that would require sending "isDone" flags over the wire also. // MUCH simpler to just block for them all now, and send over the empty set // of not-yet-blocked things. if(_local != null && _local._fs != null ) _local._fs.blockForPending(); // Block on all other pending tasks, also _keys = null; // Do not return _keys over wire if( _top_level ) postGlobal(); }
java
private final void donCompletion( CountedCompleter caller ) { // Distributed completion assert _lo == null || _lo.isDone(); assert _hi == null || _hi.isDone(); // Fold up results from left & right subtrees if( _lo != null ) reduce2(_lo.get()); if( _hi != null ) reduce2(_hi.get()); if( _local != null ) reduce2(_local ); // Note: in theory (valid semantics) we could push these "over the wire" // and block for them as we're blocking for the top-level initial split. // However, that would require sending "isDone" flags over the wire also. // MUCH simpler to just block for them all now, and send over the empty set // of not-yet-blocked things. if(_local != null && _local._fs != null ) _local._fs.blockForPending(); // Block on all other pending tasks, also _keys = null; // Do not return _keys over wire if( _top_level ) postGlobal(); }
[ "private", "final", "void", "donCompletion", "(", "CountedCompleter", "caller", ")", "{", "// Distributed completion", "assert", "_lo", "==", "null", "||", "_lo", ".", "isDone", "(", ")", ";", "assert", "_hi", "==", "null", "||", "_hi", ".", "isDone", "(", ...
Override for local completion
[ "Override", "for", "local", "completion" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/DRemoteTask.java#L148-L164
train
h2oai/h2o-2
src/main/java/water/api/RequestArguments.java
RequestArguments.argumentsToJson
protected JsonObject argumentsToJson() { JsonObject result = new JsonObject(); for (Argument a : _arguments) { if (a.specified()) result.addProperty(a._name,a.originalValue()); } return result; }
java
protected JsonObject argumentsToJson() { JsonObject result = new JsonObject(); for (Argument a : _arguments) { if (a.specified()) result.addProperty(a._name,a.originalValue()); } return result; }
[ "protected", "JsonObject", "argumentsToJson", "(", ")", "{", "JsonObject", "result", "=", "new", "JsonObject", "(", ")", ";", "for", "(", "Argument", "a", ":", "_arguments", ")", "{", "if", "(", "a", ".", "specified", "(", ")", ")", "result", ".", "add...
Returns a json object containing all arguments specified to the page. Useful for redirects and polling.
[ "Returns", "a", "json", "object", "containing", "all", "arguments", "specified", "to", "the", "page", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/api/RequestArguments.java#L56-L63
train
h2oai/h2o-2
src/main/java/hex/singlenoderf/SpeeDRF.java
SpeeDRF.init
@Override protected void init() { super.init(); assert 0 <= ntrees && ntrees < 1000000; // Sanity check // Not enough rows to run if (source.numRows() - response.naCnt() <=0) throw new IllegalArgumentException("Dataset contains too many NAs!"); if( !classification && (!(response.isEnum() || response.isInt()))) throw new IllegalArgumentException("Classification cannot be performed on a float column!"); if(classification) { if (0.0f > sample_rate || sample_rate > 1.0f) throw new IllegalArgumentException("Sampling rate must be in [0,1] but found " + sample_rate); } if(regression) throw new IllegalArgumentException("SpeeDRF does not currently support regression."); }
java
@Override protected void init() { super.init(); assert 0 <= ntrees && ntrees < 1000000; // Sanity check // Not enough rows to run if (source.numRows() - response.naCnt() <=0) throw new IllegalArgumentException("Dataset contains too many NAs!"); if( !classification && (!(response.isEnum() || response.isInt()))) throw new IllegalArgumentException("Classification cannot be performed on a float column!"); if(classification) { if (0.0f > sample_rate || sample_rate > 1.0f) throw new IllegalArgumentException("Sampling rate must be in [0,1] but found " + sample_rate); } if(regression) throw new IllegalArgumentException("SpeeDRF does not currently support regression."); }
[ "@", "Override", "protected", "void", "init", "(", ")", "{", "super", ".", "init", "(", ")", ";", "assert", "0", "<=", "ntrees", "&&", "ntrees", "<", "1000000", ";", "// Sanity check", "// Not enough rows to run", "if", "(", "source", ".", "numRows", "(", ...
Put here all precondition verification
[ "Put", "here", "all", "precondition", "verification" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/singlenoderf/SpeeDRF.java#L177-L194
train
h2oai/h2o-2
src/main/java/hex/singlenoderf/SpeeDRF.java
SpeeDRF.build
public static void build( final Key jobKey, final Key modelKey, final DRFParams drfParams, final Data localData, int ntrees, int numSplitFeatures, int[] rowsPerChunks) { Timer t_alltrees = new Timer(); Tree[] trees = new Tree[ntrees]; Log.info(Log.Tag.Sys.RANDF,"Building "+ntrees+" trees"); Log.info(Log.Tag.Sys.RANDF,"Number of split features: "+ numSplitFeatures); Log.info(Log.Tag.Sys.RANDF,"Starting RF computation with "+ localData.rows()+" rows "); Random rnd = Utils.getRNG(localData.seed() + ROOT_SEED_ADD); Sampling sampler = createSampler(drfParams, rowsPerChunks); byte producerId = (byte) H2O.SELF.index(); for (int i = 0; i < ntrees; ++i) { long treeSeed = rnd.nextLong() + TREE_SEED_INIT; // make sure that enough bits is initialized trees[i] = new Tree(jobKey, modelKey, localData, producerId, drfParams.max_depth, drfParams.stat_type, numSplitFeatures, treeSeed, i, drfParams._exclusiveSplitLimit, sampler, drfParams._verbose, drfParams.regression, !drfParams._useNonLocalData, ((SpeeDRFModel)UKV.get(modelKey)).score_pojo); } Log.info("Invoking the tree build tasks on all nodes."); DRemoteTask.invokeAll(trees); Log.info(Log.Tag.Sys.RANDF,"All trees ("+ntrees+") done in "+ t_alltrees); }
java
public static void build( final Key jobKey, final Key modelKey, final DRFParams drfParams, final Data localData, int ntrees, int numSplitFeatures, int[] rowsPerChunks) { Timer t_alltrees = new Timer(); Tree[] trees = new Tree[ntrees]; Log.info(Log.Tag.Sys.RANDF,"Building "+ntrees+" trees"); Log.info(Log.Tag.Sys.RANDF,"Number of split features: "+ numSplitFeatures); Log.info(Log.Tag.Sys.RANDF,"Starting RF computation with "+ localData.rows()+" rows "); Random rnd = Utils.getRNG(localData.seed() + ROOT_SEED_ADD); Sampling sampler = createSampler(drfParams, rowsPerChunks); byte producerId = (byte) H2O.SELF.index(); for (int i = 0; i < ntrees; ++i) { long treeSeed = rnd.nextLong() + TREE_SEED_INIT; // make sure that enough bits is initialized trees[i] = new Tree(jobKey, modelKey, localData, producerId, drfParams.max_depth, drfParams.stat_type, numSplitFeatures, treeSeed, i, drfParams._exclusiveSplitLimit, sampler, drfParams._verbose, drfParams.regression, !drfParams._useNonLocalData, ((SpeeDRFModel)UKV.get(modelKey)).score_pojo); } Log.info("Invoking the tree build tasks on all nodes."); DRemoteTask.invokeAll(trees); Log.info(Log.Tag.Sys.RANDF,"All trees ("+ntrees+") done in "+ t_alltrees); }
[ "public", "static", "void", "build", "(", "final", "Key", "jobKey", ",", "final", "Key", "modelKey", ",", "final", "DRFParams", "drfParams", ",", "final", "Data", "localData", ",", "int", "ntrees", ",", "int", "numSplitFeatures", ",", "int", "[", "]", "row...
Build random forest for data stored on this node.
[ "Build", "random", "forest", "for", "data", "stored", "on", "this", "node", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/singlenoderf/SpeeDRF.java#L580-L606
train
h2oai/h2o-2
h2o-samples/src/main/java/samples/expert/WebAPI.java
WebAPI.listJobs
static void listJobs() throws Exception { HttpClient client = new HttpClient(); GetMethod get = new GetMethod(URL + "/Jobs.json"); int status = client.executeMethod(get); if( status != 200 ) throw new Exception(get.getStatusText()); Gson gson = new Gson(); JobsRes res = gson.fromJson(new InputStreamReader(get.getResponseBodyAsStream()), JobsRes.class); System.out.println("Running jobs:"); for( Job job : res.jobs ) System.out.println(job.description + " " + job.destination_key); get.releaseConnection(); }
java
static void listJobs() throws Exception { HttpClient client = new HttpClient(); GetMethod get = new GetMethod(URL + "/Jobs.json"); int status = client.executeMethod(get); if( status != 200 ) throw new Exception(get.getStatusText()); Gson gson = new Gson(); JobsRes res = gson.fromJson(new InputStreamReader(get.getResponseBodyAsStream()), JobsRes.class); System.out.println("Running jobs:"); for( Job job : res.jobs ) System.out.println(job.description + " " + job.destination_key); get.releaseConnection(); }
[ "static", "void", "listJobs", "(", ")", "throws", "Exception", "{", "HttpClient", "client", "=", "new", "HttpClient", "(", ")", ";", "GetMethod", "get", "=", "new", "GetMethod", "(", "URL", "+", "\"/Jobs.json\"", ")", ";", "int", "status", "=", "client", ...
Lists jobs currently running.
[ "Lists", "jobs", "currently", "running", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/h2o-samples/src/main/java/samples/expert/WebAPI.java#L38-L50
train
h2oai/h2o-2
h2o-samples/src/main/java/samples/expert/WebAPI.java
WebAPI.exportModel
static void exportModel() throws Exception { HttpClient client = new HttpClient(); GetMethod get = new GetMethod(URL + "/2/ExportModel.json?model=MyInitialNeuralNet"); int status = client.executeMethod(get); if( status != 200 ) throw new Exception(get.getStatusText()); JsonObject response = (JsonObject) new JsonParser().parse(new InputStreamReader(get.getResponseBodyAsStream())); JsonElement model = response.get("model"); JsonWriter writer = new JsonWriter(new FileWriter(JSON_FILE)); writer.setLenient(true); writer.setIndent(" "); Streams.write(model, writer); writer.close(); get.releaseConnection(); }
java
static void exportModel() throws Exception { HttpClient client = new HttpClient(); GetMethod get = new GetMethod(URL + "/2/ExportModel.json?model=MyInitialNeuralNet"); int status = client.executeMethod(get); if( status != 200 ) throw new Exception(get.getStatusText()); JsonObject response = (JsonObject) new JsonParser().parse(new InputStreamReader(get.getResponseBodyAsStream())); JsonElement model = response.get("model"); JsonWriter writer = new JsonWriter(new FileWriter(JSON_FILE)); writer.setLenient(true); writer.setIndent(" "); Streams.write(model, writer); writer.close(); get.releaseConnection(); }
[ "static", "void", "exportModel", "(", ")", "throws", "Exception", "{", "HttpClient", "client", "=", "new", "HttpClient", "(", ")", ";", "GetMethod", "get", "=", "new", "GetMethod", "(", "URL", "+", "\"/2/ExportModel.json?model=MyInitialNeuralNet\"", ")", ";", "i...
Exports a model to a JSON file.
[ "Exports", "a", "model", "to", "a", "JSON", "file", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/h2o-samples/src/main/java/samples/expert/WebAPI.java#L67-L81
train
h2oai/h2o-2
h2o-samples/src/main/java/samples/expert/WebAPI.java
WebAPI.importModel
public static void importModel() throws Exception { // Upload file to H2O HttpClient client = new HttpClient(); PostMethod post = new PostMethod(URL + "/Upload.json?key=" + JSON_FILE.getName()); Part[] parts = { new FilePart(JSON_FILE.getName(), JSON_FILE) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); if( 200 != client.executeMethod(post) ) throw new RuntimeException("Request failed: " + post.getStatusLine()); post.releaseConnection(); // Parse the key into a model GetMethod get = new GetMethod(URL + "/2/ImportModel.json?" // + "destination_key=MyImportedNeuralNet&" // + "type=NeuralNetModel&" // + "json=" + JSON_FILE.getName()); if( 200 != client.executeMethod(get) ) throw new RuntimeException("Request failed: " + get.getStatusLine()); get.releaseConnection(); }
java
public static void importModel() throws Exception { // Upload file to H2O HttpClient client = new HttpClient(); PostMethod post = new PostMethod(URL + "/Upload.json?key=" + JSON_FILE.getName()); Part[] parts = { new FilePart(JSON_FILE.getName(), JSON_FILE) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); if( 200 != client.executeMethod(post) ) throw new RuntimeException("Request failed: " + post.getStatusLine()); post.releaseConnection(); // Parse the key into a model GetMethod get = new GetMethod(URL + "/2/ImportModel.json?" // + "destination_key=MyImportedNeuralNet&" // + "type=NeuralNetModel&" // + "json=" + JSON_FILE.getName()); if( 200 != client.executeMethod(get) ) throw new RuntimeException("Request failed: " + get.getStatusLine()); get.releaseConnection(); }
[ "public", "static", "void", "importModel", "(", ")", "throws", "Exception", "{", "// Upload file to H2O", "HttpClient", "client", "=", "new", "HttpClient", "(", ")", ";", "PostMethod", "post", "=", "new", "PostMethod", "(", "URL", "+", "\"/Upload.json?key=\"", "...
Imports a model from a JSON file.
[ "Imports", "a", "model", "from", "a", "JSON", "file", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/h2o-samples/src/main/java/samples/expert/WebAPI.java#L86-L104
train
h2oai/h2o-2
src/main/java/hex/singlenoderf/DABuilder.java
DABuilder.checkAndLimitFeatureUsedPerSplit
private void checkAndLimitFeatureUsedPerSplit(Frame fr) { int validCols = fr.numCols()-1; // for classIdx column if (validCols < _rfParams.num_split_features) { Log.info(Log.Tag.Sys.RANDF, "Limiting features from " + _rfParams.num_split_features + " to " + validCols + " because there are no more valid columns in the dataset"); _rfParams.num_split_features= validCols; } }
java
private void checkAndLimitFeatureUsedPerSplit(Frame fr) { int validCols = fr.numCols()-1; // for classIdx column if (validCols < _rfParams.num_split_features) { Log.info(Log.Tag.Sys.RANDF, "Limiting features from " + _rfParams.num_split_features + " to " + validCols + " because there are no more valid columns in the dataset"); _rfParams.num_split_features= validCols; } }
[ "private", "void", "checkAndLimitFeatureUsedPerSplit", "(", "Frame", "fr", ")", "{", "int", "validCols", "=", "fr", ".", "numCols", "(", ")", "-", "1", ";", "// for classIdx column", "if", "(", "validCols", "<", "_rfParams", ".", "num_split_features", ")", "{"...
Check that we have proper number of valid columns vs. features selected, if not cap
[ "Check", "that", "we", "have", "proper", "number", "of", "valid", "columns", "vs", ".", "features", "selected", "if", "not", "cap" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/singlenoderf/DABuilder.java#L34-L41
train
h2oai/h2o-2
src/main/java/hex/singlenoderf/DABuilder.java
DABuilder.getChunkId
private long getChunkId(final Frame fr) { Key[] keys = new Key[fr.anyVec().nChunks()]; for(int i = 0; i < fr.anyVec().nChunks(); ++i) { keys[i] = fr.anyVec().chunkKey(i); } for(int i = 0; i < keys.length; ++i) { if (keys[i].home()) return i; } return -99999; //throw new Error("No key on this node"); }
java
private long getChunkId(final Frame fr) { Key[] keys = new Key[fr.anyVec().nChunks()]; for(int i = 0; i < fr.anyVec().nChunks(); ++i) { keys[i] = fr.anyVec().chunkKey(i); } for(int i = 0; i < keys.length; ++i) { if (keys[i].home()) return i; } return -99999; //throw new Error("No key on this node"); }
[ "private", "long", "getChunkId", "(", "final", "Frame", "fr", ")", "{", "Key", "[", "]", "keys", "=", "new", "Key", "[", "fr", ".", "anyVec", "(", ")", ".", "nChunks", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "fr",...
Return chunk index of the first chunk on this node. Used to identify the trees built here.
[ "Return", "chunk", "index", "of", "the", "first", "chunk", "on", "this", "node", ".", "Used", "to", "identify", "the", "trees", "built", "here", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/singlenoderf/DABuilder.java#L47-L56
train
h2oai/h2o-2
src/main/java/water/api/RequestStatics.java
RequestStatics.JSON2HTML
public static String JSON2HTML(String name) { if( name.length() < 1 ) return name; if(name == "row") { return name.substring(0,1).toUpperCase()+ name.replace("_"," ").substring(1); } return name.substring(0,1)+name.replace("_"," ").substring(1); }
java
public static String JSON2HTML(String name) { if( name.length() < 1 ) return name; if(name == "row") { return name.substring(0,1).toUpperCase()+ name.replace("_"," ").substring(1); } return name.substring(0,1)+name.replace("_"," ").substring(1); }
[ "public", "static", "String", "JSON2HTML", "(", "String", "name", ")", "{", "if", "(", "name", ".", "length", "(", ")", "<", "1", ")", "return", "name", ";", "if", "(", "name", "==", "\"row\"", ")", "{", "return", "name", ".", "substring", "(", "0"...
Returns the name of the JSON property pretty printed. That is spaces instead of underscores and capital first letter. @param name @return
[ "Returns", "the", "name", "of", "the", "JSON", "property", "pretty", "printed", ".", "That", "is", "spaces", "instead", "of", "underscores", "and", "capital", "first", "letter", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/api/RequestStatics.java#L93-L99
train
h2oai/h2o-2
src/main/java/water/parser/SVMLightParser.java
SVMLightParser.guessSetup
public static PSetupGuess guessSetup(byte [] bytes){ // find the last eof int i = bytes.length-1; while(i > 0 && bytes[i] != '\n')--i; assert i >= 0; InputStream is = new ByteArrayInputStream(Arrays.copyOf(bytes,i)); SVMLightParser p = new SVMLightParser(new ParserSetup(ParserType.SVMLight, CsvParser.AUTO_SEP, false)); InspectDataOut dout = new InspectDataOut(); try{p.streamParse(is, dout);}catch(Exception e){throw new RuntimeException(e);} return new PSetupGuess(new ParserSetup(ParserType.SVMLight, CsvParser.AUTO_SEP, dout._ncols,false,null,false),dout._nlines,dout._invalidLines,dout.data(),dout._ncols > 0 && dout._nlines > 0 && dout._nlines > dout._invalidLines,dout.errors()); }
java
public static PSetupGuess guessSetup(byte [] bytes){ // find the last eof int i = bytes.length-1; while(i > 0 && bytes[i] != '\n')--i; assert i >= 0; InputStream is = new ByteArrayInputStream(Arrays.copyOf(bytes,i)); SVMLightParser p = new SVMLightParser(new ParserSetup(ParserType.SVMLight, CsvParser.AUTO_SEP, false)); InspectDataOut dout = new InspectDataOut(); try{p.streamParse(is, dout);}catch(Exception e){throw new RuntimeException(e);} return new PSetupGuess(new ParserSetup(ParserType.SVMLight, CsvParser.AUTO_SEP, dout._ncols,false,null,false),dout._nlines,dout._invalidLines,dout.data(),dout._ncols > 0 && dout._nlines > 0 && dout._nlines > dout._invalidLines,dout.errors()); }
[ "public", "static", "PSetupGuess", "guessSetup", "(", "byte", "[", "]", "bytes", ")", "{", "// find the last eof", "int", "i", "=", "bytes", ".", "length", "-", "1", ";", "while", "(", "i", ">", "0", "&&", "bytes", "[", "i", "]", "!=", "'", "'", ")...
Try to parse the bytes as svm light format, return SVMParser instance if the input is in svm light format, null otherwise. @param bytes @return SVMLightPArser instance or null
[ "Try", "to", "parse", "the", "bytes", "as", "svm", "light", "format", "return", "SVMParser", "instance", "if", "the", "input", "is", "in", "svm", "light", "format", "null", "otherwise", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/parser/SVMLightParser.java#L52-L62
train
h2oai/h2o-2
src/main/java/water/nbhm/UtilUnsafe.java
UtilUnsafe.getUnsafe
public static Unsafe getUnsafe() { // Not on bootclasspath if( UtilUnsafe.class.getClassLoader() == null ) return Unsafe.getUnsafe(); try { final Field fld = Unsafe.class.getDeclaredField("theUnsafe"); fld.setAccessible(true); return (Unsafe) fld.get(UtilUnsafe.class); } catch (Exception e) { throw new RuntimeException("Could not obtain access to sun.misc.Unsafe", e); } }
java
public static Unsafe getUnsafe() { // Not on bootclasspath if( UtilUnsafe.class.getClassLoader() == null ) return Unsafe.getUnsafe(); try { final Field fld = Unsafe.class.getDeclaredField("theUnsafe"); fld.setAccessible(true); return (Unsafe) fld.get(UtilUnsafe.class); } catch (Exception e) { throw new RuntimeException("Could not obtain access to sun.misc.Unsafe", e); } }
[ "public", "static", "Unsafe", "getUnsafe", "(", ")", "{", "// Not on bootclasspath", "if", "(", "UtilUnsafe", ".", "class", ".", "getClassLoader", "(", ")", "==", "null", ")", "return", "Unsafe", ".", "getUnsafe", "(", ")", ";", "try", "{", "final", "Field...
Fetch the Unsafe. Use With Caution.
[ "Fetch", "the", "Unsafe", ".", "Use", "With", "Caution", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/nbhm/UtilUnsafe.java#L17-L28
train
h2oai/h2o-2
src/main/java/hex/deeplearning/Neurons.java
Linear.bprop
protected void bprop(float target) { assert (target != missing_real_value); if (params.loss != Loss.MeanSquare) throw new UnsupportedOperationException("Regression is only implemented for MeanSquare error."); final int row = 0; // Computing partial derivative: dE/dnet = dE/dy * dy/dnet = dE/dy * 1 final float g = target - _a.get(row); //for MSE -dMSE/dy = target-y float m = momentum(); float r = _minfo.adaDelta() ? 0 : rate(_minfo.get_processed_total()) * (1f - m); bprop(row, g, r, m); }
java
protected void bprop(float target) { assert (target != missing_real_value); if (params.loss != Loss.MeanSquare) throw new UnsupportedOperationException("Regression is only implemented for MeanSquare error."); final int row = 0; // Computing partial derivative: dE/dnet = dE/dy * dy/dnet = dE/dy * 1 final float g = target - _a.get(row); //for MSE -dMSE/dy = target-y float m = momentum(); float r = _minfo.adaDelta() ? 0 : rate(_minfo.get_processed_total()) * (1f - m); bprop(row, g, r, m); }
[ "protected", "void", "bprop", "(", "float", "target", ")", "{", "assert", "(", "target", "!=", "missing_real_value", ")", ";", "if", "(", "params", ".", "loss", "!=", "Loss", ".", "MeanSquare", ")", "throw", "new", "UnsupportedOperationException", "(", "\"Re...
Backpropagation for regression @param target floating-point target value
[ "Backpropagation", "for", "regression" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/deeplearning/Neurons.java#L1041-L1050
train
h2oai/h2o-2
src/main/java/water/score/ScorecardModel.java
ScorecardModel.score_interpreter
public double score_interpreter(final HashMap<String, Comparable> row ) { double score = _initialScore; for( int i=0; i<_rules.length; i++ ) score += _rules[i].score(row.get(_colNames[i])); return score; }
java
public double score_interpreter(final HashMap<String, Comparable> row ) { double score = _initialScore; for( int i=0; i<_rules.length; i++ ) score += _rules[i].score(row.get(_colNames[i])); return score; }
[ "public", "double", "score_interpreter", "(", "final", "HashMap", "<", "String", ",", "Comparable", ">", "row", ")", "{", "double", "score", "=", "_initialScore", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "_rules", ".", "length", ";", "i", ...
Use the rule interpreter
[ "Use", "the", "rule", "interpreter" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/score/ScorecardModel.java#L35-L40
train
h2oai/h2o-2
src/main/java/water/score/ScorecardModel.java
ScorecardModel.getName
public static String getName( String pname, DataTypes type, StringBuilder sb ) { String jname = xml2jname(pname); // Emit the code to do the load return jname; }
java
public static String getName( String pname, DataTypes type, StringBuilder sb ) { String jname = xml2jname(pname); // Emit the code to do the load return jname; }
[ "public", "static", "String", "getName", "(", "String", "pname", ",", "DataTypes", "type", ",", "StringBuilder", "sb", ")", "{", "String", "jname", "=", "xml2jname", "(", "pname", ")", ";", "// Emit the code to do the load", "return", "jname", ";", "}" ]
to emit it at runtime.
[ "to", "emit", "it", "at", "runtime", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/score/ScorecardModel.java#L96-L101
train
h2oai/h2o-2
src/main/java/water/Key.java
Key.set_cache
private boolean set_cache( long cache ) { while( true ) { // Spin till get it long old = _cache; // Read once at the start if( !H2O.larger(cloud(cache),cloud(old)) ) // Rolling backwards? // Attempt to set for an older Cloud. Blow out with a failure; caller // should retry on a new Cloud. return false; assert cloud(cache) != cloud(old) || cache == old; if( old == cache ) return true; // Fast-path cutout if( _cacheUpdater.compareAndSet(this,old,cache) ) return true; // Can fail if the cache is really old, and just got updated to a version // which is still not the latest, and we are trying to update it again. } }
java
private boolean set_cache( long cache ) { while( true ) { // Spin till get it long old = _cache; // Read once at the start if( !H2O.larger(cloud(cache),cloud(old)) ) // Rolling backwards? // Attempt to set for an older Cloud. Blow out with a failure; caller // should retry on a new Cloud. return false; assert cloud(cache) != cloud(old) || cache == old; if( old == cache ) return true; // Fast-path cutout if( _cacheUpdater.compareAndSet(this,old,cache) ) return true; // Can fail if the cache is really old, and just got updated to a version // which is still not the latest, and we are trying to update it again. } }
[ "private", "boolean", "set_cache", "(", "long", "cache", ")", "{", "while", "(", "true", ")", "{", "// Spin till get it", "long", "old", "=", "_cache", ";", "// Read once at the start", "if", "(", "!", "H2O", ".", "larger", "(", "cloud", "(", "cache", ")",...
Update the cache, but only to strictly newer Clouds
[ "Update", "the", "cache", "but", "only", "to", "strictly", "newer", "Clouds" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Key.java#L161-L174
train
h2oai/h2o-2
src/main/java/water/Key.java
Key.cloud_info
public long cloud_info( H2O cloud ) { long x = _cache; // See if cached for this Cloud. This should be the 99% fast case. if( cloud(x) == cloud._idx ) return x; // Cache missed! Probaby it just needs (atomic) updating. // But we might be holding the stale cloud... // Figure out home Node in this Cloud char home = (char)D(0); // Figure out what replica # I am, if any int desired = desired(x); int replica = -1; for( int i=0; i<desired; i++ ) { int idx = D(i); if( idx >= 0 && cloud._memary[idx] == H2O.SELF ) { replica = i; break; } } long cache = build_cache(cloud._idx,home,replica,desired); set_cache(cache); // Attempt to upgrade cache, but ignore failure return cache; // Return the magic word for this Cloud }
java
public long cloud_info( H2O cloud ) { long x = _cache; // See if cached for this Cloud. This should be the 99% fast case. if( cloud(x) == cloud._idx ) return x; // Cache missed! Probaby it just needs (atomic) updating. // But we might be holding the stale cloud... // Figure out home Node in this Cloud char home = (char)D(0); // Figure out what replica # I am, if any int desired = desired(x); int replica = -1; for( int i=0; i<desired; i++ ) { int idx = D(i); if( idx >= 0 && cloud._memary[idx] == H2O.SELF ) { replica = i; break; } } long cache = build_cache(cloud._idx,home,replica,desired); set_cache(cache); // Attempt to upgrade cache, but ignore failure return cache; // Return the magic word for this Cloud }
[ "public", "long", "cloud_info", "(", "H2O", "cloud", ")", "{", "long", "x", "=", "_cache", ";", "// See if cached for this Cloud. This should be the 99% fast case.", "if", "(", "cloud", "(", "x", ")", "==", "cloud", ".", "_idx", ")", "return", "x", ";", "// Ca...
Return the info word for this Cloud. Use the cache if possible
[ "Return", "the", "info", "word", "for", "this", "Cloud", ".", "Use", "the", "cache", "if", "possible" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Key.java#L176-L198
train
h2oai/h2o-2
src/main/java/water/Key.java
Key.make
static public Key make(byte[] kb, byte rf) { if( rf == -1 ) throw new IllegalArgumentException(); Key key = new Key(kb); Key key2 = H2O.getk(key); // Get the interned version, if any if( key2 != null ) // There is one! Return it instead return key2; // Set the cache with desired replication factor, and a fake cloud index H2O cloud = H2O.CLOUD; // Read once key._cache = build_cache(cloud._idx-1,0,0,rf); key.cloud_info(cloud); // Now compute & cache the real data return key; }
java
static public Key make(byte[] kb, byte rf) { if( rf == -1 ) throw new IllegalArgumentException(); Key key = new Key(kb); Key key2 = H2O.getk(key); // Get the interned version, if any if( key2 != null ) // There is one! Return it instead return key2; // Set the cache with desired replication factor, and a fake cloud index H2O cloud = H2O.CLOUD; // Read once key._cache = build_cache(cloud._idx-1,0,0,rf); key.cloud_info(cloud); // Now compute & cache the real data return key; }
[ "static", "public", "Key", "make", "(", "byte", "[", "]", "kb", ",", "byte", "rf", ")", "{", "if", "(", "rf", "==", "-", "1", ")", "throw", "new", "IllegalArgumentException", "(", ")", ";", "Key", "key", "=", "new", "Key", "(", "kb", ")", ";", ...
Make new Keys. Optimistically attempt interning, but no guarantee.
[ "Make", "new", "Keys", ".", "Optimistically", "attempt", "interning", "but", "no", "guarantee", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Key.java#L222-L234
train
h2oai/h2o-2
src/main/java/water/Key.java
Key.rand
static public String rand() { UUID uid = UUID.randomUUID(); long l1 = uid.getLeastSignificantBits(); long l2 = uid. getMostSignificantBits(); return "_"+Long.toHexString(l1)+Long.toHexString(l2); }
java
static public String rand() { UUID uid = UUID.randomUUID(); long l1 = uid.getLeastSignificantBits(); long l2 = uid. getMostSignificantBits(); return "_"+Long.toHexString(l1)+Long.toHexString(l2); }
[ "static", "public", "String", "rand", "(", ")", "{", "UUID", "uid", "=", "UUID", ".", "randomUUID", "(", ")", ";", "long", "l1", "=", "uid", ".", "getLeastSignificantBits", "(", ")", ";", "long", "l2", "=", "uid", ".", "getMostSignificantBits", "(", ")...
A random string, useful as a Key name or partial Key suffix.
[ "A", "random", "string", "useful", "as", "a", "Key", "name", "or", "partial", "Key", "suffix", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Key.java#L237-L242
train
h2oai/h2o-2
src/main/java/water/Key.java
Key.make
static public Key make(String s, byte rf, byte systemType, H2ONode... replicas) { return make(decodeKeyName(s),rf,systemType,replicas); }
java
static public Key make(String s, byte rf, byte systemType, H2ONode... replicas) { return make(decodeKeyName(s),rf,systemType,replicas); }
[ "static", "public", "Key", "make", "(", "String", "s", ",", "byte", "rf", ",", "byte", "systemType", ",", "H2ONode", "...", "replicas", ")", "{", "return", "make", "(", "decodeKeyName", "(", "s", ")", ",", "rf", ",", "systemType", ",", "replicas", ")",...
If the addresses are not specified, returns a key with no home information.
[ "If", "the", "addresses", "are", "not", "specified", "returns", "a", "key", "with", "no", "home", "information", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Key.java#L252-L254
train
h2oai/h2o-2
src/main/java/water/Key.java
Key.make
static public Key make(byte[] kb, byte rf, byte systemType, H2ONode... replicas) { // no more than 3 replicas allowed to be stored in the key assert 0 <=replicas.length && replicas.length<=3; assert systemType<32; // only system keys allowed // Key byte layout is: // 0 - systemType, from 0-31 // 1 - replica-count, plus up to 3 bits for ip4 vs ip6 // 2-n - zero, one, two or 3 IP4 (4+2 bytes) or IP6 (16+2 bytes) addresses // 2-5- 4 bytes of chunk#, or -1 for masters // n+ - repeat of the original kb AutoBuffer ab = new AutoBuffer(); ab.put1(systemType).put1(replicas.length); for( H2ONode h2o : replicas ) h2o.write(ab); ab.put4(-1); ab.putA1(kb,kb.length); return make(Arrays.copyOf(ab.buf(),ab.position()),rf); }
java
static public Key make(byte[] kb, byte rf, byte systemType, H2ONode... replicas) { // no more than 3 replicas allowed to be stored in the key assert 0 <=replicas.length && replicas.length<=3; assert systemType<32; // only system keys allowed // Key byte layout is: // 0 - systemType, from 0-31 // 1 - replica-count, plus up to 3 bits for ip4 vs ip6 // 2-n - zero, one, two or 3 IP4 (4+2 bytes) or IP6 (16+2 bytes) addresses // 2-5- 4 bytes of chunk#, or -1 for masters // n+ - repeat of the original kb AutoBuffer ab = new AutoBuffer(); ab.put1(systemType).put1(replicas.length); for( H2ONode h2o : replicas ) h2o.write(ab); ab.put4(-1); ab.putA1(kb,kb.length); return make(Arrays.copyOf(ab.buf(),ab.position()),rf); }
[ "static", "public", "Key", "make", "(", "byte", "[", "]", "kb", ",", "byte", "rf", ",", "byte", "systemType", ",", "H2ONode", "...", "replicas", ")", "{", "// no more than 3 replicas allowed to be stored in the key", "assert", "0", "<=", "replicas", ".", "length...
Make a Key which is homed to specific nodes.
[ "Make", "a", "Key", "which", "is", "homed", "to", "specific", "nodes", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Key.java#L261-L278
train
h2oai/h2o-2
src/main/java/water/Key.java
Key.makeSystem
final public static Key makeSystem(String s) { byte[] kb= decodeKeyName(s); byte[] kb2 = new byte[kb.length+1]; System.arraycopy(kb,0,kb2,1,kb.length); kb2[0] = Key.BUILT_IN_KEY; return Key.make(kb2); }
java
final public static Key makeSystem(String s) { byte[] kb= decodeKeyName(s); byte[] kb2 = new byte[kb.length+1]; System.arraycopy(kb,0,kb2,1,kb.length); kb2[0] = Key.BUILT_IN_KEY; return Key.make(kb2); }
[ "final", "public", "static", "Key", "makeSystem", "(", "String", "s", ")", "{", "byte", "[", "]", "kb", "=", "decodeKeyName", "(", "s", ")", ";", "byte", "[", "]", "kb2", "=", "new", "byte", "[", "kb", ".", "length", "+", "1", "]", ";", "System",...
Hide a user key by turning it into a system key of type HIDDEN_USER_KEY
[ "Hide", "a", "user", "key", "by", "turning", "it", "into", "a", "system", "key", "of", "type", "HIDDEN_USER_KEY" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/Key.java#L281-L287
train
h2oai/h2o-2
src/main/java/water/api/TutorialWorkflow.java
TutorialWorkflow.decorateActiveStep
protected void decorateActiveStep(final TutorStep step, StringBuilder sb) { sb.append("<h4>").append(step.summary()).append("</h4>"); sb.append(step.content()); }
java
protected void decorateActiveStep(final TutorStep step, StringBuilder sb) { sb.append("<h4>").append(step.summary()).append("</h4>"); sb.append(step.content()); }
[ "protected", "void", "decorateActiveStep", "(", "final", "TutorStep", "step", ",", "StringBuilder", "sb", ")", "{", "sb", ".", "append", "(", "\"<h4>\"", ")", ".", "append", "(", "step", ".", "summary", "(", ")", ")", ".", "append", "(", "\"</h4>\"", ")"...
Shows the active workflow step
[ "Shows", "the", "active", "workflow", "step" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/api/TutorialWorkflow.java#L34-L37
train
h2oai/h2o-2
src/main/java/water/util/JStackCollectorTask.java
JStackCollectorTask.reduce
@Override public void reduce(JStackCollectorTask that) { if( _result == null ) _result = that._result; else for (int i=0; i<_result.length; ++i) if (_result[i] == null) _result[i] = that._result[i]; }
java
@Override public void reduce(JStackCollectorTask that) { if( _result == null ) _result = that._result; else for (int i=0; i<_result.length; ++i) if (_result[i] == null) _result[i] = that._result[i]; }
[ "@", "Override", "public", "void", "reduce", "(", "JStackCollectorTask", "that", ")", "{", "if", "(", "_result", "==", "null", ")", "_result", "=", "that", ".", "_result", ";", "else", "for", "(", "int", "i", "=", "0", ";", "i", "<", "_result", ".", ...
for each node in the cloud it contains all threads stack traces
[ "for", "each", "node", "in", "the", "cloud", "it", "contains", "all", "threads", "stack", "traces" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/util/JStackCollectorTask.java#L11-L16
train
h2oai/h2o-2
src/main/java/water/genmodel/GeneratedModel.java
GeneratedModel.predict
public float[] predict( Map<String, Double> row, double data[], float preds[] ) { return predict(map(row,data),preds); }
java
public float[] predict( Map<String, Double> row, double data[], float preds[] ) { return predict(map(row,data),preds); }
[ "public", "float", "[", "]", "predict", "(", "Map", "<", "String", ",", "Double", ">", "row", ",", "double", "data", "[", "]", ",", "float", "preds", "[", "]", ")", "{", "return", "predict", "(", "map", "(", "row", ",", "data", ")", ",", "preds",...
Does the mapping lookup for every row, no allocation
[ "Does", "the", "mapping", "lookup", "for", "every", "row", "no", "allocation" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/genmodel/GeneratedModel.java#L83-L85
train
h2oai/h2o-2
hadoop/src/main/java/water/hadoop/h2omapper.java
h2omapper.emitLogHeader
private void emitLogHeader(Context context, String mapredTaskId) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); Text textId = new Text(mapredTaskId); for (Map.Entry<String, String> entry: conf) { StringBuilder sb = new StringBuilder(); sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); context.write(textId, new Text(sb.toString())); } context.write(textId, new Text("----- Properties -----")); String[] plist = { "mapred.local.dir", "mapred.child.java.opts", }; for (String k : plist) { String v = conf.get(k); if (v == null) { v = "(null)"; } context.write(textId, new Text(k + " " + v)); } String userDir = System.getProperty("user.dir"); context.write(textId, new Text("user.dir " + userDir)); try { java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); context.write(textId, new Text("hostname " + localMachine.getHostName())); } catch (java.net.UnknownHostException uhe) { // handle exception } }
java
private void emitLogHeader(Context context, String mapredTaskId) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); Text textId = new Text(mapredTaskId); for (Map.Entry<String, String> entry: conf) { StringBuilder sb = new StringBuilder(); sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); context.write(textId, new Text(sb.toString())); } context.write(textId, new Text("----- Properties -----")); String[] plist = { "mapred.local.dir", "mapred.child.java.opts", }; for (String k : plist) { String v = conf.get(k); if (v == null) { v = "(null)"; } context.write(textId, new Text(k + " " + v)); } String userDir = System.getProperty("user.dir"); context.write(textId, new Text("user.dir " + userDir)); try { java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); context.write(textId, new Text("hostname " + localMachine.getHostName())); } catch (java.net.UnknownHostException uhe) { // handle exception } }
[ "private", "void", "emitLogHeader", "(", "Context", "context", ",", "String", "mapredTaskId", ")", "throws", "IOException", ",", "InterruptedException", "{", "Configuration", "conf", "=", "context", ".", "getConfiguration", "(", ")", ";", "Text", "textId", "=", ...
Emit a bunch of logging output at the beginning of the map task. @throws IOException @throws InterruptedException
[ "Emit", "a", "bunch", "of", "logging", "output", "at", "the", "beginning", "of", "the", "map", "task", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/hadoop/src/main/java/water/hadoop/h2omapper.java#L270-L304
train
h2oai/h2o-2
src/main/java/water/api/DomainMapping.java
DomainMapping.serve
@Override protected Response serve() { if( src_key == null ) return RequestServer._http404.serve(); Vec v = src_key.anyVec(); if (v.isEnum()) { map = Arrays.asList(v.domain()).indexOf(str); } else if (v.masterVec() != null && v.masterVec().isEnum()) { map = Arrays.asList(v.masterVec().domain()).indexOf(str); } else { map = -1; } return Response.done(this); }
java
@Override protected Response serve() { if( src_key == null ) return RequestServer._http404.serve(); Vec v = src_key.anyVec(); if (v.isEnum()) { map = Arrays.asList(v.domain()).indexOf(str); } else if (v.masterVec() != null && v.masterVec().isEnum()) { map = Arrays.asList(v.masterVec().domain()).indexOf(str); } else { map = -1; } return Response.done(this); }
[ "@", "Override", "protected", "Response", "serve", "(", ")", "{", "if", "(", "src_key", "==", "null", ")", "return", "RequestServer", ".", "_http404", ".", "serve", "(", ")", ";", "Vec", "v", "=", "src_key", ".", "anyVec", "(", ")", ";", "if", "(", ...
Just validate the frame, and fill in the summary bits
[ "Just", "validate", "the", "frame", "and", "fill", "in", "the", "summary", "bits" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/api/DomainMapping.java#L27-L38
train
h2oai/h2o-2
src/main/java/water/DKV.java
DKV.DputIfMatch
static public Value DputIfMatch( Key key, Value val, Value old, Futures fs) { return DputIfMatch(key, val, old, fs, false); }
java
static public Value DputIfMatch( Key key, Value val, Value old, Futures fs) { return DputIfMatch(key, val, old, fs, false); }
[ "static", "public", "Value", "DputIfMatch", "(", "Key", "key", ",", "Value", "val", ",", "Value", "old", ",", "Futures", "fs", ")", "{", "return", "DputIfMatch", "(", "key", ",", "val", ",", "old", ",", "fs", ",", "false", ")", ";", "}" ]
to consume.
[ "to", "consume", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/DKV.java#L47-L49
train
h2oai/h2o-2
src/main/java/water/DKV.java
DKV.write_barrier
static public void write_barrier() { for( H2ONode h2o : H2O.CLOUD._memary ) for( RPC rpc : h2o.tasks() ) if( rpc._dt instanceof TaskPutKey || rpc._dt instanceof Atomic ) rpc.get(); }
java
static public void write_barrier() { for( H2ONode h2o : H2O.CLOUD._memary ) for( RPC rpc : h2o.tasks() ) if( rpc._dt instanceof TaskPutKey || rpc._dt instanceof Atomic ) rpc.get(); }
[ "static", "public", "void", "write_barrier", "(", ")", "{", "for", "(", "H2ONode", "h2o", ":", "H2O", ".", "CLOUD", ".", "_memary", ")", "for", "(", "RPC", "rpc", ":", "h2o", ".", "tasks", "(", ")", ")", "if", "(", "rpc", ".", "_dt", "instanceof", ...
Used to order successive writes.
[ "Used", "to", "order", "successive", "writes", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/DKV.java#L87-L92
train
h2oai/h2o-2
src/main/java/water/DKV.java
DKV.get
static public Value get( Key key, int len, int priority ) { while( true ) { // Read the Cloud once per put-attempt, to keep a consistent snapshot. H2O cloud = H2O.CLOUD; Value val = H2O.get(key); // Hit in local cache? if( val != null ) { if( len > val._max ) len = val._max; // See if we have enough data cached locally if( len == 0 || val.rawMem() != null || val.rawPOJO() != null || val.isPersisted() ) return val; assert !key.home(); // Master must have *something*; we got nothing & need to fetch } // While in theory we could read from any replica, we always need to // inform the home-node that his copy has been Shared... in case it // changes and he needs to issue an invalidate. For now, always and only // fetch from the Home node. H2ONode home = cloud._memary[key.home(cloud)]; // If we missed in the cache AND we are the home node, then there is // no V for this K (or we have a disk failure). if( home == H2O.SELF ) return null; // Pending write to same key from this node? Take that write instead. // Moral equivalent of "peeking into the cpu store buffer". Can happen, // e.g., because a prior 'put' of a null (i.e. a remove) is still mid- // send to the remote, so the local get has missed above, but a remote // get still might 'win' because the remote 'remove' is still in-progress. for( RPC<?> rpc : home.tasks() ) if( rpc._dt instanceof TaskPutKey ) { assert rpc._target == home; TaskPutKey tpk = (TaskPutKey)rpc._dt; Key k = tpk._key; if( k != null && key.equals(k) ) return tpk._xval; } return TaskGetKey.get(home,key,priority); } }
java
static public Value get( Key key, int len, int priority ) { while( true ) { // Read the Cloud once per put-attempt, to keep a consistent snapshot. H2O cloud = H2O.CLOUD; Value val = H2O.get(key); // Hit in local cache? if( val != null ) { if( len > val._max ) len = val._max; // See if we have enough data cached locally if( len == 0 || val.rawMem() != null || val.rawPOJO() != null || val.isPersisted() ) return val; assert !key.home(); // Master must have *something*; we got nothing & need to fetch } // While in theory we could read from any replica, we always need to // inform the home-node that his copy has been Shared... in case it // changes and he needs to issue an invalidate. For now, always and only // fetch from the Home node. H2ONode home = cloud._memary[key.home(cloud)]; // If we missed in the cache AND we are the home node, then there is // no V for this K (or we have a disk failure). if( home == H2O.SELF ) return null; // Pending write to same key from this node? Take that write instead. // Moral equivalent of "peeking into the cpu store buffer". Can happen, // e.g., because a prior 'put' of a null (i.e. a remove) is still mid- // send to the remote, so the local get has missed above, but a remote // get still might 'win' because the remote 'remove' is still in-progress. for( RPC<?> rpc : home.tasks() ) if( rpc._dt instanceof TaskPutKey ) { assert rpc._target == home; TaskPutKey tpk = (TaskPutKey)rpc._dt; Key k = tpk._key; if( k != null && key.equals(k) ) return tpk._xval; } return TaskGetKey.get(home,key,priority); } }
[ "static", "public", "Value", "get", "(", "Key", "key", ",", "int", "len", ",", "int", "priority", ")", "{", "while", "(", "true", ")", "{", "// Read the Cloud once per put-attempt, to keep a consistent snapshot.", "H2O", "cloud", "=", "H2O", ".", "CLOUD", ";", ...
User-Weak-Get a Key from the distributed cloud.
[ "User", "-", "Weak", "-", "Get", "a", "Key", "from", "the", "distributed", "cloud", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/DKV.java#L95-L133
train
h2oai/h2o-2
src/main/java/water/util/LogCollectorTask.java
LogCollectorTask.zipDir
private void zipDir(String dir2zip, ZipOutputStream zos) throws IOException { try { //create a new File object based on the directory we have to zip. File zipDir = new File(dir2zip); //get a listing of the directory content String[] dirList = zipDir.list(); byte[] readBuffer = new byte[4096]; int bytesIn = 0; //loop through dirList, and zip the files for(int i=0; i<dirList.length; i++) { File f = new File(zipDir, dirList[i]); if(f.isDirectory()) { //if the File object is a directory, call this //function again to add its content recursively String filePath = f.getPath(); zipDir(filePath, zos); //loop again continue; } //if we reached here, the File object f was not a directory //create a FileInputStream on top of f FileInputStream fis = new FileInputStream(f); // create a new zip entry ZipEntry anEntry = new ZipEntry(f.getPath()); anEntry.setTime(f.lastModified()); //place the zip entry in the ZipOutputStream object zos.putNextEntry(anEntry); //now write the content of the file to the ZipOutputStream boolean stopEarlyBecauseTooMuchData = false; while((bytesIn = fis.read(readBuffer)) != -1) { zos.write(readBuffer, 0, bytesIn); if (baos.size() > MAX_SIZE) { stopEarlyBecauseTooMuchData = true; break; } } //close the Stream fis.close(); zos.closeEntry(); if (stopEarlyBecauseTooMuchData) { Log.warn("LogCollectorTask stopEarlyBecauseTooMuchData"); break; } } } catch(Exception e) { //handle exception } }
java
private void zipDir(String dir2zip, ZipOutputStream zos) throws IOException { try { //create a new File object based on the directory we have to zip. File zipDir = new File(dir2zip); //get a listing of the directory content String[] dirList = zipDir.list(); byte[] readBuffer = new byte[4096]; int bytesIn = 0; //loop through dirList, and zip the files for(int i=0; i<dirList.length; i++) { File f = new File(zipDir, dirList[i]); if(f.isDirectory()) { //if the File object is a directory, call this //function again to add its content recursively String filePath = f.getPath(); zipDir(filePath, zos); //loop again continue; } //if we reached here, the File object f was not a directory //create a FileInputStream on top of f FileInputStream fis = new FileInputStream(f); // create a new zip entry ZipEntry anEntry = new ZipEntry(f.getPath()); anEntry.setTime(f.lastModified()); //place the zip entry in the ZipOutputStream object zos.putNextEntry(anEntry); //now write the content of the file to the ZipOutputStream boolean stopEarlyBecauseTooMuchData = false; while((bytesIn = fis.read(readBuffer)) != -1) { zos.write(readBuffer, 0, bytesIn); if (baos.size() > MAX_SIZE) { stopEarlyBecauseTooMuchData = true; break; } } //close the Stream fis.close(); zos.closeEntry(); if (stopEarlyBecauseTooMuchData) { Log.warn("LogCollectorTask stopEarlyBecauseTooMuchData"); break; } } } catch(Exception e) { //handle exception } }
[ "private", "void", "zipDir", "(", "String", "dir2zip", ",", "ZipOutputStream", "zos", ")", "throws", "IOException", "{", "try", "{", "//create a new File object based on the directory we have to zip.", "File", "zipDir", "=", "new", "File", "(", "dir2zip", ")", ";", ...
here is the code for the method
[ "here", "is", "the", "code", "for", "the", "method" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/util/LogCollectorTask.java#L47-L103
train
h2oai/h2o-2
src/main/java/water/InternalInterface.java
InternalInterface.scoreKey
@Override public float[] scoreKey( Object modelKey, String [] colNames, String domains[][], double[] row ) { Key key = (Key)modelKey; String sk = key.toString(); Value v = DKV.get(key); if (v == null) throw new IllegalArgumentException("Key "+sk+" not found!"); try { return scoreModel(v.get(),colNames,domains,row); } catch(Throwable t) { Log.err(t); throw new IllegalArgumentException("Key "+sk+" is not a Model key"); } }
java
@Override public float[] scoreKey( Object modelKey, String [] colNames, String domains[][], double[] row ) { Key key = (Key)modelKey; String sk = key.toString(); Value v = DKV.get(key); if (v == null) throw new IllegalArgumentException("Key "+sk+" not found!"); try { return scoreModel(v.get(),colNames,domains,row); } catch(Throwable t) { Log.err(t); throw new IllegalArgumentException("Key "+sk+" is not a Model key"); } }
[ "@", "Override", "public", "float", "[", "]", "scoreKey", "(", "Object", "modelKey", ",", "String", "[", "]", "colNames", ",", "String", "domains", "[", "]", "[", "]", ",", "double", "[", "]", "row", ")", "{", "Key", "key", "=", "(", "Key", ")", ...
All-in-one call to lookup a model, map the columns and score
[ "All", "-", "in", "-", "one", "call", "to", "lookup", "a", "model", "map", "the", "columns", "and", "score" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/InternalInterface.java#L22-L34
train
h2oai/h2o-2
src/main/java/hex/gbm/DRealHistogram.java
DRealHistogram.incr1
void incr1( int b, double y, double yy ) { Utils.AtomicDoubleArray.add(_sums,b,y); Utils.AtomicDoubleArray.add(_ssqs,b,yy); }
java
void incr1( int b, double y, double yy ) { Utils.AtomicDoubleArray.add(_sums,b,y); Utils.AtomicDoubleArray.add(_ssqs,b,yy); }
[ "void", "incr1", "(", "int", "b", ",", "double", "y", ",", "double", "yy", ")", "{", "Utils", ".", "AtomicDoubleArray", ".", "add", "(", "_sums", ",", "b", ",", "y", ")", ";", "Utils", ".", "AtomicDoubleArray", ".", "add", "(", "_ssqs", ",", "b", ...
Same, except square done by caller
[ "Same", "except", "square", "done", "by", "caller" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/gbm/DRealHistogram.java#L52-L55
train
h2oai/h2o-2
src/main/java/water/api/RequestQueries.java
RequestQueries.checkArguments
protected final String checkArguments(Properties args, RequestType type) { // Why the following lines duplicate lines from Request#92 - handling query? // reset all arguments for (Argument arg: _arguments) arg.reset(); // return query if in query mode if (type == RequestType.query) return buildQuery(args,type); /* // Check that for each actual input argument from the user, there is some // request argument that this method is expecting. //*/ if (H2O.OPT_ARGS.check_rest_params && !(this instanceof GridSearch) && !(this instanceof HTTP500)) { Enumeration en = args.propertyNames(); while (en.hasMoreElements()) { boolean found = false; String key = (String) en.nextElement(); for (Argument arg: _arguments) { if (arg._name.equals(key)) { found = true; break; } } if (!found) { return jsonError("Request specifies the argument '"+key+"' but it is not a valid parameter for this query " + this.getClass().getName()).toString(); } } } // check the arguments now for (Argument arg: _arguments) { if (!arg.disabled()) { try { arg.check(RequestQueries.this, args.getProperty(arg._name,"")); queryArgumentValueSet(arg, args); } catch( IllegalArgumentException e ) { if (type == RequestType.json) return jsonError("Argument '"+arg._name+"' error: "+e.getMessage()).toString(); else return buildQuery(args,type); } } } return null; }
java
protected final String checkArguments(Properties args, RequestType type) { // Why the following lines duplicate lines from Request#92 - handling query? // reset all arguments for (Argument arg: _arguments) arg.reset(); // return query if in query mode if (type == RequestType.query) return buildQuery(args,type); /* // Check that for each actual input argument from the user, there is some // request argument that this method is expecting. //*/ if (H2O.OPT_ARGS.check_rest_params && !(this instanceof GridSearch) && !(this instanceof HTTP500)) { Enumeration en = args.propertyNames(); while (en.hasMoreElements()) { boolean found = false; String key = (String) en.nextElement(); for (Argument arg: _arguments) { if (arg._name.equals(key)) { found = true; break; } } if (!found) { return jsonError("Request specifies the argument '"+key+"' but it is not a valid parameter for this query " + this.getClass().getName()).toString(); } } } // check the arguments now for (Argument arg: _arguments) { if (!arg.disabled()) { try { arg.check(RequestQueries.this, args.getProperty(arg._name,"")); queryArgumentValueSet(arg, args); } catch( IllegalArgumentException e ) { if (type == RequestType.json) return jsonError("Argument '"+arg._name+"' error: "+e.getMessage()).toString(); else return buildQuery(args,type); } } } return null; }
[ "protected", "final", "String", "checkArguments", "(", "Properties", "args", ",", "RequestType", "type", ")", "{", "// Why the following lines duplicate lines from Request#92 - handling query?", "// reset all arguments", "for", "(", "Argument", "arg", ":", "_arguments", ")", ...
Checks the given arguments. When first argument is found wrong, generates the json error and returns the result to be returned if any problems were found. Otherwise returns @param args @param type @return
[ "Checks", "the", "given", "arguments", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/api/RequestQueries.java#L35-L80
train
h2oai/h2o-2
src/main/java/water/UDPReceiverThread.java
UDPReceiverThread.basic_packet_handling
static public void basic_packet_handling( AutoBuffer ab ) throws java.io.IOException { // Randomly drop 1/10th of the packets, as-if broken network. Dropped // packets are timeline recorded before dropping - and we still will // respond to timelines and suicide packets. int drop = H2O.OPT_ARGS.random_udp_drop!= null && RANDOM_UDP_DROP.nextInt(5) == 0 ? 2 : 0; // Record the last time we heard from any given Node TimeLine.record_recv(ab,false,drop); ab._h2o._last_heard_from = System.currentTimeMillis(); // Snapshots are handled *IN THIS THREAD*, to prevent more UDP packets from // being handled during the dump. Also works for packets from outside the // Cloud... because we use Timelines to diagnose Paxos failures. int ctrl = ab.getCtrl(); ab.getPort(); // skip the port bytes if( ctrl == UDP.udp.timeline.ordinal() ) { UDP.udp.timeline._udp.call(ab); return; } // Suicide packet? Short-n-sweet... if( ctrl == UDP.udp.rebooted.ordinal()) UDPRebooted.checkForSuicide(ctrl, ab); // Drop the packet. if( drop != 0 ) return; // Get the Cloud we are operating under for this packet H2O cloud = H2O.CLOUD; // Check cloud membership; stale ex-members are "fail-stop" - we mostly // ignore packets from them (except paxos packets). boolean is_member = cloud.contains(ab._h2o); // Paxos stateless packets & ACKs just fire immediately in a worker // thread. Dups are handled by these packet handlers directly. No // current membership check required for Paxos packets if( UDP.udp.UDPS[ctrl]._paxos || is_member ) { H2O.submitTask(new FJPacket(ab,ctrl)); return; } // Some non-Paxos packet from a non-member. Probably should record & complain. // Filter unknown-packet-reports. In bad situations of poisoned Paxos // voting we can get a LOT of these packets/sec, flooding the console. _unknown_packets_per_sec++; long timediff = ab._h2o._last_heard_from - _unknown_packet_time; if( timediff > 1000 ) { Log.warn("UDP packets from outside the cloud: "+_unknown_packets_per_sec+"/sec, last one from "+ab._h2o+ " @ "+new Date()); _unknown_packets_per_sec = 0; _unknown_packet_time = ab._h2o._last_heard_from; } ab.close(); }
java
static public void basic_packet_handling( AutoBuffer ab ) throws java.io.IOException { // Randomly drop 1/10th of the packets, as-if broken network. Dropped // packets are timeline recorded before dropping - and we still will // respond to timelines and suicide packets. int drop = H2O.OPT_ARGS.random_udp_drop!= null && RANDOM_UDP_DROP.nextInt(5) == 0 ? 2 : 0; // Record the last time we heard from any given Node TimeLine.record_recv(ab,false,drop); ab._h2o._last_heard_from = System.currentTimeMillis(); // Snapshots are handled *IN THIS THREAD*, to prevent more UDP packets from // being handled during the dump. Also works for packets from outside the // Cloud... because we use Timelines to diagnose Paxos failures. int ctrl = ab.getCtrl(); ab.getPort(); // skip the port bytes if( ctrl == UDP.udp.timeline.ordinal() ) { UDP.udp.timeline._udp.call(ab); return; } // Suicide packet? Short-n-sweet... if( ctrl == UDP.udp.rebooted.ordinal()) UDPRebooted.checkForSuicide(ctrl, ab); // Drop the packet. if( drop != 0 ) return; // Get the Cloud we are operating under for this packet H2O cloud = H2O.CLOUD; // Check cloud membership; stale ex-members are "fail-stop" - we mostly // ignore packets from them (except paxos packets). boolean is_member = cloud.contains(ab._h2o); // Paxos stateless packets & ACKs just fire immediately in a worker // thread. Dups are handled by these packet handlers directly. No // current membership check required for Paxos packets if( UDP.udp.UDPS[ctrl]._paxos || is_member ) { H2O.submitTask(new FJPacket(ab,ctrl)); return; } // Some non-Paxos packet from a non-member. Probably should record & complain. // Filter unknown-packet-reports. In bad situations of poisoned Paxos // voting we can get a LOT of these packets/sec, flooding the console. _unknown_packets_per_sec++; long timediff = ab._h2o._last_heard_from - _unknown_packet_time; if( timediff > 1000 ) { Log.warn("UDP packets from outside the cloud: "+_unknown_packets_per_sec+"/sec, last one from "+ab._h2o+ " @ "+new Date()); _unknown_packets_per_sec = 0; _unknown_packet_time = ab._h2o._last_heard_from; } ab.close(); }
[ "static", "public", "void", "basic_packet_handling", "(", "AutoBuffer", "ab", ")", "throws", "java", ".", "io", ".", "IOException", "{", "// Randomly drop 1/10th of the packets, as-if broken network. Dropped", "// packets are timeline recorded before dropping - and we still will", ...
- Timeline record it
[ "-", "Timeline", "record", "it" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/UDPReceiverThread.java#L70-L123
train
h2oai/h2o-2
src/main/java/water/exec/Env.java
Env.push
void push( int slots ) { assert 0 <= slots && slots < 1000; int len = _d.length; _sp += slots; while( _sp > len ) { _key= Arrays.copyOf(_key,len<<1); _ary= Arrays.copyOf(_ary,len<<1); _d = Arrays.copyOf(_d ,len<<1); _fcn= Arrays.copyOf(_fcn,len<<=1); _str= Arrays.copyOf(_str,len<<1); } }
java
void push( int slots ) { assert 0 <= slots && slots < 1000; int len = _d.length; _sp += slots; while( _sp > len ) { _key= Arrays.copyOf(_key,len<<1); _ary= Arrays.copyOf(_ary,len<<1); _d = Arrays.copyOf(_d ,len<<1); _fcn= Arrays.copyOf(_fcn,len<<=1); _str= Arrays.copyOf(_str,len<<1); } }
[ "void", "push", "(", "int", "slots", ")", "{", "assert", "0", "<=", "slots", "&&", "slots", "<", "1000", ";", "int", "len", "=", "_d", ".", "length", ";", "_sp", "+=", "slots", ";", "while", "(", "_sp", ">", "len", ")", "{", "_key", "=", "Array...
Push k empty slots
[ "Push", "k", "empty", "slots" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/exec/Env.java#L83-L94
train
h2oai/h2o-2
src/main/java/water/exec/Env.java
Env.push_slot
void push_slot( int d, int n ) { assert d==0; // Should use a fcn's closure for d>1 int idx = _display[_tod-d]+n; push(1); _ary[_sp-1] = addRef(_ary[idx]); _d [_sp-1] = _d [idx]; _fcn[_sp-1] = addRef(_fcn[idx]); _str[_sp-1] = _str[idx]; assert _ary[0]==null || check_refcnt(_ary[0].anyVec()); }
java
void push_slot( int d, int n ) { assert d==0; // Should use a fcn's closure for d>1 int idx = _display[_tod-d]+n; push(1); _ary[_sp-1] = addRef(_ary[idx]); _d [_sp-1] = _d [idx]; _fcn[_sp-1] = addRef(_fcn[idx]); _str[_sp-1] = _str[idx]; assert _ary[0]==null || check_refcnt(_ary[0].anyVec()); }
[ "void", "push_slot", "(", "int", "d", ",", "int", "n", ")", "{", "assert", "d", "==", "0", ";", "// Should use a fcn's closure for d>1", "int", "idx", "=", "_display", "[", "_tod", "-", "d", "]", "+", "n", ";", "push", "(", "1", ")", ";", "_ary", "...
Copy from display offset d, nth slot
[ "Copy", "from", "display", "offset", "d", "nth", "slot" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/exec/Env.java#L102-L111
train
h2oai/h2o-2
src/main/java/water/exec/Env.java
Env.tos_into_slot
void tos_into_slot( int d, int n, String id ) { // In a copy-on-modify language, only update the local scope, or return val assert d==0 || (d==1 && _display[_tod]==n+1); int idx = _display[_tod-d]+n; // Temporary solution to kill a UDF from global name space. Needs to fix in the future. if (_tod == 0) ASTOp.removeUDF(id); subRef(_ary[idx], _key[idx]); subRef(_fcn[idx]); Frame fr = _ary[_sp-1]; _ary[idx] = fr==null ? null : addRef(new Frame(fr)); _d [idx] = _d [_sp-1] ; _str[idx] = _str[_sp-1] ; _fcn[idx] = addRef(_fcn[_sp-1]); _key[idx] = d==0 && fr!=null ? id : null; // Temporary solution to add a UDF to global name space. Needs to fix in the future. if (_tod == 0 && _fcn[_sp-1] != null) ASTOp.putUDF(_fcn[_sp-1], id); assert _ary[0]== null || check_refcnt(_ary[0].anyVec()); }
java
void tos_into_slot( int d, int n, String id ) { // In a copy-on-modify language, only update the local scope, or return val assert d==0 || (d==1 && _display[_tod]==n+1); int idx = _display[_tod-d]+n; // Temporary solution to kill a UDF from global name space. Needs to fix in the future. if (_tod == 0) ASTOp.removeUDF(id); subRef(_ary[idx], _key[idx]); subRef(_fcn[idx]); Frame fr = _ary[_sp-1]; _ary[idx] = fr==null ? null : addRef(new Frame(fr)); _d [idx] = _d [_sp-1] ; _str[idx] = _str[_sp-1] ; _fcn[idx] = addRef(_fcn[_sp-1]); _key[idx] = d==0 && fr!=null ? id : null; // Temporary solution to add a UDF to global name space. Needs to fix in the future. if (_tod == 0 && _fcn[_sp-1] != null) ASTOp.putUDF(_fcn[_sp-1], id); assert _ary[0]== null || check_refcnt(_ary[0].anyVec()); }
[ "void", "tos_into_slot", "(", "int", "d", ",", "int", "n", ",", "String", "id", ")", "{", "// In a copy-on-modify language, only update the local scope, or return val", "assert", "d", "==", "0", "||", "(", "d", "==", "1", "&&", "_display", "[", "_tod", "]", "=...
Copy from TOS into a slot. Does NOT pop results.
[ "Copy", "from", "TOS", "into", "a", "slot", ".", "Does", "NOT", "pop", "results", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/exec/Env.java#L124-L141
train
h2oai/h2o-2
src/main/java/water/exec/Env.java
Env.tos_into_slot
void tos_into_slot( int idx, String id ) { subRef(_ary[idx], _key[idx]); subRef(_fcn[idx]); Frame fr = _ary[_sp-1]; _ary[idx] = fr==null ? null : addRef(new Frame(fr)); _d [idx] = _d [_sp-1] ; _fcn[idx] = addRef(_fcn[_sp-1]); _str[idx] = _str[_sp-1] ; _key[idx] = fr!=null ? id : null; assert _ary[0]== null || check_refcnt(_ary[0].anyVec()); }
java
void tos_into_slot( int idx, String id ) { subRef(_ary[idx], _key[idx]); subRef(_fcn[idx]); Frame fr = _ary[_sp-1]; _ary[idx] = fr==null ? null : addRef(new Frame(fr)); _d [idx] = _d [_sp-1] ; _fcn[idx] = addRef(_fcn[_sp-1]); _str[idx] = _str[_sp-1] ; _key[idx] = fr!=null ? id : null; assert _ary[0]== null || check_refcnt(_ary[0].anyVec()); }
[ "void", "tos_into_slot", "(", "int", "idx", ",", "String", "id", ")", "{", "subRef", "(", "_ary", "[", "idx", "]", ",", "_key", "[", "idx", "]", ")", ";", "subRef", "(", "_fcn", "[", "idx", "]", ")", ";", "Frame", "fr", "=", "_ary", "[", "_sp",...
Copy from TOS into a slot, using absolute index.
[ "Copy", "from", "TOS", "into", "a", "slot", "using", "absolute", "index", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/exec/Env.java#L143-L153
train
h2oai/h2o-2
src/main/java/water/exec/Env.java
Env.popXAry
public Frame popXAry() { Frame fr = popAry(); for( Vec vec : fr.vecs() ) { popVec(vec); if ( vec.masterVec() != null ) popVec(vec.masterVec()); } return fr; }
java
public Frame popXAry() { Frame fr = popAry(); for( Vec vec : fr.vecs() ) { popVec(vec); if ( vec.masterVec() != null ) popVec(vec.masterVec()); } return fr; }
[ "public", "Frame", "popXAry", "(", ")", "{", "Frame", "fr", "=", "popAry", "(", ")", ";", "for", "(", "Vec", "vec", ":", "fr", ".", "vecs", "(", ")", ")", "{", "popVec", "(", "vec", ")", ";", "if", "(", "vec", ".", "masterVec", "(", ")", "!="...
Assumption is that this Frame will get pushed again shortly.
[ "Assumption", "is", "that", "this", "Frame", "will", "get", "pushed", "again", "shortly", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/exec/Env.java#L216-L223
train
h2oai/h2o-2
src/main/java/water/exec/Env.java
Env.poppush
public void poppush( int n, Frame ary, String key) { addRef(ary); for( int i=0; i<n; i++ ) { assert _sp > 0; _sp--; _fcn[_sp] = subRef(_fcn[_sp]); _ary[_sp] = subRef(_ary[_sp], _key[_sp]); } push(1); _ary[_sp-1] = ary; _key[_sp-1] = key; assert check_all_refcnts(); }
java
public void poppush( int n, Frame ary, String key) { addRef(ary); for( int i=0; i<n; i++ ) { assert _sp > 0; _sp--; _fcn[_sp] = subRef(_fcn[_sp]); _ary[_sp] = subRef(_ary[_sp], _key[_sp]); } push(1); _ary[_sp-1] = ary; _key[_sp-1] = key; assert check_all_refcnts(); }
[ "public", "void", "poppush", "(", "int", "n", ",", "Frame", "ary", ",", "String", "key", ")", "{", "addRef", "(", "ary", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "assert", "_sp", ">", "0", ";...
Replace a function invocation with it's result
[ "Replace", "a", "function", "invocation", "with", "it", "s", "result" ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/exec/Env.java#L231-L241
train
h2oai/h2o-2
src/main/java/water/exec/Env.java
Env.subRef
public Futures subRef( Vec vec, Futures fs ) { assert fs != null : "Future should not be null!"; if ( vec.masterVec() != null ) subRef(vec.masterVec(), fs); int cnt = _refcnt.get(vec)._val-1; if ( cnt > 0 ) { _refcnt.put(vec,new IcedInt(cnt)); } else { UKV.remove(vec._key,fs); _refcnt.remove(vec); } return fs; }
java
public Futures subRef( Vec vec, Futures fs ) { assert fs != null : "Future should not be null!"; if ( vec.masterVec() != null ) subRef(vec.masterVec(), fs); int cnt = _refcnt.get(vec)._val-1; if ( cnt > 0 ) { _refcnt.put(vec,new IcedInt(cnt)); } else { UKV.remove(vec._key,fs); _refcnt.remove(vec); } return fs; }
[ "public", "Futures", "subRef", "(", "Vec", "vec", ",", "Futures", "fs", ")", "{", "assert", "fs", "!=", "null", ":", "\"Future should not be null!\"", ";", "if", "(", "vec", ".", "masterVec", "(", ")", "!=", "null", ")", "subRef", "(", "vec", ".", "mas...
Subtract reference count. @param vec vector to handle @param fs future, cannot be null @return returns given Future
[ "Subtract", "reference", "count", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/exec/Env.java#L279-L290
train
h2oai/h2o-2
src/main/java/water/schemas/Schema.java
Schema.fillFrom
public S fillFrom( Properties parms ) { // Get passed-in fields, assign into Schema Class clz = getClass(); for( String key : parms.stringPropertyNames() ) { try { Field f = clz.getDeclaredField(key); // No such field error, if parm is junk int mods = f.getModifiers(); if( Modifier.isTransient(mods) || Modifier.isStatic(mods) ) // Attempting to set a transient or static; treat same as junk fieldname throw new IllegalArgumentException("Unknown argument "+key); // Only support a single annotation which is an API, and is required API api = (API)f.getAnnotations()[0]; // Must have one of these set to be an input field if( api.validation().length()==0 && api.values ().length()==0 && api.dependsOn ().length ==0 ) throw new IllegalArgumentException("Attempting to set output field "+key); // Primitive parse by field type f.set(this,parse(parms.getProperty(key),f.getType())); } catch( NoSuchFieldException nsfe ) { // Convert missing-field to IAE throw new IllegalArgumentException("Unknown argument "+key); } catch( ArrayIndexOutOfBoundsException aioobe ) { // Come here if missing annotation throw new RuntimeException("Broken internal schema; missing API annotation: "+key); } catch( IllegalAccessException iae ) { // Come here if field is final or private throw new RuntimeException("Broken internal schema; cannot be private nor final: "+key); } } // Here every thing in 'parms' was set into some field - so we have already // checked for unknown or extra parms. // Confirm required fields are set do { for( Field f : clz.getDeclaredFields() ) { int mods = f.getModifiers(); if( Modifier.isTransient(mods) || Modifier.isStatic(mods) ) continue; // Ignore transient & static API api = (API)f.getAnnotations()[0]; if( api.validation().length() > 0 ) { // TODO: execute "validation language" in the BackEnd, which includes a "required check", if any if( parms.getProperty(f.getName()) == null ) throw new IllegalArgumentException("Required field "+f.getName()+" not specified"); } } clz = clz.getSuperclass(); } while( Iced.class.isAssignableFrom(clz.getSuperclass()) ); return (S)this; }
java
public S fillFrom( Properties parms ) { // Get passed-in fields, assign into Schema Class clz = getClass(); for( String key : parms.stringPropertyNames() ) { try { Field f = clz.getDeclaredField(key); // No such field error, if parm is junk int mods = f.getModifiers(); if( Modifier.isTransient(mods) || Modifier.isStatic(mods) ) // Attempting to set a transient or static; treat same as junk fieldname throw new IllegalArgumentException("Unknown argument "+key); // Only support a single annotation which is an API, and is required API api = (API)f.getAnnotations()[0]; // Must have one of these set to be an input field if( api.validation().length()==0 && api.values ().length()==0 && api.dependsOn ().length ==0 ) throw new IllegalArgumentException("Attempting to set output field "+key); // Primitive parse by field type f.set(this,parse(parms.getProperty(key),f.getType())); } catch( NoSuchFieldException nsfe ) { // Convert missing-field to IAE throw new IllegalArgumentException("Unknown argument "+key); } catch( ArrayIndexOutOfBoundsException aioobe ) { // Come here if missing annotation throw new RuntimeException("Broken internal schema; missing API annotation: "+key); } catch( IllegalAccessException iae ) { // Come here if field is final or private throw new RuntimeException("Broken internal schema; cannot be private nor final: "+key); } } // Here every thing in 'parms' was set into some field - so we have already // checked for unknown or extra parms. // Confirm required fields are set do { for( Field f : clz.getDeclaredFields() ) { int mods = f.getModifiers(); if( Modifier.isTransient(mods) || Modifier.isStatic(mods) ) continue; // Ignore transient & static API api = (API)f.getAnnotations()[0]; if( api.validation().length() > 0 ) { // TODO: execute "validation language" in the BackEnd, which includes a "required check", if any if( parms.getProperty(f.getName()) == null ) throw new IllegalArgumentException("Required field "+f.getName()+" not specified"); } } clz = clz.getSuperclass(); } while( Iced.class.isAssignableFrom(clz.getSuperclass()) ); return (S)this; }
[ "public", "S", "fillFrom", "(", "Properties", "parms", ")", "{", "// Get passed-in fields, assign into Schema", "Class", "clz", "=", "getClass", "(", ")", ";", "for", "(", "String", "key", ":", "parms", ".", "stringPropertyNames", "(", ")", ")", "{", "try", ...
private. Input fields get filled here, so must not be final.
[ "private", ".", "Input", "fields", "get", "filled", "here", "so", "must", "not", "be", "final", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/schemas/Schema.java#L54-L104
train
h2oai/h2o-2
src/main/java/water/fvec/Chunk.java
Chunk.isNA
public final boolean isNA(long i) { long x = i - (_start>0 ? _start : 0); if( 0 <= x && x < _len ) return isNA0((int)x); throw new ArrayIndexOutOfBoundsException(getClass().getSimpleName() + " " +_start+" <= "+i+" < "+(_start+_len)); }
java
public final boolean isNA(long i) { long x = i - (_start>0 ? _start : 0); if( 0 <= x && x < _len ) return isNA0((int)x); throw new ArrayIndexOutOfBoundsException(getClass().getSimpleName() + " " +_start+" <= "+i+" < "+(_start+_len)); }
[ "public", "final", "boolean", "isNA", "(", "long", "i", ")", "{", "long", "x", "=", "i", "-", "(", "_start", ">", "0", "?", "_start", ":", "0", ")", ";", "if", "(", "0", "<=", "x", "&&", "x", "<", "_len", ")", "return", "isNA0", "(", "(", "...
Fetch the missing-status the slow way.
[ "Fetch", "the", "missing", "-", "status", "the", "slow", "way", "." ]
be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1
https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/water/fvec/Chunk.java#L54-L58
train