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
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/jersey/AuthenticationManagerService.java
AuthenticationManagerService.authorizedTeams
@GET @Path("teams") public Response authorizedTeams(@HeaderParam("Authorization") @DefaultValue("no token") String auth) throws Exception { if(!this.isAuth(auth)) { return Response.status(Status.FORBIDDEN).build(); } Integer teams[] = getAuthorizedTeams(); return Response.ok(new Gson().toJson(teams), MediaType.APPLICATION_JSON).build(); }
java
@GET @Path("teams") public Response authorizedTeams(@HeaderParam("Authorization") @DefaultValue("no token") String auth) throws Exception { if(!this.isAuth(auth)) { return Response.status(Status.FORBIDDEN).build(); } Integer teams[] = getAuthorizedTeams(); return Response.ok(new Gson().toJson(teams), MediaType.APPLICATION_JSON).build(); }
[ "@", "GET", "@", "Path", "(", "\"teams\"", ")", "public", "Response", "authorizedTeams", "(", "@", "HeaderParam", "(", "\"Authorization\"", ")", "@", "DefaultValue", "(", "\"no token\"", ")", "String", "auth", ")", "throws", "Exception", "{", "if", "(", "!",...
Get the list of github team ids that are allowed to access this instance. @param auth @return @throws Exception
[ "Get", "the", "list", "of", "github", "team", "ids", "that", "are", "allowed", "to", "access", "this", "instance", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/jersey/AuthenticationManagerService.java#L149-L157
train
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/AuthCommand.java
AuthCommand.sendRequest
private void sendRequest(HttpUriRequest request, int expectedStatus) throws Exception { addAuthHeader(request); HttpClient client = httpClient(); HttpResponse response = client.execute(request); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { EntityUtils.consume(response.getEntity()); System.err.println("Authentication has been disabled for "+args.get(1)+"."); } else if(response.getStatusLine().getStatusCode() == expectedStatus) { if(expectedStatus == HttpStatus.SC_OK) { String responseStr = EntityUtils.toString(response.getEntity()); List<String> usernames = new Gson().fromJson(responseStr, new TypeToken<List<String>>(){}.getType()); if(usernames == null || usernames.isEmpty()) { System.out.println("There have been no site specific users created."); } else { System.out.println(usernames.size() + " Users:"); for(String user : usernames) { System.out.println(user); } } } } else { System.err.println(EntityUtils.toString(response.getEntity())); System.err.println("Unexpected status code returned. "+response.getStatusLine().getStatusCode()); } }
java
private void sendRequest(HttpUriRequest request, int expectedStatus) throws Exception { addAuthHeader(request); HttpClient client = httpClient(); HttpResponse response = client.execute(request); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { EntityUtils.consume(response.getEntity()); System.err.println("Authentication has been disabled for "+args.get(1)+"."); } else if(response.getStatusLine().getStatusCode() == expectedStatus) { if(expectedStatus == HttpStatus.SC_OK) { String responseStr = EntityUtils.toString(response.getEntity()); List<String> usernames = new Gson().fromJson(responseStr, new TypeToken<List<String>>(){}.getType()); if(usernames == null || usernames.isEmpty()) { System.out.println("There have been no site specific users created."); } else { System.out.println(usernames.size() + " Users:"); for(String user : usernames) { System.out.println(user); } } } } else { System.err.println(EntityUtils.toString(response.getEntity())); System.err.println("Unexpected status code returned. "+response.getStatusLine().getStatusCode()); } }
[ "private", "void", "sendRequest", "(", "HttpUriRequest", "request", ",", "int", "expectedStatus", ")", "throws", "Exception", "{", "addAuthHeader", "(", "request", ")", ";", "HttpClient", "client", "=", "httpClient", "(", ")", ";", "HttpResponse", "response", "=...
Sends a request to the rest endpoint. @param request @param expectedStatus @throws KeyManagementException @throws UnrecoverableKeyException @throws NoSuchAlgorithmException @throws KeyStoreException @throws IOException @throws ClientProtocolException
[ "Sends", "a", "request", "to", "the", "rest", "endpoint", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/AuthCommand.java#L121-L148
train
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/AuthCommand.java
AuthCommand.hashPasswordForShiro
private String hashPasswordForShiro() { //Hash password HashFormatFactory HASH_FORMAT_FACTORY = new DefaultHashFormatFactory(); SecureRandomNumberGenerator generator = new SecureRandomNumberGenerator(); int byteSize = 128 / 8; ByteSource salt = generator.nextBytes(byteSize); SimpleHash hash = new SimpleHash("SHA-256", password, salt, 10); HashFormat format = HASH_FORMAT_FACTORY.getInstance("shiro1"); return format.format(hash); }
java
private String hashPasswordForShiro() { //Hash password HashFormatFactory HASH_FORMAT_FACTORY = new DefaultHashFormatFactory(); SecureRandomNumberGenerator generator = new SecureRandomNumberGenerator(); int byteSize = 128 / 8; ByteSource salt = generator.nextBytes(byteSize); SimpleHash hash = new SimpleHash("SHA-256", password, salt, 10); HashFormat format = HASH_FORMAT_FACTORY.getInstance("shiro1"); return format.format(hash); }
[ "private", "String", "hashPasswordForShiro", "(", ")", "{", "//Hash password", "HashFormatFactory", "HASH_FORMAT_FACTORY", "=", "new", "DefaultHashFormatFactory", "(", ")", ";", "SecureRandomNumberGenerator", "generator", "=", "new", "SecureRandomNumberGenerator", "(", ")",...
Hashes a password the shiro way. @return
[ "Hashes", "a", "password", "the", "shiro", "way", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/AuthCommand.java#L154-L165
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/Fields.java
Fields.createTupleField
public static Field createTupleField(String name, Schema schema) { return Field.createTupleField(name, schema); }
java
public static Field createTupleField(String name, Schema schema) { return Field.createTupleField(name, schema); }
[ "public", "static", "Field", "createTupleField", "(", "String", "name", ",", "Schema", "schema", ")", "{", "return", "Field", ".", "createTupleField", "(", "name", ",", "schema", ")", ";", "}" ]
Creates a field containing a Pangool Tuple. @param name Field's name @param schema The schema of the field @return the field @deprecated Use {@link Field#createTupleField(String, Schema)} instead}
[ "Creates", "a", "field", "containing", "a", "Pangool", "Tuple", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/Fields.java#L145-L147
train
meltmedia/cadmium
deployer/src/main/java/com/meltmedia/cadmium/deployer/DeployerModule.java
DeployerModule.configure
@Override protected void configure() { try { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); File appRoot = new File(System.getProperty(CadmiumListener.BASE_PATH_ENV), "maven"); FileUtils.forceMkdir(appRoot); String remoteMavenRepo = System.getProperty(MAVEN_REPOSITORY); ArtifactResolver resolver = new ArtifactResolver(remoteMavenRepo, appRoot.getAbsolutePath()); bind(ArtifactResolver.class).toInstance(resolver); bind(JBossAdminApi.class); Multibinder<ConfigurationListener> listenerBinder = Multibinder.newSetBinder(binder(), ConfigurationListener.class); listenerBinder.addBinding().to(JBossAdminApi.class); bind(IJBossUtil.class).to(JBossDelegator.class); } catch(Exception e) { logger.error("Failed to initialize maven artifact resolver.", e); } }
java
@Override protected void configure() { try { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); File appRoot = new File(System.getProperty(CadmiumListener.BASE_PATH_ENV), "maven"); FileUtils.forceMkdir(appRoot); String remoteMavenRepo = System.getProperty(MAVEN_REPOSITORY); ArtifactResolver resolver = new ArtifactResolver(remoteMavenRepo, appRoot.getAbsolutePath()); bind(ArtifactResolver.class).toInstance(resolver); bind(JBossAdminApi.class); Multibinder<ConfigurationListener> listenerBinder = Multibinder.newSetBinder(binder(), ConfigurationListener.class); listenerBinder.addBinding().to(JBossAdminApi.class); bind(IJBossUtil.class).to(JBossDelegator.class); } catch(Exception e) { logger.error("Failed to initialize maven artifact resolver.", e); } }
[ "@", "Override", "protected", "void", "configure", "(", ")", "{", "try", "{", "InternalLoggerFactory", ".", "setDefaultFactory", "(", "new", "Slf4JLoggerFactory", "(", ")", ")", ";", "File", "appRoot", "=", "new", "File", "(", "System", ".", "getProperty", "...
Called to do all bindings for this module. @see <a href="http://code.google.com/p/google-guice/">Google Guice</a>
[ "Called", "to", "do", "all", "bindings", "for", "this", "module", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/deployer/src/main/java/com/meltmedia/cadmium/deployer/DeployerModule.java#L55-L71
train
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/jersey/error/ErrorUtil.java
ErrorUtil.internalError
public static Response internalError(Throwable throwable, UriInfo uriInfo) { GenericError error = new GenericError( ExceptionUtils.getRootCauseMessage(throwable), ErrorCode.INTERNAL.getCode(), uriInfo.getAbsolutePath().toString()); if (!isProduction()) { error.setStack(ExceptionUtils.getStackTrace(throwable)); } return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .type(MediaType.APPLICATION_JSON_TYPE) .entity(error) .build(); }
java
public static Response internalError(Throwable throwable, UriInfo uriInfo) { GenericError error = new GenericError( ExceptionUtils.getRootCauseMessage(throwable), ErrorCode.INTERNAL.getCode(), uriInfo.getAbsolutePath().toString()); if (!isProduction()) { error.setStack(ExceptionUtils.getStackTrace(throwable)); } return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .type(MediaType.APPLICATION_JSON_TYPE) .entity(error) .build(); }
[ "public", "static", "Response", "internalError", "(", "Throwable", "throwable", ",", "UriInfo", "uriInfo", ")", "{", "GenericError", "error", "=", "new", "GenericError", "(", "ExceptionUtils", ".", "getRootCauseMessage", "(", "throwable", ")", ",", "ErrorCode", "....
Creates Jersey response corresponding to internal error @param throwable {@link Throwable} object representing an error @param uriInfo {@link UriInfo} object used for forming links @return {@link Response} Jersey response object containing JSON representation of the error.
[ "Creates", "Jersey", "response", "corresponding", "to", "internal", "error" ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/jersey/error/ErrorUtil.java#L51-L65
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/git/GitService.java
GitService.initializeConfigDirectory
public static GitService initializeConfigDirectory(String uri, String branch, String root, String warName, HistoryManager historyManager, ConfigManager configManager) throws Exception { initializeBaseDirectoryStructure(root, warName); String warDir = FileSystemManager.getChildDirectoryIfExists(root, warName); Properties configProperties = configManager.getDefaultProperties(); GitLocation gitLocation = new GitLocation(uri, branch, configProperties.getProperty("config.git.ref.sha")); GitService cloned = initializeRepo(gitLocation, warDir, "git-config-checkout"); try { String renderedContentDir = initializeSnapshotDirectory(warDir, configProperties, "com.meltmedia.cadmium.config.lastUpdated", "git-config-checkout", "config"); boolean hasExisting = configProperties.containsKey("com.meltmedia.cadmium.config.lastUpdated") && renderedContentDir != null && renderedContentDir.equals(configProperties.getProperty("com.meltmedia.cadmium.config.lastUpdated")); if(renderedContentDir != null) { configProperties.setProperty("com.meltmedia.cadmium.config.lastUpdated", renderedContentDir); } configProperties.setProperty("config.branch", cloned.getBranchName()); configProperties.setProperty("config.git.ref.sha", cloned.getCurrentRevision()); configProperties.setProperty("config.repo", cloned.getRemoteRepository()); configManager.persistDefaultProperties(); ExecutorService pool = null; if(historyManager == null) { pool = Executors.newSingleThreadExecutor(); historyManager = new HistoryManager(warDir, pool); } try{ if(historyManager != null && !hasExisting) { historyManager.logEvent(EntryType.CONFIG, // NOTE: We should integrate the git pointer into this class. new GitLocation(cloned.getRemoteRepository(), cloned.getBranchName(), cloned.getCurrentRevision()), "AUTO", renderedContentDir, "", "Initial config pull.", true, true); } } finally { if(pool != null) { pool.shutdownNow(); } } return cloned; } catch (Throwable e){ cloned.close(); throw new Exception(e); } }
java
public static GitService initializeConfigDirectory(String uri, String branch, String root, String warName, HistoryManager historyManager, ConfigManager configManager) throws Exception { initializeBaseDirectoryStructure(root, warName); String warDir = FileSystemManager.getChildDirectoryIfExists(root, warName); Properties configProperties = configManager.getDefaultProperties(); GitLocation gitLocation = new GitLocation(uri, branch, configProperties.getProperty("config.git.ref.sha")); GitService cloned = initializeRepo(gitLocation, warDir, "git-config-checkout"); try { String renderedContentDir = initializeSnapshotDirectory(warDir, configProperties, "com.meltmedia.cadmium.config.lastUpdated", "git-config-checkout", "config"); boolean hasExisting = configProperties.containsKey("com.meltmedia.cadmium.config.lastUpdated") && renderedContentDir != null && renderedContentDir.equals(configProperties.getProperty("com.meltmedia.cadmium.config.lastUpdated")); if(renderedContentDir != null) { configProperties.setProperty("com.meltmedia.cadmium.config.lastUpdated", renderedContentDir); } configProperties.setProperty("config.branch", cloned.getBranchName()); configProperties.setProperty("config.git.ref.sha", cloned.getCurrentRevision()); configProperties.setProperty("config.repo", cloned.getRemoteRepository()); configManager.persistDefaultProperties(); ExecutorService pool = null; if(historyManager == null) { pool = Executors.newSingleThreadExecutor(); historyManager = new HistoryManager(warDir, pool); } try{ if(historyManager != null && !hasExisting) { historyManager.logEvent(EntryType.CONFIG, // NOTE: We should integrate the git pointer into this class. new GitLocation(cloned.getRemoteRepository(), cloned.getBranchName(), cloned.getCurrentRevision()), "AUTO", renderedContentDir, "", "Initial config pull.", true, true); } } finally { if(pool != null) { pool.shutdownNow(); } } return cloned; } catch (Throwable e){ cloned.close(); throw new Exception(e); } }
[ "public", "static", "GitService", "initializeConfigDirectory", "(", "String", "uri", ",", "String", "branch", ",", "String", "root", ",", "String", "warName", ",", "HistoryManager", "historyManager", ",", "ConfigManager", "configManager", ")", "throws", "Exception", ...
Initializes war configuration directory for a Cadmium war. @param uri The remote Git repository ssh URI. @param branch The remote branch to checkout. @param root The shared root. @param warName The name of the war file. @param historyManager The history manager to log the initialization event. @return A GitService object the points to the freshly cloned Git repository. @throws RefNotFoundException @throws Exception
[ "Initializes", "war", "configuration", "directory", "for", "a", "Cadmium", "war", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/git/GitService.java#L175-L225
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/git/GitService.java
GitService.checkinNewContent
public String checkinNewContent(String sourceDirectory, String message) throws Exception { RmCommand remove = git.rm(); boolean hasFiles = false; for(String filename : new File(getBaseDirectory()).list()) { if(!filename.equals(".git")) { remove.addFilepattern(filename); hasFiles = true; } } if(hasFiles) { log.info("Removing old content."); remove.call(); } log.info("Copying in new content."); FileSystemManager.copyAllContent(sourceDirectory, getBaseDirectory(), true); log.info("Adding new content."); AddCommand add = git.add(); for(String filename : new File(getBaseDirectory()).list()) { if(!filename.equals(".git")) { add.addFilepattern(filename); } } add.call(); log.info("Committing new content."); git.commit().setMessage(message).call(); return getCurrentRevision(); }
java
public String checkinNewContent(String sourceDirectory, String message) throws Exception { RmCommand remove = git.rm(); boolean hasFiles = false; for(String filename : new File(getBaseDirectory()).list()) { if(!filename.equals(".git")) { remove.addFilepattern(filename); hasFiles = true; } } if(hasFiles) { log.info("Removing old content."); remove.call(); } log.info("Copying in new content."); FileSystemManager.copyAllContent(sourceDirectory, getBaseDirectory(), true); log.info("Adding new content."); AddCommand add = git.add(); for(String filename : new File(getBaseDirectory()).list()) { if(!filename.equals(".git")) { add.addFilepattern(filename); } } add.call(); log.info("Committing new content."); git.commit().setMessage(message).call(); return getCurrentRevision(); }
[ "public", "String", "checkinNewContent", "(", "String", "sourceDirectory", ",", "String", "message", ")", "throws", "Exception", "{", "RmCommand", "remove", "=", "git", ".", "rm", "(", ")", ";", "boolean", "hasFiles", "=", "false", ";", "for", "(", "String",...
Checks in content from a source directory into the current git repository. @param sourceDirectory The directory to pull content in from. @param message The commit message to use. @return The new SHA revision. @throws Exception
[ "Checks", "in", "content", "from", "a", "source", "directory", "into", "the", "current", "git", "repository", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/git/GitService.java#L578-L604
train
opentable/otj-logging
core/src/main/java/com/opentable/logging/JsonLogEncoder.java
JsonLogEncoder.convertToObjectNode
public ObjectNode convertToObjectNode(ILoggingEvent event) { final ObjectNode logLine = mapper.valueToTree( event instanceof OtlType ? event : new ApplicationLogEvent(event)); final Marker marker = event.getMarker(); if (marker instanceof LogMetadata) { ObjectNode metadataNode = mapper.valueToTree(((LogMetadata) marker).getMetadata()); logLine.setAll(metadataNode); for (Object o : ((LogMetadata) marker).getInlines()) { metadataNode = mapper.valueToTree(o); logLine.setAll(metadataNode); } } if (marker instanceof OtlMarker) { ObjectNode metadataNode = mapper.valueToTree(((OtlMarker) marker).getOtl()); logLine.setAll(metadataNode); } for (Entry<String, String> e : event.getMDCPropertyMap().entrySet()) { if (!logLine.has(e.getKey())) { logLine.put(e.getKey(), e.getValue()); } } logLine.put("sequencenumber", LOG_SEQUENCE_NUMBER.incrementAndGet()); return logLine; }
java
public ObjectNode convertToObjectNode(ILoggingEvent event) { final ObjectNode logLine = mapper.valueToTree( event instanceof OtlType ? event : new ApplicationLogEvent(event)); final Marker marker = event.getMarker(); if (marker instanceof LogMetadata) { ObjectNode metadataNode = mapper.valueToTree(((LogMetadata) marker).getMetadata()); logLine.setAll(metadataNode); for (Object o : ((LogMetadata) marker).getInlines()) { metadataNode = mapper.valueToTree(o); logLine.setAll(metadataNode); } } if (marker instanceof OtlMarker) { ObjectNode metadataNode = mapper.valueToTree(((OtlMarker) marker).getOtl()); logLine.setAll(metadataNode); } for (Entry<String, String> e : event.getMDCPropertyMap().entrySet()) { if (!logLine.has(e.getKey())) { logLine.put(e.getKey(), e.getValue()); } } logLine.put("sequencenumber", LOG_SEQUENCE_NUMBER.incrementAndGet()); return logLine; }
[ "public", "ObjectNode", "convertToObjectNode", "(", "ILoggingEvent", "event", ")", "{", "final", "ObjectNode", "logLine", "=", "mapper", ".", "valueToTree", "(", "event", "instanceof", "OtlType", "?", "event", ":", "new", "ApplicationLogEvent", "(", "event", ")", ...
Prepare a log event but don't append it, return it as an ObjectNode instead. @param the logging event to encode @return the JSON object version of the log event
[ "Prepare", "a", "log", "event", "but", "don", "t", "append", "it", "return", "it", "as", "an", "ObjectNode", "instead", "." ]
eaa74c877c4721ddb9af8eb7fe1612166f7ac14d
https://github.com/opentable/otj-logging/blob/eaa74c877c4721ddb9af8eb7fe1612166f7ac14d/core/src/main/java/com/opentable/logging/JsonLogEncoder.java#L71-L98
train
opentable/otj-logging
core/src/main/java/com/opentable/logging/JsonLogEncoder.java
JsonLogEncoder.getLogMessage
protected byte[] getLogMessage(final ObjectNode event) { try(ByteArrayBuilder buf = new ByteArrayBuilder()){ mapper.writeValue(buf, event); buf.append('\n'); return buf.toByteArray(); } catch (IOException e) { addError("while serializing log event", e); return NADA; } }
java
protected byte[] getLogMessage(final ObjectNode event) { try(ByteArrayBuilder buf = new ByteArrayBuilder()){ mapper.writeValue(buf, event); buf.append('\n'); return buf.toByteArray(); } catch (IOException e) { addError("while serializing log event", e); return NADA; } }
[ "protected", "byte", "[", "]", "getLogMessage", "(", "final", "ObjectNode", "event", ")", "{", "try", "(", "ByteArrayBuilder", "buf", "=", "new", "ByteArrayBuilder", "(", ")", ")", "{", "mapper", ".", "writeValue", "(", "buf", ",", "event", ")", ";", "bu...
Convert the JSON object to a byte array to log @param event the event to log @return the byte array to append to the log
[ "Convert", "the", "JSON", "object", "to", "a", "byte", "array", "to", "log" ]
eaa74c877c4721ddb9af8eb7fe1612166f7ac14d
https://github.com/opentable/otj-logging/blob/eaa74c877c4721ddb9af8eb7fe1612166f7ac14d/core/src/main/java/com/opentable/logging/JsonLogEncoder.java#L105-L114
train
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/CommitCommand.java
CommitCommand.execute
public void execute() throws Exception { String content = null; String siteUrl = null; if (params.size() == 2) { content = params.get(0); siteUrl = getSecureBaseUrl(params.get(1)); } else if (params.size() == 0) { System.err.println("The content directory and site must be specifed."); System.exit(1); } else { System.err.println("Too many parameters were specified."); System.exit(1); } GitService git = null; try { System.out.println("Getting status of [" + siteUrl + "]"); Status status = StatusCommand.getSiteStatus(siteUrl, token); if (repo != null) { status.setRepo(repo); } status.setRevision(null); System.out.println("Cloning repository that [" + siteUrl + "] is serving"); git = CloneCommand.cloneSiteRepo(status); String revision = status.getRevision(); String branch = status.getBranch(); if (!UpdateCommand.isValidBranchName(branch, UpdateRequest.CONTENT_BRANCH_PREFIX)) { throw new Exception("Cannot commit to a branch without the prefix of " + UpdateRequest.CONTENT_BRANCH_PREFIX + "."); } if (git.isTag(branch)) { throw new Exception("Cannot commit to a tag!"); } System.out.println("Cloning content from [" + content + "] to [" + siteUrl + ":" + branch + "]"); revision = CloneCommand.cloneContent(content, git, comment); System.out.println("Switching content on [" + siteUrl + "]"); if (!UpdateCommand.sendUpdateMessage(siteUrl, null, branch, revision, comment, token)) { System.err.println("Failed to update [" + siteUrl + "]"); System.exit(1); } } catch (Exception e) { System.err.println("Failed to commit changes to [" + siteUrl + "]: " + e.getMessage()); System.exit(1); } finally { if (git != null) { String dir = git.getBaseDirectory(); git.close(); FileUtils.forceDelete(new File(dir)); } } }
java
public void execute() throws Exception { String content = null; String siteUrl = null; if (params.size() == 2) { content = params.get(0); siteUrl = getSecureBaseUrl(params.get(1)); } else if (params.size() == 0) { System.err.println("The content directory and site must be specifed."); System.exit(1); } else { System.err.println("Too many parameters were specified."); System.exit(1); } GitService git = null; try { System.out.println("Getting status of [" + siteUrl + "]"); Status status = StatusCommand.getSiteStatus(siteUrl, token); if (repo != null) { status.setRepo(repo); } status.setRevision(null); System.out.println("Cloning repository that [" + siteUrl + "] is serving"); git = CloneCommand.cloneSiteRepo(status); String revision = status.getRevision(); String branch = status.getBranch(); if (!UpdateCommand.isValidBranchName(branch, UpdateRequest.CONTENT_BRANCH_PREFIX)) { throw new Exception("Cannot commit to a branch without the prefix of " + UpdateRequest.CONTENT_BRANCH_PREFIX + "."); } if (git.isTag(branch)) { throw new Exception("Cannot commit to a tag!"); } System.out.println("Cloning content from [" + content + "] to [" + siteUrl + ":" + branch + "]"); revision = CloneCommand.cloneContent(content, git, comment); System.out.println("Switching content on [" + siteUrl + "]"); if (!UpdateCommand.sendUpdateMessage(siteUrl, null, branch, revision, comment, token)) { System.err.println("Failed to update [" + siteUrl + "]"); System.exit(1); } } catch (Exception e) { System.err.println("Failed to commit changes to [" + siteUrl + "]: " + e.getMessage()); System.exit(1); } finally { if (git != null) { String dir = git.getBaseDirectory(); git.close(); FileUtils.forceDelete(new File(dir)); } } }
[ "public", "void", "execute", "(", ")", "throws", "Exception", "{", "String", "content", "=", "null", ";", "String", "siteUrl", "=", "null", ";", "if", "(", "params", ".", "size", "(", ")", "==", "2", ")", "{", "content", "=", "params", ".", "get", ...
Does the work for this command. @throws Exception
[ "Does", "the", "work", "for", "this", "command", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/CommitCommand.java#L55-L114
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/serialization/TupleSerialization.java
TupleSerialization.enableSerialization
public static void enableSerialization(Configuration conf) { String serClass = TupleSerialization.class.getName(); Collection<String> currentSers = conf.getStringCollection("io.serializations"); if(currentSers.size() == 0) { conf.set("io.serializations", serClass); return; } // Check if it is already present if(!currentSers.contains(serClass)) { currentSers.add(serClass); conf.setStrings("io.serializations", currentSers.toArray(new String[] {})); } }
java
public static void enableSerialization(Configuration conf) { String serClass = TupleSerialization.class.getName(); Collection<String> currentSers = conf.getStringCollection("io.serializations"); if(currentSers.size() == 0) { conf.set("io.serializations", serClass); return; } // Check if it is already present if(!currentSers.contains(serClass)) { currentSers.add(serClass); conf.setStrings("io.serializations", currentSers.toArray(new String[] {})); } }
[ "public", "static", "void", "enableSerialization", "(", "Configuration", "conf", ")", "{", "String", "serClass", "=", "TupleSerialization", ".", "class", ".", "getName", "(", ")", ";", "Collection", "<", "String", ">", "currentSers", "=", "conf", ".", "getStri...
Use this method to enable this serialization in Hadoop
[ "Use", "this", "method", "to", "enable", "this", "serialization", "in", "Hadoop" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/serialization/TupleSerialization.java#L138-L152
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/serialization/TupleSerialization.java
TupleSerialization.disableSerialization
public static void disableSerialization(Configuration conf) { String ser = conf.get("io.serializations").trim(); String stToSearch = Pattern.quote("," + TupleSerialization.class.getName()); ser = ser.replaceAll(stToSearch, ""); conf.set("io.serializations", ser); }
java
public static void disableSerialization(Configuration conf) { String ser = conf.get("io.serializations").trim(); String stToSearch = Pattern.quote("," + TupleSerialization.class.getName()); ser = ser.replaceAll(stToSearch, ""); conf.set("io.serializations", ser); }
[ "public", "static", "void", "disableSerialization", "(", "Configuration", "conf", ")", "{", "String", "ser", "=", "conf", ".", "get", "(", "\"io.serializations\"", ")", ".", "trim", "(", ")", ";", "String", "stToSearch", "=", "Pattern", ".", "quote", "(", ...
Use this method to disable this serialization in Hadoop
[ "Use", "this", "method", "to", "disable", "this", "serialization", "in", "Hadoop" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/serialization/TupleSerialization.java#L157-L162
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/util/sort/QNameSort.java
QNameSort.compare
public static int compare(String ns1, String ln1, String ns2, String ln2) { if (ns1 == null) { ns1 = Constants.XML_NULL_NS_URI; } if (ns2 == null) { ns2 = Constants.XML_NULL_NS_URI; } int cLocalPart = ln1.compareTo(ln2); return (cLocalPart == 0 ? ns1.compareTo(ns2) : cLocalPart); }
java
public static int compare(String ns1, String ln1, String ns2, String ln2) { if (ns1 == null) { ns1 = Constants.XML_NULL_NS_URI; } if (ns2 == null) { ns2 = Constants.XML_NULL_NS_URI; } int cLocalPart = ln1.compareTo(ln2); return (cLocalPart == 0 ? ns1.compareTo(ns2) : cLocalPart); }
[ "public", "static", "int", "compare", "(", "String", "ns1", ",", "String", "ln1", ",", "String", "ns2", ",", "String", "ln2", ")", "{", "if", "(", "ns1", "==", "null", ")", "{", "ns1", "=", "Constants", ".", "XML_NULL_NS_URI", ";", "}", "if", "(", ...
Sort lexicographically by qname local-name, then by qname uri @param ns1 qname1 namespace @param ln1 qname1 local-name @param ns2 qname2 namespace @param ln2 qname2 local-name @return a negative integer, zero, or a positive integer as the first qname is less than, equal to, or greater than the second.
[ "Sort", "lexicographically", "by", "qname", "local", "-", "name", "then", "by", "qname", "uri" ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/util/sort/QNameSort.java#L63-L72
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.postConstructQuietly
public static void postConstructQuietly(Object obj, Logger log) { try { postConstruct(obj, log); } catch( Throwable t ) { log.warn("Could not @PostConstruct object", t); } }
java
public static void postConstructQuietly(Object obj, Logger log) { try { postConstruct(obj, log); } catch( Throwable t ) { log.warn("Could not @PostConstruct object", t); } }
[ "public", "static", "void", "postConstructQuietly", "(", "Object", "obj", ",", "Logger", "log", ")", "{", "try", "{", "postConstruct", "(", "obj", ",", "log", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "log", ".", "warn", "(", "\"Could no...
Calls postConstruct with the same arguments, logging any exceptions that are thrown at the level warn.
[ "Calls", "postConstruct", "with", "the", "same", "arguments", "logging", "any", "exceptions", "that", "are", "thrown", "at", "the", "level", "warn", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L70-L77
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.preDestroyQuietly
public static void preDestroyQuietly(Object obj, Logger log) { try { preDestroy(obj, log); } catch( Throwable t ) { log.warn("Could not @PreDestroy object", t); } }
java
public static void preDestroyQuietly(Object obj, Logger log) { try { preDestroy(obj, log); } catch( Throwable t ) { log.warn("Could not @PreDestroy object", t); } }
[ "public", "static", "void", "preDestroyQuietly", "(", "Object", "obj", ",", "Logger", "log", ")", "{", "try", "{", "preDestroy", "(", "obj", ",", "log", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "log", ".", "warn", "(", "\"Could not @Pre...
Calls preDestroy with the same arguments, logging any exceptions that are thrown at the level warn.
[ "Calls", "preDestroy", "with", "the", "same", "arguments", "logging", "any", "exceptions", "that", "are", "thrown", "at", "the", "level", "warn", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L96-L103
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.getAnnotatedMethodsFromChildToParent
private static List<Method> getAnnotatedMethodsFromChildToParent(Class<?> clazz, Class<? extends Annotation> annotation, Logger log) { List<Method> methodsToRun = new ArrayList<Method>(); while(clazz != null) { List<Method> newMethods = getMethodsWithAnnotation(clazz, annotation, log); for(Method newMethod : newMethods) { if(containsMethod(newMethod, methodsToRun)) { removeMethodByName(newMethod, methodsToRun); } else { methodsToRun.add(newMethod); } } clazz = clazz.getSuperclass(); if(clazz != null && clazz.equals(Object.class)) { clazz = null; } } return methodsToRun; }
java
private static List<Method> getAnnotatedMethodsFromChildToParent(Class<?> clazz, Class<? extends Annotation> annotation, Logger log) { List<Method> methodsToRun = new ArrayList<Method>(); while(clazz != null) { List<Method> newMethods = getMethodsWithAnnotation(clazz, annotation, log); for(Method newMethod : newMethods) { if(containsMethod(newMethod, methodsToRun)) { removeMethodByName(newMethod, methodsToRun); } else { methodsToRun.add(newMethod); } } clazz = clazz.getSuperclass(); if(clazz != null && clazz.equals(Object.class)) { clazz = null; } } return methodsToRun; }
[ "private", "static", "List", "<", "Method", ">", "getAnnotatedMethodsFromChildToParent", "(", "Class", "<", "?", ">", "clazz", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotation", ",", "Logger", "log", ")", "{", "List", "<", "Method", ">", "...
Locates all annotated methods on the type passed in sorted as declared from the type to its super class. @param clazz The type of the class to get methods from. @param annotation The annotation to look for on methods. @param log @return
[ "Locates", "all", "annotated", "methods", "on", "the", "type", "passed", "in", "sorted", "as", "declared", "from", "the", "type", "to", "its", "super", "class", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L142-L160
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.containsMethod
private static boolean containsMethod(Method method, List<Method> methods) { if(methods != null) { for(Method aMethod : methods){ if(method.getName().equals(aMethod.getName())) { return true; } } } return false; }
java
private static boolean containsMethod(Method method, List<Method> methods) { if(methods != null) { for(Method aMethod : methods){ if(method.getName().equals(aMethod.getName())) { return true; } } } return false; }
[ "private", "static", "boolean", "containsMethod", "(", "Method", "method", ",", "List", "<", "Method", ">", "methods", ")", "{", "if", "(", "methods", "!=", "null", ")", "{", "for", "(", "Method", "aMethod", ":", "methods", ")", "{", "if", "(", "method...
Checks if the passed in method already exists in the list of methods. Checks for equality by the name of the method. @param method @param methods @return
[ "Checks", "if", "the", "passed", "in", "method", "already", "exists", "in", "the", "list", "of", "methods", ".", "Checks", "for", "equality", "by", "the", "name", "of", "the", "method", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L168-L177
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.removeMethodByName
private static void removeMethodByName(Method method, List<Method> methods) { if(methods != null) { Iterator<Method> itr = methods.iterator(); Method aMethod = null; while(itr.hasNext()) { aMethod = itr.next(); if(aMethod.getName().equals(method.getName())) { itr.remove(); break; } } if(aMethod != null) { methods.add(aMethod); } } }
java
private static void removeMethodByName(Method method, List<Method> methods) { if(methods != null) { Iterator<Method> itr = methods.iterator(); Method aMethod = null; while(itr.hasNext()) { aMethod = itr.next(); if(aMethod.getName().equals(method.getName())) { itr.remove(); break; } } if(aMethod != null) { methods.add(aMethod); } } }
[ "private", "static", "void", "removeMethodByName", "(", "Method", "method", ",", "List", "<", "Method", ">", "methods", ")", "{", "if", "(", "methods", "!=", "null", ")", "{", "Iterator", "<", "Method", ">", "itr", "=", "methods", ".", "iterator", "(", ...
Removes a method from the given list and adds it to the end of the list. @param method @param methods
[ "Removes", "a", "method", "from", "the", "given", "list", "and", "adds", "it", "to", "the", "end", "of", "the", "list", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L184-L199
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.getMethodsWithAnnotation
private static List<Method> getMethodsWithAnnotation(Class<?> clazz, Class<? extends Annotation> annotation, Logger log) { List<Method> annotatedMethods = new ArrayList<Method>(); Method classMethods[] = clazz.getDeclaredMethods(); for(Method classMethod : classMethods) { if(classMethod.isAnnotationPresent(annotation) && classMethod.getParameterTypes().length == 0) { if(!containsMethod(classMethod, annotatedMethods)) { annotatedMethods.add(classMethod); } } } Collections.sort(annotatedMethods, new Comparator<Method> () { @Override public int compare(Method method1, Method method2) { return method1.getName().compareTo(method2.getName()); } }); return annotatedMethods; }
java
private static List<Method> getMethodsWithAnnotation(Class<?> clazz, Class<? extends Annotation> annotation, Logger log) { List<Method> annotatedMethods = new ArrayList<Method>(); Method classMethods[] = clazz.getDeclaredMethods(); for(Method classMethod : classMethods) { if(classMethod.isAnnotationPresent(annotation) && classMethod.getParameterTypes().length == 0) { if(!containsMethod(classMethod, annotatedMethods)) { annotatedMethods.add(classMethod); } } } Collections.sort(annotatedMethods, new Comparator<Method> () { @Override public int compare(Method method1, Method method2) { return method1.getName().compareTo(method2.getName()); } }); return annotatedMethods; }
[ "private", "static", "List", "<", "Method", ">", "getMethodsWithAnnotation", "(", "Class", "<", "?", ">", "clazz", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotation", ",", "Logger", "log", ")", "{", "List", "<", "Method", ">", "annotatedMet...
Locates all methods annotated with a given annotation that are declared directly in the class passed in alphabetical order. @param clazz @param annotation @param log @return
[ "Locates", "all", "methods", "annotated", "with", "a", "given", "annotation", "that", "are", "declared", "directly", "in", "the", "class", "passed", "in", "alphabetical", "order", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L209-L227
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.createJsr250Executor
public static Jsr250Executor createJsr250Executor(Injector injector, final Logger log, Scope... scopes ) { final Set<Object> instances = findInstancesInScopes(injector, scopes); final List<Object> reverseInstances = new ArrayList<Object>(instances); Collections.reverse(reverseInstances); return new Jsr250Executor() { @Override public Set<Object> getInstances() { return instances; } @Override public void postConstruct() { for( Object instance : instances ) { postConstructQuietly(instance, log); } } @Override public void preDestroy() { for( Object instance : reverseInstances ) { preDestroyQuietly(instance, log); } } }; }
java
public static Jsr250Executor createJsr250Executor(Injector injector, final Logger log, Scope... scopes ) { final Set<Object> instances = findInstancesInScopes(injector, scopes); final List<Object> reverseInstances = new ArrayList<Object>(instances); Collections.reverse(reverseInstances); return new Jsr250Executor() { @Override public Set<Object> getInstances() { return instances; } @Override public void postConstruct() { for( Object instance : instances ) { postConstructQuietly(instance, log); } } @Override public void preDestroy() { for( Object instance : reverseInstances ) { preDestroyQuietly(instance, log); } } }; }
[ "public", "static", "Jsr250Executor", "createJsr250Executor", "(", "Injector", "injector", ",", "final", "Logger", "log", ",", "Scope", "...", "scopes", ")", "{", "final", "Set", "<", "Object", ">", "instances", "=", "findInstancesInScopes", "(", "injector", ","...
Creates a Jsr250Executor for the specified scopes. @param injector @param log @param scopes @return
[ "Creates", "a", "Jsr250Executor", "for", "the", "specified", "scopes", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L237-L263
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.findInstancesInScopes
public static Set<Object> findInstancesInScopes(Injector injector, Class<? extends Annotation>... scopeAnnotations) { Set<Object> objects = new TreeSet<Object>(new Comparator<Object>() { @Override public int compare(Object o0, Object o1) { return o0.getClass().getName().compareTo(o1.getClass().getName()); } }); for( Map.Entry<Key<?>, Binding<?>> entry : findBindingsInScope(injector, scopeAnnotations).entrySet()) { Object object = injector.getInstance(entry.getKey()); objects.add(object); } return objects; }
java
public static Set<Object> findInstancesInScopes(Injector injector, Class<? extends Annotation>... scopeAnnotations) { Set<Object> objects = new TreeSet<Object>(new Comparator<Object>() { @Override public int compare(Object o0, Object o1) { return o0.getClass().getName().compareTo(o1.getClass().getName()); } }); for( Map.Entry<Key<?>, Binding<?>> entry : findBindingsInScope(injector, scopeAnnotations).entrySet()) { Object object = injector.getInstance(entry.getKey()); objects.add(object); } return objects; }
[ "public", "static", "Set", "<", "Object", ">", "findInstancesInScopes", "(", "Injector", "injector", ",", "Class", "<", "?", "extends", "Annotation", ">", "...", "scopeAnnotations", ")", "{", "Set", "<", "Object", ">", "objects", "=", "new", "TreeSet", "<", ...
Finds all of the instances in the specified scopes. <p> Returns a list of the objects from the specified scope, sorted by their class name. </p> @param injector the injector to search. @param scopeAnnotations the scopes to search for. @return the objects bound in the injector.
[ "Finds", "all", "of", "the", "instances", "in", "the", "specified", "scopes", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L276-L290
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.findBindingsInScope
public static Map<Key<?>, Binding<?>> findBindingsInScope(Injector injector, Class<? extends Annotation>... scopeAnnotations) { Map<Key<?>,Binding<?>> bindings = new LinkedHashMap<Key<?>, Binding<?>>(); ALL_BINDINGS: for( Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet() ) { for( Class<? extends Annotation> scopeAnnotation : scopeAnnotations ) { if( inScope(injector, entry.getValue(), scopeAnnotation )) { bindings.put(entry.getKey(), entry.getValue()); continue ALL_BINDINGS; } } } return bindings; }
java
public static Map<Key<?>, Binding<?>> findBindingsInScope(Injector injector, Class<? extends Annotation>... scopeAnnotations) { Map<Key<?>,Binding<?>> bindings = new LinkedHashMap<Key<?>, Binding<?>>(); ALL_BINDINGS: for( Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet() ) { for( Class<? extends Annotation> scopeAnnotation : scopeAnnotations ) { if( inScope(injector, entry.getValue(), scopeAnnotation )) { bindings.put(entry.getKey(), entry.getValue()); continue ALL_BINDINGS; } } } return bindings; }
[ "public", "static", "Map", "<", "Key", "<", "?", ">", ",", "Binding", "<", "?", ">", ">", "findBindingsInScope", "(", "Injector", "injector", ",", "Class", "<", "?", "extends", "Annotation", ">", "...", "scopeAnnotations", ")", "{", "Map", "<", "Key", ...
Finds all of the unique providers in the injector in the specified scopes. <p> </p> @param injector the injector to search. @param scopeAnnotations the scopes to search for. @return the keys for the specified scope names.
[ "Finds", "all", "of", "the", "unique", "providers", "in", "the", "injector", "in", "the", "specified", "scopes", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L329-L340
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.findBindingsInScope
public static Map<Key<?>, Binding<?>> findBindingsInScope(Injector injector, Scope... scopes) { Map<Key<?>,Binding<?>> bindings = new LinkedHashMap<Key<?>, Binding<?>>(); ALL_BINDINGS: for( Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet() ) { for( Scope scope : scopes ) { if( inScope(injector, entry.getValue(), scope )) { bindings.put(entry.getKey(), entry.getValue()); continue ALL_BINDINGS; } } } return bindings; }
java
public static Map<Key<?>, Binding<?>> findBindingsInScope(Injector injector, Scope... scopes) { Map<Key<?>,Binding<?>> bindings = new LinkedHashMap<Key<?>, Binding<?>>(); ALL_BINDINGS: for( Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet() ) { for( Scope scope : scopes ) { if( inScope(injector, entry.getValue(), scope )) { bindings.put(entry.getKey(), entry.getValue()); continue ALL_BINDINGS; } } } return bindings; }
[ "public", "static", "Map", "<", "Key", "<", "?", ">", ",", "Binding", "<", "?", ">", ">", "findBindingsInScope", "(", "Injector", "injector", ",", "Scope", "...", "scopes", ")", "{", "Map", "<", "Key", "<", "?", ">", ",", "Binding", "<", "?", ">", ...
Returns the bindings in the specified scope. @param injector @param scopes @return
[ "Returns", "the", "bindings", "in", "the", "specified", "scope", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L349-L360
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java
Jsr250Utils.inScope
public static boolean inScope(final Injector injector, final Binding<?> binding, final Class<? extends Annotation> scope) { return binding.acceptScopingVisitor(new BindingScopingVisitor<Boolean>() { @Override public Boolean visitEagerSingleton() { return scope == Singleton.class || scope == javax.inject.Singleton.class; } @Override public Boolean visitNoScoping() { return false; } @Override public Boolean visitScope(Scope guiceScope) { return injector.getScopeBindings().get(scope) == guiceScope; } @Override public Boolean visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) { return scopeAnnotation == scope; } }); }
java
public static boolean inScope(final Injector injector, final Binding<?> binding, final Class<? extends Annotation> scope) { return binding.acceptScopingVisitor(new BindingScopingVisitor<Boolean>() { @Override public Boolean visitEagerSingleton() { return scope == Singleton.class || scope == javax.inject.Singleton.class; } @Override public Boolean visitNoScoping() { return false; } @Override public Boolean visitScope(Scope guiceScope) { return injector.getScopeBindings().get(scope) == guiceScope; } @Override public Boolean visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) { return scopeAnnotation == scope; } }); }
[ "public", "static", "boolean", "inScope", "(", "final", "Injector", "injector", ",", "final", "Binding", "<", "?", ">", "binding", ",", "final", "Class", "<", "?", "extends", "Annotation", ">", "scope", ")", "{", "return", "binding", ".", "acceptScopingVisit...
Returns true if the binding is in the specified scope, false otherwise. @param binding the binding to inspect @param scope the scope to look for @return true if the binding is in the specified scope, false otherwise.
[ "Returns", "true", "if", "the", "binding", "is", "in", "the", "specified", "scope", "false", "otherwise", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/Jsr250Utils.java#L368-L391
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/scheduler/SchedulerTask.java
SchedulerTask.init
private void init(Class<?> type) { if(method.isAnnotationPresent(CoordinatorOnly.class) || type.isAnnotationPresent(CoordinatorOnly.class)) { coordinatorOnly = true; } if(method.isAnnotationPresent(Scheduled.class)) { annotation = method.getAnnotation(Scheduled.class); } else if(type.isAnnotationPresent(Scheduled.class)) { annotation = type.getAnnotation(Scheduled.class); } }
java
private void init(Class<?> type) { if(method.isAnnotationPresent(CoordinatorOnly.class) || type.isAnnotationPresent(CoordinatorOnly.class)) { coordinatorOnly = true; } if(method.isAnnotationPresent(Scheduled.class)) { annotation = method.getAnnotation(Scheduled.class); } else if(type.isAnnotationPresent(Scheduled.class)) { annotation = type.getAnnotation(Scheduled.class); } }
[ "private", "void", "init", "(", "Class", "<", "?", ">", "type", ")", "{", "if", "(", "method", ".", "isAnnotationPresent", "(", "CoordinatorOnly", ".", "class", ")", "||", "type", ".", "isAnnotationPresent", "(", "CoordinatorOnly", ".", "class", ")", ")", ...
Sets all values needed for the scheduling of this Runnable. @param type
[ "Sets", "all", "values", "needed", "for", "the", "scheduling", "of", "this", "Runnable", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/scheduler/SchedulerTask.java#L88-L98
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/scheduler/SchedulerTask.java
SchedulerTask.checkRunnable
private void checkRunnable(Class<?> type) { if(Runnable.class.isAssignableFrom(type)) { try{ this.method = type.getMethod("run"); } catch(Exception e) { throw new RuntimeException("Cannot get run method of runnable class.", e); } } }
java
private void checkRunnable(Class<?> type) { if(Runnable.class.isAssignableFrom(type)) { try{ this.method = type.getMethod("run"); } catch(Exception e) { throw new RuntimeException("Cannot get run method of runnable class.", e); } } }
[ "private", "void", "checkRunnable", "(", "Class", "<", "?", ">", "type", ")", "{", "if", "(", "Runnable", ".", "class", ".", "isAssignableFrom", "(", "type", ")", ")", "{", "try", "{", "this", ".", "method", "=", "type", ".", "getMethod", "(", "\"run...
Checks if the type is a Runnable and gets the run method. @param type
[ "Checks", "if", "the", "type", "is", "a", "Runnable", "and", "gets", "the", "run", "method", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/scheduler/SchedulerTask.java#L117-L125
train
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/ApiCommand.java
ApiCommand.sendRequest
public static String[] sendRequest(String token, String site, OPERATION op, String path) throws Exception { HttpClient client = httpClient(); HttpUriRequest message = null; if(op == OPERATION.DISABLE) { message = new HttpPut(site + ENDPOINT + path); } else if(op == OPERATION.ENABLE){ message = new HttpDelete(site + ENDPOINT + path); } else { message = new HttpGet(site + ENDPOINT); } addAuthHeader(token, message); HttpResponse resp = client.execute(message); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String results = EntityUtils.toString(resp.getEntity()); return new Gson().fromJson(results, String[].class); } return null; }
java
public static String[] sendRequest(String token, String site, OPERATION op, String path) throws Exception { HttpClient client = httpClient(); HttpUriRequest message = null; if(op == OPERATION.DISABLE) { message = new HttpPut(site + ENDPOINT + path); } else if(op == OPERATION.ENABLE){ message = new HttpDelete(site + ENDPOINT + path); } else { message = new HttpGet(site + ENDPOINT); } addAuthHeader(token, message); HttpResponse resp = client.execute(message); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String results = EntityUtils.toString(resp.getEntity()); return new Gson().fromJson(results, String[].class); } return null; }
[ "public", "static", "String", "[", "]", "sendRequest", "(", "String", "token", ",", "String", "site", ",", "OPERATION", "op", ",", "String", "path", ")", "throws", "Exception", "{", "HttpClient", "client", "=", "httpClient", "(", ")", ";", "HttpUriRequest", ...
Sends acl request to cadmium. @param site @param op @param path @return @throws Exception
[ "Sends", "acl", "request", "to", "cadmium", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/ApiCommand.java#L90-L108
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/Tuple.java
Tuple.shallowCopy
public void shallowCopy(ITuple tupleDest) { for(Field field: this.getSchema().getFields()) { tupleDest.set(field.getName(), this.get(field.getName())); } }
java
public void shallowCopy(ITuple tupleDest) { for(Field field: this.getSchema().getFields()) { tupleDest.set(field.getName(), this.get(field.getName())); } }
[ "public", "void", "shallowCopy", "(", "ITuple", "tupleDest", ")", "{", "for", "(", "Field", "field", ":", "this", ".", "getSchema", "(", ")", ".", "getFields", "(", ")", ")", "{", "tupleDest", ".", "set", "(", "field", ".", "getName", "(", ")", ",", ...
Simple shallow copy of this Tuple to another Tuple. @param tupleDest The destination Tuple (should have the same Schema or a super-set of it).
[ "Simple", "shallow", "copy", "of", "this", "Tuple", "to", "another", "Tuple", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/Tuple.java#L192-L196
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/util/xml/QNameUtilities.java
QNameUtilities.getQualifiedName
public static final String getQualifiedName(String localName, String pfx) { pfx = pfx == null ? "" : pfx; return pfx.length() == 0 ? localName : (pfx + Constants.COLON + localName); }
java
public static final String getQualifiedName(String localName, String pfx) { pfx = pfx == null ? "" : pfx; return pfx.length() == 0 ? localName : (pfx + Constants.COLON + localName); }
[ "public", "static", "final", "String", "getQualifiedName", "(", "String", "localName", ",", "String", "pfx", ")", "{", "pfx", "=", "pfx", "==", "null", "?", "\"\"", ":", "pfx", ";", "return", "pfx", ".", "length", "(", ")", "==", "0", "?", "localName",...
Returns qualified name as String <p> QName ::= PrefixedName | UnprefixedName <br> PrefixedName ::= Prefix ':' LocalPart <br> UnprefixedName ::= LocalPart </p> @param localName local-name @param pfx prefix @return <code>String</code> for qname
[ "Returns", "qualified", "name", "as", "String" ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/util/xml/QNameUtilities.java#L85-L89
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/EncodingOptions.java
EncodingOptions.setOption
public void setOption(String key, Object value) throws UnsupportedOption { if (key.equals(INCLUDE_COOKIE)) { options.put(key, null); } else if (key.equals(INCLUDE_OPTIONS)) { options.put(key, null); } else if (key.equals(INCLUDE_SCHEMA_ID)) { options.put(key, null); } else if (key.equals(RETAIN_ENTITY_REFERENCE)) { options.put(key, null); } else if (key.equals(INCLUDE_XSI_SCHEMALOCATION)) { options.put(key, null); } else if (key.equals(INCLUDE_INSIGNIFICANT_XSI_NIL)) { options.put(key, null); } else if (key.equals(INCLUDE_PROFILE_VALUES)) { options.put(key, null); } else if (key.equals(CANONICAL_EXI)) { options.put(key, null); // by default the Canonical EXI Option "omitOptionsDocument" is // false // --> include options this.setOption(INCLUDE_OPTIONS); } else if (key.equals(UTC_TIME)) { options.put(key, null); } else if (key.equals(DEFLATE_COMPRESSION_VALUE)) { if (value != null && value instanceof Integer) { options.put(key, value); } else { throw new UnsupportedOption("EncodingOption '" + key + "' requires value of type Integer"); } } else { throw new UnsupportedOption("EncodingOption '" + key + "' is unknown!"); } }
java
public void setOption(String key, Object value) throws UnsupportedOption { if (key.equals(INCLUDE_COOKIE)) { options.put(key, null); } else if (key.equals(INCLUDE_OPTIONS)) { options.put(key, null); } else if (key.equals(INCLUDE_SCHEMA_ID)) { options.put(key, null); } else if (key.equals(RETAIN_ENTITY_REFERENCE)) { options.put(key, null); } else if (key.equals(INCLUDE_XSI_SCHEMALOCATION)) { options.put(key, null); } else if (key.equals(INCLUDE_INSIGNIFICANT_XSI_NIL)) { options.put(key, null); } else if (key.equals(INCLUDE_PROFILE_VALUES)) { options.put(key, null); } else if (key.equals(CANONICAL_EXI)) { options.put(key, null); // by default the Canonical EXI Option "omitOptionsDocument" is // false // --> include options this.setOption(INCLUDE_OPTIONS); } else if (key.equals(UTC_TIME)) { options.put(key, null); } else if (key.equals(DEFLATE_COMPRESSION_VALUE)) { if (value != null && value instanceof Integer) { options.put(key, value); } else { throw new UnsupportedOption("EncodingOption '" + key + "' requires value of type Integer"); } } else { throw new UnsupportedOption("EncodingOption '" + key + "' is unknown!"); } }
[ "public", "void", "setOption", "(", "String", "key", ",", "Object", "value", ")", "throws", "UnsupportedOption", "{", "if", "(", "key", ".", "equals", "(", "INCLUDE_COOKIE", ")", ")", "{", "options", ".", "put", "(", "key", ",", "null", ")", ";", "}", ...
Enables given option with value. <p> Note: Some options (e.g. INCLUDE_SCHEMA_ID) will only take effect if the EXI options document is set to encode options in general (see INCLUDE_OPTIONS). </p> @param key referring to a specific option @param value specific option value @throws UnsupportedOption if option is not supported
[ "Enables", "given", "option", "with", "value", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/EncodingOptions.java#L146-L180
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/EncodingOptions.java
EncodingOptions.unsetOption
public boolean unsetOption(String key) { // we do have null values --> check for key boolean b = options.containsKey(key); options.remove(key); return b; }
java
public boolean unsetOption(String key) { // we do have null values --> check for key boolean b = options.containsKey(key); options.remove(key); return b; }
[ "public", "boolean", "unsetOption", "(", "String", "key", ")", "{", "// we do have null values --> check for key", "boolean", "b", "=", "options", ".", "containsKey", "(", "key", ")", ";", "options", ".", "remove", "(", "key", ")", ";", "return", "b", ";", "...
Disables given option. @param key referring to a specific option @return whether option was set
[ "Disables", "given", "option", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/EncodingOptions.java#L190-L195
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java
PangoolMultipleOutputs.checkNamedOutputName
private static void checkNamedOutputName(JobContext job, String namedOutput, boolean alreadyDefined) { validateOutputName(namedOutput); List<String> definedChannels = getNamedOutputsList(job); if(alreadyDefined && definedChannels.contains(namedOutput)) { throw new IllegalArgumentException("Named output '" + namedOutput + "' already alreadyDefined"); } else if(!alreadyDefined && !definedChannels.contains(namedOutput)) { throw new IllegalArgumentException("Named output '" + namedOutput + "' not defined"); } }
java
private static void checkNamedOutputName(JobContext job, String namedOutput, boolean alreadyDefined) { validateOutputName(namedOutput); List<String> definedChannels = getNamedOutputsList(job); if(alreadyDefined && definedChannels.contains(namedOutput)) { throw new IllegalArgumentException("Named output '" + namedOutput + "' already alreadyDefined"); } else if(!alreadyDefined && !definedChannels.contains(namedOutput)) { throw new IllegalArgumentException("Named output '" + namedOutput + "' not defined"); } }
[ "private", "static", "void", "checkNamedOutputName", "(", "JobContext", "job", ",", "String", "namedOutput", ",", "boolean", "alreadyDefined", ")", "{", "validateOutputName", "(", "namedOutput", ")", ";", "List", "<", "String", ">", "definedChannels", "=", "getNam...
Checks if a named output name is valid. @param namedOutput named output Name @throws IllegalArgumentException if the output name is not valid.
[ "Checks", "if", "a", "named", "output", "name", "is", "valid", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java#L134-L142
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java
PangoolMultipleOutputs.getDefaultNamedOutputFormatInstanceFile
private static String getDefaultNamedOutputFormatInstanceFile(JobContext job) { return job.getConfiguration().get(DEFAULT_MO_PREFIX + FORMAT_INSTANCE_FILE, null); }
java
private static String getDefaultNamedOutputFormatInstanceFile(JobContext job) { return job.getConfiguration().get(DEFAULT_MO_PREFIX + FORMAT_INSTANCE_FILE, null); }
[ "private", "static", "String", "getDefaultNamedOutputFormatInstanceFile", "(", "JobContext", "job", ")", "{", "return", "job", ".", "getConfiguration", "(", ")", ".", "get", "(", "DEFAULT_MO_PREFIX", "+", "FORMAT_INSTANCE_FILE", ",", "null", ")", ";", "}" ]
Returns the DEFAULT named output OutputFormat.
[ "Returns", "the", "DEFAULT", "named", "output", "OutputFormat", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java#L182-L184
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java
PangoolMultipleOutputs.getDefaultNamedOutputKeyClass
private static Class<?> getDefaultNamedOutputKeyClass(JobContext job) { return job.getConfiguration().getClass(DEFAULT_MO_PREFIX + KEY, null, Object.class); }
java
private static Class<?> getDefaultNamedOutputKeyClass(JobContext job) { return job.getConfiguration().getClass(DEFAULT_MO_PREFIX + KEY, null, Object.class); }
[ "private", "static", "Class", "<", "?", ">", "getDefaultNamedOutputKeyClass", "(", "JobContext", "job", ")", "{", "return", "job", ".", "getConfiguration", "(", ")", ".", "getClass", "(", "DEFAULT_MO_PREFIX", "+", "KEY", ",", "null", ",", "Object", ".", "cla...
Returns the DEFAULT key class for a named output.
[ "Returns", "the", "DEFAULT", "key", "class", "for", "a", "named", "output", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java#L187-L189
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java
PangoolMultipleOutputs.getDefaultNamedOutputValueClass
private static Class<?> getDefaultNamedOutputValueClass(JobContext job) { return job.getConfiguration().getClass(DEFAULT_MO_PREFIX + VALUE, null, Object.class); }
java
private static Class<?> getDefaultNamedOutputValueClass(JobContext job) { return job.getConfiguration().getClass(DEFAULT_MO_PREFIX + VALUE, null, Object.class); }
[ "private", "static", "Class", "<", "?", ">", "getDefaultNamedOutputValueClass", "(", "JobContext", "job", ")", "{", "return", "job", ".", "getConfiguration", "(", ")", ".", "getClass", "(", "DEFAULT_MO_PREFIX", "+", "VALUE", ",", "null", ",", "Object", ".", ...
Returns the DEFAULT value class for a named output.
[ "Returns", "the", "DEFAULT", "value", "class", "for", "a", "named", "output", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java#L192-L194
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java
PangoolMultipleOutputs.addNamedOutput
public static String addNamedOutput(Job job, String namedOutput, OutputFormat outputFormat, Class<?> keyClass, Class<?> valueClass) throws FileNotFoundException, IOException, URISyntaxException { checkNamedOutputName(job, namedOutput, true); Configuration conf = job.getConfiguration(); String uniqueName = UUID.randomUUID().toString() + '.' + "out-format.dat"; InstancesDistributor.distribute(outputFormat, uniqueName, conf); conf.set(MULTIPLE_OUTPUTS, conf.get(MULTIPLE_OUTPUTS, "") + " " + namedOutput); conf.set(MO_PREFIX + namedOutput + FORMAT_INSTANCE_FILE, uniqueName); conf.setClass(MO_PREFIX + namedOutput + KEY, keyClass, Object.class); conf.setClass(MO_PREFIX + namedOutput + VALUE, valueClass, Object.class); return uniqueName; }
java
public static String addNamedOutput(Job job, String namedOutput, OutputFormat outputFormat, Class<?> keyClass, Class<?> valueClass) throws FileNotFoundException, IOException, URISyntaxException { checkNamedOutputName(job, namedOutput, true); Configuration conf = job.getConfiguration(); String uniqueName = UUID.randomUUID().toString() + '.' + "out-format.dat"; InstancesDistributor.distribute(outputFormat, uniqueName, conf); conf.set(MULTIPLE_OUTPUTS, conf.get(MULTIPLE_OUTPUTS, "") + " " + namedOutput); conf.set(MO_PREFIX + namedOutput + FORMAT_INSTANCE_FILE, uniqueName); conf.setClass(MO_PREFIX + namedOutput + KEY, keyClass, Object.class); conf.setClass(MO_PREFIX + namedOutput + VALUE, valueClass, Object.class); return uniqueName; }
[ "public", "static", "String", "addNamedOutput", "(", "Job", "job", ",", "String", "namedOutput", ",", "OutputFormat", "outputFormat", ",", "Class", "<", "?", ">", "keyClass", ",", "Class", "<", "?", ">", "valueClass", ")", "throws", "FileNotFoundException", ",...
Adds a named output for the job. Returns the instance file that has been created.
[ "Adds", "a", "named", "output", "for", "the", "job", ".", "Returns", "the", "instance", "file", "that", "has", "been", "created", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java#L199-L211
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java
PangoolMultipleOutputs.write
@SuppressWarnings("unchecked") public <K, V> void write(String namedOutput, K key, V value, String baseOutputPath) throws IOException, InterruptedException { checkNamedOutputName(context, namedOutput, false); checkBaseOutputPath(baseOutputPath); if(!namedOutputs.contains(namedOutput)) { throw new IllegalArgumentException("Undefined named output '" + namedOutput + "'"); } getRecordWriter(baseOutputPath).write(key, value); }
java
@SuppressWarnings("unchecked") public <K, V> void write(String namedOutput, K key, V value, String baseOutputPath) throws IOException, InterruptedException { checkNamedOutputName(context, namedOutput, false); checkBaseOutputPath(baseOutputPath); if(!namedOutputs.contains(namedOutput)) { throw new IllegalArgumentException("Undefined named output '" + namedOutput + "'"); } getRecordWriter(baseOutputPath).write(key, value); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "K", ",", "V", ">", "void", "write", "(", "String", "namedOutput", ",", "K", "key", ",", "V", "value", ",", "String", "baseOutputPath", ")", "throws", "IOException", ",", "InterruptedExceptio...
Write key and value to baseOutputPath using the namedOutput. @param namedOutput the named output name @param key the key @param value the value @param baseOutputPath base-output path to write the record to. Note: Framework will generate unique filename for the baseOutputPath
[ "Write", "key", "and", "value", "to", "baseOutputPath", "using", "the", "namedOutput", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java#L385-L394
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java
PangoolMultipleOutputs.close
public void close() throws IOException, InterruptedException { for(OutputContext outputContext : this.outputContexts.values()) { outputContext.recordWriter.close(outputContext.taskAttemptContext); outputContext.outputCommitter.commitTask(outputContext.taskAttemptContext); // This is a trick for Hadoop 2.0 where there is extra business logic in commitJob() JobContext jContext; try { jContext = JobContextFactory.get(outputContext.taskAttemptContext.getConfiguration(), new JobID()); } catch(Exception e) { throw new IOException(e); } try { Class cl = Class.forName(OutputCommitter.class.getName()); Method method = cl.getMethod("commitJob", Class.forName(JobContext.class.getName())); if(method != null) { method.invoke(outputContext.outputCommitter, jContext); } } catch(Exception e) { // Hadoop 2.0 : do nothing // we need to call commitJob as a trick, but the trick itself may throw an IOException. // it doesn't mean that something went wrong. // If there was something really wrong it would have failed before. } outputContext.outputCommitter.cleanupJob(outputContext.jobContext); } }
java
public void close() throws IOException, InterruptedException { for(OutputContext outputContext : this.outputContexts.values()) { outputContext.recordWriter.close(outputContext.taskAttemptContext); outputContext.outputCommitter.commitTask(outputContext.taskAttemptContext); // This is a trick for Hadoop 2.0 where there is extra business logic in commitJob() JobContext jContext; try { jContext = JobContextFactory.get(outputContext.taskAttemptContext.getConfiguration(), new JobID()); } catch(Exception e) { throw new IOException(e); } try { Class cl = Class.forName(OutputCommitter.class.getName()); Method method = cl.getMethod("commitJob", Class.forName(JobContext.class.getName())); if(method != null) { method.invoke(outputContext.outputCommitter, jContext); } } catch(Exception e) { // Hadoop 2.0 : do nothing // we need to call commitJob as a trick, but the trick itself may throw an IOException. // it doesn't mean that something went wrong. // If there was something really wrong it would have failed before. } outputContext.outputCommitter.cleanupJob(outputContext.jobContext); } }
[ "public", "void", "close", "(", ")", "throws", "IOException", ",", "InterruptedException", "{", "for", "(", "OutputContext", "outputContext", ":", "this", ".", "outputContexts", ".", "values", "(", ")", ")", "{", "outputContext", ".", "recordWriter", ".", "clo...
Closes all the opened outputs. This should be called from cleanup method of map/reduce task. If overridden subclasses must invoke <code>super.close()</code> at the end of their <code>close()</code>
[ "Closes", "all", "the", "opened", "outputs", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/PangoolMultipleOutputs.java#L501-L527
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/coder/AbstractEXIBodyEncoder.java
AbstractEXIBodyEncoder.getDatatypeWhiteSpace
private WhiteSpace getDatatypeWhiteSpace() { Grammar currGr = this.getCurrentGrammar(); if (currGr.isSchemaInformed() && currGr.getNumberOfEvents() > 0) { Production prod = currGr.getProduction(0); if (prod.getEvent().getEventType() == EventType.CHARACTERS) { Characters ch = (Characters) prod.getEvent(); return ch.getDatatype().getWhiteSpace(); } } return null; }
java
private WhiteSpace getDatatypeWhiteSpace() { Grammar currGr = this.getCurrentGrammar(); if (currGr.isSchemaInformed() && currGr.getNumberOfEvents() > 0) { Production prod = currGr.getProduction(0); if (prod.getEvent().getEventType() == EventType.CHARACTERS) { Characters ch = (Characters) prod.getEvent(); return ch.getDatatype().getWhiteSpace(); } } return null; }
[ "private", "WhiteSpace", "getDatatypeWhiteSpace", "(", ")", "{", "Grammar", "currGr", "=", "this", ".", "getCurrentGrammar", "(", ")", ";", "if", "(", "currGr", ".", "isSchemaInformed", "(", ")", "&&", "currGr", ".", "getNumberOfEvents", "(", ")", ">", "0", ...
returns null if no CH datatype is available or schema-less
[ "returns", "null", "if", "no", "CH", "datatype", "is", "available", "or", "schema", "-", "less" ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/coder/AbstractEXIBodyEncoder.java#L1353-L1364
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/BitInputStream.java
BitInputStream.skip
public void skip(long n) throws IOException { if (capacity == 0) { // aligned while (n != 0) { n -= istream.skip(n); } } else { // not aligned, grrr for (int i = 0; i < n; n++) { readBits(8); } } }
java
public void skip(long n) throws IOException { if (capacity == 0) { // aligned while (n != 0) { n -= istream.skip(n); } } else { // not aligned, grrr for (int i = 0; i < n; n++) { readBits(8); } } }
[ "public", "void", "skip", "(", "long", "n", ")", "throws", "IOException", "{", "if", "(", "capacity", "==", "0", ")", "{", "// aligned", "while", "(", "n", "!=", "0", ")", "{", "n", "-=", "istream", ".", "skip", "(", "n", ")", ";", "}", "}", "e...
Skip n bytes @param n bytes @throws IOException IO exception
[ "Skip", "n", "bytes" ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/BitInputStream.java#L132-L144
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/BitInputStream.java
BitInputStream.readBits
public int readBits(int n) throws IOException { assert (n > 0); int result; if (n <= capacity) { // buffer already holds all necessary bits result = (buffer >> (capacity -= n)) & (0xff >> (BUFFER_CAPACITY - n)); } else if (capacity == 0 && n == BUFFER_CAPACITY) { // possible to read direct byte, nothing else to do result = readDirectByte(); } else { // get as many bits from buffer as possible result = buffer & (0xff >> (BUFFER_CAPACITY - capacity)); n -= capacity; capacity = 0; // possibly read whole bytes while (n > 7) { if (capacity == 0) { readBuffer(); } result = (result << BUFFER_CAPACITY) | buffer; n -= BUFFER_CAPACITY; capacity = 0; } // read the rest of the bits if (n > 0) { if (capacity == 0) { readBuffer(); } result = (result << n) | (buffer >> (capacity = (BUFFER_CAPACITY - n))); } } return result; }
java
public int readBits(int n) throws IOException { assert (n > 0); int result; if (n <= capacity) { // buffer already holds all necessary bits result = (buffer >> (capacity -= n)) & (0xff >> (BUFFER_CAPACITY - n)); } else if (capacity == 0 && n == BUFFER_CAPACITY) { // possible to read direct byte, nothing else to do result = readDirectByte(); } else { // get as many bits from buffer as possible result = buffer & (0xff >> (BUFFER_CAPACITY - capacity)); n -= capacity; capacity = 0; // possibly read whole bytes while (n > 7) { if (capacity == 0) { readBuffer(); } result = (result << BUFFER_CAPACITY) | buffer; n -= BUFFER_CAPACITY; capacity = 0; } // read the rest of the bits if (n > 0) { if (capacity == 0) { readBuffer(); } result = (result << n) | (buffer >> (capacity = (BUFFER_CAPACITY - n))); } } return result; }
[ "public", "int", "readBits", "(", "int", "n", ")", "throws", "IOException", "{", "assert", "(", "n", ">", "0", ")", ";", "int", "result", ";", "if", "(", "n", "<=", "capacity", ")", "{", "// buffer already holds all necessary bits", "result", "=", "(", "...
Read the next n bits and return the result as an integer. @param n The number of bits in the range [1,32]. @throws IOException IO exception @return nbit value
[ "Read", "the", "next", "n", "bits", "and", "return", "the", "result", "as", "an", "integer", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/BitInputStream.java#L170-L208
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/serialization/SimpleTupleDeserializer.java
SimpleTupleDeserializer.readFields
public void readFields(ITuple tuple, Deserializer[] customDeserializers) throws IOException { readFields(tuple, readSchema, customDeserializers); }
java
public void readFields(ITuple tuple, Deserializer[] customDeserializers) throws IOException { readFields(tuple, readSchema, customDeserializers); }
[ "public", "void", "readFields", "(", "ITuple", "tuple", ",", "Deserializer", "[", "]", "customDeserializers", ")", "throws", "IOException", "{", "readFields", "(", "tuple", ",", "readSchema", ",", "customDeserializers", ")", ";", "}" ]
Read fields using the specified "readSchema" in the constructor.
[ "Read", "fields", "using", "the", "specified", "readSchema", "in", "the", "constructor", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/serialization/SimpleTupleDeserializer.java#L138-L140
train
toddfast/mutagen-cassandra
src/main/java/com/toddfast/mutagen/cassandra/AbstractCassandraMutation.java
AbstractCassandraMutation.mutate
@Override public final void mutate(Context context) throws MutagenException { // Perform the mutation performMutation(context); int version=getResultingState().getID(); String change=getChangeSummary(); if (change==null) { change=""; } String changeHash=md5String(change); // The straightforward way, without locking try { MutationBatch batch=getKeyspace().prepareMutationBatch(); batch .withRow(CassandraSubject.VERSION_CF, CassandraSubject.ROW_KEY) .putColumn(CassandraSubject.VERSION_COLUMN,version); batch .withRow(CassandraSubject.VERSION_CF, String.format("%08d",version)) .putColumn("change",change) .putColumn("hash",changeHash); batch.execute(); } catch (ConnectionException e) { throw new MutagenException("Could not update \"schema_version\" "+ "column family to state "+version+ "; schema is now out of sync with recorded version",e); } // TAF: Why does this fail with a StaleLockException? Do we need to use a // separate lock table? // // Attempt to acquire a lock to update the version // ColumnPrefixDistributedRowLock<String> lock = // new ColumnPrefixDistributedRowLock<String>(getKeyspace(), // CassandraSubject.VERSION_CF,CassandraSubject.VERSION_COLUMN) // .withBackoff(new BoundedExponentialBackoff(250, 10000, 10)) // .expireLockAfter(1, TimeUnit.SECONDS) //// .failOnStaleLock(false); // .failOnStaleLock(true); // // try { // lock.acquire(); // } // catch (StaleLockException e) { // // Won't happen // throw new MutagenException("Could not update "+ // "\"schema_version\" column family to state "+version+ // " because lock expired",e); // } // catch (BusyLockException e) { // throw new MutagenException("Could not update "+ // "\"schema_version\" column family to state "+version+ // " because another client is updating the recorded version",e); // } // catch (Exception e) { // if (e instanceof RuntimeException) { // throw (RuntimeException)e; // } // else { // throw new MutagenException("Could not update "+ // "\"schema_version\" column family to state "+version+ // " because a write lock could not be obtained",e); // } // } // finally { // try { // MutationBatch batch=getKeyspace().prepareMutationBatch(); // batch.withRow(CassandraSubject.VERSION_CF, // CassandraSubject.ROW_KEY) // .putColumn(CassandraSubject.VERSION_COLUMN,version); // // // Release and update // lock.releaseWithMutation(batch); // } // catch (Exception e) { // if (e instanceof RuntimeException) { // throw (RuntimeException)e; // } // else { // throw new MutagenException("Could not update "+ // "\"schema_version\" column family to state "+version+ // "; schema is now out of sync with recorded version",e); // } // } // } }
java
@Override public final void mutate(Context context) throws MutagenException { // Perform the mutation performMutation(context); int version=getResultingState().getID(); String change=getChangeSummary(); if (change==null) { change=""; } String changeHash=md5String(change); // The straightforward way, without locking try { MutationBatch batch=getKeyspace().prepareMutationBatch(); batch .withRow(CassandraSubject.VERSION_CF, CassandraSubject.ROW_KEY) .putColumn(CassandraSubject.VERSION_COLUMN,version); batch .withRow(CassandraSubject.VERSION_CF, String.format("%08d",version)) .putColumn("change",change) .putColumn("hash",changeHash); batch.execute(); } catch (ConnectionException e) { throw new MutagenException("Could not update \"schema_version\" "+ "column family to state "+version+ "; schema is now out of sync with recorded version",e); } // TAF: Why does this fail with a StaleLockException? Do we need to use a // separate lock table? // // Attempt to acquire a lock to update the version // ColumnPrefixDistributedRowLock<String> lock = // new ColumnPrefixDistributedRowLock<String>(getKeyspace(), // CassandraSubject.VERSION_CF,CassandraSubject.VERSION_COLUMN) // .withBackoff(new BoundedExponentialBackoff(250, 10000, 10)) // .expireLockAfter(1, TimeUnit.SECONDS) //// .failOnStaleLock(false); // .failOnStaleLock(true); // // try { // lock.acquire(); // } // catch (StaleLockException e) { // // Won't happen // throw new MutagenException("Could not update "+ // "\"schema_version\" column family to state "+version+ // " because lock expired",e); // } // catch (BusyLockException e) { // throw new MutagenException("Could not update "+ // "\"schema_version\" column family to state "+version+ // " because another client is updating the recorded version",e); // } // catch (Exception e) { // if (e instanceof RuntimeException) { // throw (RuntimeException)e; // } // else { // throw new MutagenException("Could not update "+ // "\"schema_version\" column family to state "+version+ // " because a write lock could not be obtained",e); // } // } // finally { // try { // MutationBatch batch=getKeyspace().prepareMutationBatch(); // batch.withRow(CassandraSubject.VERSION_CF, // CassandraSubject.ROW_KEY) // .putColumn(CassandraSubject.VERSION_COLUMN,version); // // // Release and update // lock.releaseWithMutation(batch); // } // catch (Exception e) { // if (e instanceof RuntimeException) { // throw (RuntimeException)e; // } // else { // throw new MutagenException("Could not update "+ // "\"schema_version\" column family to state "+version+ // "; schema is now out of sync with recorded version",e); // } // } // } }
[ "@", "Override", "public", "final", "void", "mutate", "(", "Context", "context", ")", "throws", "MutagenException", "{", "// Perform the mutation", "performMutation", "(", "context", ")", ";", "int", "version", "=", "getResultingState", "(", ")", ".", "getID", "...
Performs the actual mutation and then updates the recorded schema version
[ "Performs", "the", "actual", "mutation", "and", "then", "updates", "the", "recorded", "schema", "version" ]
97da163d045a03763c513fbd5455330e0af48acd
https://github.com/toddfast/mutagen-cassandra/blob/97da163d045a03763c513fbd5455330e0af48acd/src/main/java/com/toddfast/mutagen/cassandra/AbstractCassandraMutation.java#L117-L212
train
toddfast/mutagen-cassandra
src/main/java/com/toddfast/mutagen/cassandra/AbstractCassandraMutation.java
AbstractCassandraMutation.toHex
public static String toHex(byte[] bytes) { StringBuilder hexString=new StringBuilder(); for (int i=0; i<bytes.length; i++) { String hex=Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); }
java
public static String toHex(byte[] bytes) { StringBuilder hexString=new StringBuilder(); for (int i=0; i<bytes.length; i++) { String hex=Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); }
[ "public", "static", "String", "toHex", "(", "byte", "[", "]", "bytes", ")", "{", "StringBuilder", "hexString", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "++", ")",...
Encode a byte array as a hexadecimal string @param bytes @return
[ "Encode", "a", "byte", "array", "as", "a", "hexadecimal", "string" ]
97da163d045a03763c513fbd5455330e0af48acd
https://github.com/toddfast/mutagen-cassandra/blob/97da163d045a03763c513fbd5455330e0af48acd/src/main/java/com/toddfast/mutagen/cassandra/AbstractCassandraMutation.java#L262-L275
train
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/UndeployCommand.java
UndeployCommand.getDeployed
public static List<String> getDeployed(String url, String token) throws Exception { List<String> deployed = new ArrayList<String> (); HttpClient client = httpClient(); HttpGet get = new HttpGet(url + "/system/deployment/list"); addAuthHeader(token, get); HttpResponse resp = client.execute(get); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { List<String> respList = new Gson().fromJson(EntityUtils.toString(resp.getEntity()), new TypeToken<List<String>>() {}.getType()); if(respList != null) { deployed.addAll(respList); } } return deployed; }
java
public static List<String> getDeployed(String url, String token) throws Exception { List<String> deployed = new ArrayList<String> (); HttpClient client = httpClient(); HttpGet get = new HttpGet(url + "/system/deployment/list"); addAuthHeader(token, get); HttpResponse resp = client.execute(get); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { List<String> respList = new Gson().fromJson(EntityUtils.toString(resp.getEntity()), new TypeToken<List<String>>() {}.getType()); if(respList != null) { deployed.addAll(respList); } } return deployed; }
[ "public", "static", "List", "<", "String", ">", "getDeployed", "(", "String", "url", ",", "String", "token", ")", "throws", "Exception", "{", "List", "<", "String", ">", "deployed", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "HttpClient"...
Retrieves a list of Cadmium wars that are deployed. @param url The uri to a Cadmium deployer war. @param token The Github API token used for authentication. @return @throws Exception
[ "Retrieves", "a", "list", "of", "Cadmium", "wars", "that", "are", "deployed", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/UndeployCommand.java#L122-L140
train
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/UndeployCommand.java
UndeployCommand.undeploy
public static void undeploy(String url, String warName, String token) throws Exception { HttpClient client = httpClient(); HttpPost del = new HttpPost(url + "/system/undeploy"); addAuthHeader(token, del); del.addHeader("Content-Type", MediaType.APPLICATION_JSON); UndeployRequest req = new UndeployRequest(); req.setWarName(warName); del.setEntity(new StringEntity(new Gson().toJson(req), "UTF-8")); HttpResponse resp = client.execute(del); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String respStr = EntityUtils.toString(resp.getEntity()); if(!respStr.equals("ok")) { throw new Exception("Failed to undeploy "+warName); } else { System.out.println("Undeployment of "+warName+" successful"); } } else { System.err.println("Failed to undeploy "+warName); System.err.println(resp.getStatusLine().getStatusCode()+": "+EntityUtils.toString(resp.getEntity())); } }
java
public static void undeploy(String url, String warName, String token) throws Exception { HttpClient client = httpClient(); HttpPost del = new HttpPost(url + "/system/undeploy"); addAuthHeader(token, del); del.addHeader("Content-Type", MediaType.APPLICATION_JSON); UndeployRequest req = new UndeployRequest(); req.setWarName(warName); del.setEntity(new StringEntity(new Gson().toJson(req), "UTF-8")); HttpResponse resp = client.execute(del); if(resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String respStr = EntityUtils.toString(resp.getEntity()); if(!respStr.equals("ok")) { throw new Exception("Failed to undeploy "+warName); } else { System.out.println("Undeployment of "+warName+" successful"); } } else { System.err.println("Failed to undeploy "+warName); System.err.println(resp.getStatusLine().getStatusCode()+": "+EntityUtils.toString(resp.getEntity())); } }
[ "public", "static", "void", "undeploy", "(", "String", "url", ",", "String", "warName", ",", "String", "token", ")", "throws", "Exception", "{", "HttpClient", "client", "=", "httpClient", "(", ")", ";", "HttpPost", "del", "=", "new", "HttpPost", "(", "url"...
Sends the undeploy command to a Cadmium-Deployer war. @param url The uri to a Cadmium-Deployer war. @param warName The war to undeploy. @param token The Github API token used for authentication. @throws Exception
[ "Sends", "the", "undeploy", "command", "to", "a", "Cadmium", "-", "Deployer", "war", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/UndeployCommand.java#L150-L175
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/BitField.java
BitField.set
public void set(int bit, boolean value) { int bite = byteForBit(bit); ensureSpace(bite + 1); int bitOnByte = bitOnByte(bit, bite); if (value) { bits[bite] = byteBitSet(bitOnByte, bits[bite]); } else { bits[bite] = byteBitUnset(bitOnByte, bits[bite]); } }
java
public void set(int bit, boolean value) { int bite = byteForBit(bit); ensureSpace(bite + 1); int bitOnByte = bitOnByte(bit, bite); if (value) { bits[bite] = byteBitSet(bitOnByte, bits[bite]); } else { bits[bite] = byteBitUnset(bitOnByte, bits[bite]); } }
[ "public", "void", "set", "(", "int", "bit", ",", "boolean", "value", ")", "{", "int", "bite", "=", "byteForBit", "(", "bit", ")", ";", "ensureSpace", "(", "bite", "+", "1", ")", ";", "int", "bitOnByte", "=", "bitOnByte", "(", "bit", ",", "bite", ")...
Sets or unsets a bit. The smaller allowed bit is 0
[ "Sets", "or", "unsets", "a", "bit", ".", "The", "smaller", "allowed", "bit", "is", "0" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/BitField.java#L56-L65
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/BitField.java
BitField.isSet
public boolean isSet(int bit) { int bite = byteForBit(bit); if (bite >= bits.length || bits.length == 0) { return false; } int bitOnByte = bitOnByte(bit, bite); return ((1 << bitOnByte) & bits[bite]) != 0; }
java
public boolean isSet(int bit) { int bite = byteForBit(bit); if (bite >= bits.length || bits.length == 0) { return false; } int bitOnByte = bitOnByte(bit, bite); return ((1 << bitOnByte) & bits[bite]) != 0; }
[ "public", "boolean", "isSet", "(", "int", "bit", ")", "{", "int", "bite", "=", "byteForBit", "(", "bit", ")", ";", "if", "(", "bite", ">=", "bits", ".", "length", "||", "bits", ".", "length", "==", "0", ")", "{", "return", "false", ";", "}", "int...
Returns the value of a given bit. False is returned for unexisting bits.
[ "Returns", "the", "value", "of", "a", "given", "bit", ".", "False", "is", "returned", "for", "unexisting", "bits", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/BitField.java#L84-L91
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/BitField.java
BitField.ser
public void ser(DataOutput out) throws IOException { if (bits.length == 0) { out.writeByte(0); return; } // removing trailing empty bytes. int bytesToWrite; for (bytesToWrite = bits.length; bytesToWrite > 1 && bits[bytesToWrite - 1] == 0; bytesToWrite--) ; // Writing first bytes, with the rightmost bit set for (int i = 0; i < (bytesToWrite - 1); i++) { out.writeByte((bits[i] | 1)); } // Writing the last byte, with the rightmost bit unset out.writeByte((bits[bytesToWrite - 1] & ~1)); }
java
public void ser(DataOutput out) throws IOException { if (bits.length == 0) { out.writeByte(0); return; } // removing trailing empty bytes. int bytesToWrite; for (bytesToWrite = bits.length; bytesToWrite > 1 && bits[bytesToWrite - 1] == 0; bytesToWrite--) ; // Writing first bytes, with the rightmost bit set for (int i = 0; i < (bytesToWrite - 1); i++) { out.writeByte((bits[i] | 1)); } // Writing the last byte, with the rightmost bit unset out.writeByte((bits[bytesToWrite - 1] & ~1)); }
[ "public", "void", "ser", "(", "DataOutput", "out", ")", "throws", "IOException", "{", "if", "(", "bits", ".", "length", "==", "0", ")", "{", "out", ".", "writeByte", "(", "0", ")", ";", "return", ";", "}", "// removing trailing empty bytes.", "int", "byt...
Serializes the bit field to the data output. It uses one byte per each 7 bits. If the rightmost bit of the read byte is set, that means that there are more bytes to consume. The latest byte has the rightmost bit unset.
[ "Serializes", "the", "bit", "field", "to", "the", "data", "output", ".", "It", "uses", "one", "byte", "per", "each", "7", "bits", ".", "If", "the", "rightmost", "bit", "of", "the", "read", "byte", "is", "set", "that", "means", "that", "there", "are", ...
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/BitField.java#L98-L112
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/BitField.java
BitField.deser
public int deser(byte[] bytes, int start) throws IOException { int idx = 0; byte current; do { current = bytes[start+idx]; ensureSpace(idx + 1); // The last bit must be clear bits[idx] = (byte) (current & ~1); idx++; } while ((current & 1) != 0); // clear the remaining bytes. for (int i = idx; i < bits.length; i++) { bits[i] = 0; } return idx; }
java
public int deser(byte[] bytes, int start) throws IOException { int idx = 0; byte current; do { current = bytes[start+idx]; ensureSpace(idx + 1); // The last bit must be clear bits[idx] = (byte) (current & ~1); idx++; } while ((current & 1) != 0); // clear the remaining bytes. for (int i = idx; i < bits.length; i++) { bits[i] = 0; } return idx; }
[ "public", "int", "deser", "(", "byte", "[", "]", "bytes", ",", "int", "start", ")", "throws", "IOException", "{", "int", "idx", "=", "0", ";", "byte", "current", ";", "do", "{", "current", "=", "bytes", "[", "start", "+", "idx", "]", ";", "ensureSp...
Deserialize a BitField serialized from a byte array. Return the number of bytes consumed.
[ "Deserialize", "a", "BitField", "serialized", "from", "a", "byte", "array", ".", "Return", "the", "number", "of", "bytes", "consumed", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/BitField.java#L139-L154
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/BitField.java
BitField.ensureSpace
protected void ensureSpace(int bytes) { if (bits.length < bytes) { bits = Arrays.copyOf(bits, bytes); } }
java
protected void ensureSpace(int bytes) { if (bits.length < bytes) { bits = Arrays.copyOf(bits, bytes); } }
[ "protected", "void", "ensureSpace", "(", "int", "bytes", ")", "{", "if", "(", "bits", ".", "length", "<", "bytes", ")", "{", "bits", "=", "Arrays", ".", "copyOf", "(", "bits", ",", "bytes", ")", ";", "}", "}" ]
Ensures a minimum size for the backing byte array
[ "Ensures", "a", "minimum", "size", "for", "the", "backing", "byte", "array" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/BitField.java#L179-L183
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/impl/YamlLenientConstructor.java
YamlLenientConstructor.addTypeDescription
@Override public TypeDescription addTypeDescription(TypeDescription definition) { if(definition != null && definition.getTag() != null) { tagsDefined.add(definition.getTag()); } return super.addTypeDescription(definition); }
java
@Override public TypeDescription addTypeDescription(TypeDescription definition) { if(definition != null && definition.getTag() != null) { tagsDefined.add(definition.getTag()); } return super.addTypeDescription(definition); }
[ "@", "Override", "public", "TypeDescription", "addTypeDescription", "(", "TypeDescription", "definition", ")", "{", "if", "(", "definition", "!=", "null", "&&", "definition", ".", "getTag", "(", ")", "!=", "null", ")", "{", "tagsDefined", ".", "add", "(", "d...
Overridden to capture what tags are defined specially.
[ "Overridden", "to", "capture", "what", "tags", "are", "defined", "specially", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/impl/YamlLenientConstructor.java#L57-L63
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/impl/YamlLenientConstructor.java
YamlLenientConstructor.getConstructor
@Override protected Construct getConstructor(Node node) { Construct construct = super.getConstructor(node); logger.trace("getting constructor for node {} Tag {} = {}", new Object[] {node, node.getTag(), construct}); if(construct instanceof ConstructYamlObject && !tagsDefined.contains(node.getTag())) { try { node.getTag().getClassName(); } catch(YAMLException e) { node.setUseClassConstructor(true); String value = null; if(node.getNodeId() == NodeId.scalar) { value = ((ScalarNode)node).getValue(); } node.setTag(resolver.resolve(node.getNodeId(), value, true)); construct = super.getConstructor(node); try { resolveType(node); } catch (ClassNotFoundException e1) { logger.debug("Could not find class.", e1); } } } logger.trace("returning constructor for node {} type {} Tag {} = {}", new Object[] {node, node.getType(), node.getTag(), construct}); return construct; }
java
@Override protected Construct getConstructor(Node node) { Construct construct = super.getConstructor(node); logger.trace("getting constructor for node {} Tag {} = {}", new Object[] {node, node.getTag(), construct}); if(construct instanceof ConstructYamlObject && !tagsDefined.contains(node.getTag())) { try { node.getTag().getClassName(); } catch(YAMLException e) { node.setUseClassConstructor(true); String value = null; if(node.getNodeId() == NodeId.scalar) { value = ((ScalarNode)node).getValue(); } node.setTag(resolver.resolve(node.getNodeId(), value, true)); construct = super.getConstructor(node); try { resolveType(node); } catch (ClassNotFoundException e1) { logger.debug("Could not find class.", e1); } } } logger.trace("returning constructor for node {} type {} Tag {} = {}", new Object[] {node, node.getType(), node.getTag(), construct}); return construct; }
[ "@", "Override", "protected", "Construct", "getConstructor", "(", "Node", "node", ")", "{", "Construct", "construct", "=", "super", ".", "getConstructor", "(", "node", ")", ";", "logger", ".", "trace", "(", "\"getting constructor for node {} Tag {} = {}\"", ",", "...
Overridden to fetch constructor even if tag is not mapped.
[ "Overridden", "to", "fetch", "constructor", "even", "if", "tag", "is", "not", "mapped", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/impl/YamlLenientConstructor.java#L68-L93
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/config/impl/YamlLenientConstructor.java
YamlLenientConstructor.resolveType
private void resolveType(Node node) throws ClassNotFoundException { String typeName = node.getTag().getClassName(); if(typeName.equals("int")) { node.setType(Integer.TYPE); } else if(typeName.equals("float")) { node.setType(Float.TYPE); } else if(typeName.equals("double")) { node.setType(Double.TYPE); } else if(typeName.equals("bool")) { node.setType(Boolean.TYPE); } else if(typeName.equals("date")) { node.setType(Date.class); } else if(typeName.equals("seq")) { node.setType(List.class); } else if(typeName.equals("str")) { node.setType(String.class); } else if(typeName.equals("map")) { node.setType(Map.class); } else { node.setType(getClassForName(node.getTag().getClassName())); } }
java
private void resolveType(Node node) throws ClassNotFoundException { String typeName = node.getTag().getClassName(); if(typeName.equals("int")) { node.setType(Integer.TYPE); } else if(typeName.equals("float")) { node.setType(Float.TYPE); } else if(typeName.equals("double")) { node.setType(Double.TYPE); } else if(typeName.equals("bool")) { node.setType(Boolean.TYPE); } else if(typeName.equals("date")) { node.setType(Date.class); } else if(typeName.equals("seq")) { node.setType(List.class); } else if(typeName.equals("str")) { node.setType(String.class); } else if(typeName.equals("map")) { node.setType(Map.class); } else { node.setType(getClassForName(node.getTag().getClassName())); } }
[ "private", "void", "resolveType", "(", "Node", "node", ")", "throws", "ClassNotFoundException", "{", "String", "typeName", "=", "node", ".", "getTag", "(", ")", ".", "getClassName", "(", ")", ";", "if", "(", "typeName", ".", "equals", "(", "\"int\"", ")", ...
Resolves the type of a node after the tag gets re-resolved. @param node @throws ClassNotFoundException
[ "Resolves", "the", "type", "of", "a", "node", "after", "the", "tag", "gets", "re", "-", "resolved", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/config/impl/YamlLenientConstructor.java#L101-L122
train
opentable/otj-logging
jetty/src/main/java/com/opentable/logging/jetty/JsonRequestLog.java
JsonRequestLog.getRequestIdFrom
protected UUID getRequestIdFrom(Request request, Response response) { return optUuid(response.getHeader(OTHeaders.REQUEST_ID)); }
java
protected UUID getRequestIdFrom(Request request, Response response) { return optUuid(response.getHeader(OTHeaders.REQUEST_ID)); }
[ "protected", "UUID", "getRequestIdFrom", "(", "Request", "request", ",", "Response", "response", ")", "{", "return", "optUuid", "(", "response", ".", "getHeader", "(", "OTHeaders", ".", "REQUEST_ID", ")", ")", ";", "}" ]
Provides a hook whereby an alternate source can be provided for grabbing the requestId
[ "Provides", "a", "hook", "whereby", "an", "alternate", "source", "can", "be", "provided", "for", "grabbing", "the", "requestId" ]
eaa74c877c4721ddb9af8eb7fe1612166f7ac14d
https://github.com/opentable/otj-logging/blob/eaa74c877c4721ddb9af8eb7fe1612166f7ac14d/jetty/src/main/java/com/opentable/logging/jetty/JsonRequestLog.java#L157-L159
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/util/LogUtils.java
LogUtils.setLogLevel
public static LoggerConfig[] setLogLevel(String loggerName, String level) { if(StringUtils.isBlank(loggerName)) { loggerName = ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME; } LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); log.debug("Setting {} to level {}", loggerName, level); ch.qos.logback.classic.Logger logger = null; try { logger = context.getLogger(loggerName); if(logger != null) { if(level.equals("null") || level.equals("none")) { logger.setLevel(null); } else { logger.setLevel(Level.toLevel(level)); } logger = context.getLogger(loggerName); return new LoggerConfig[] {new LoggerConfig(logger.getName(), logger.getLevel() + "")}; } return new LoggerConfig[] {}; } catch(Throwable t) { log.warn("Failed to change log level for logger "+loggerName+" to level "+level, t); return new LoggerConfig[] {}; } }
java
public static LoggerConfig[] setLogLevel(String loggerName, String level) { if(StringUtils.isBlank(loggerName)) { loggerName = ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME; } LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); log.debug("Setting {} to level {}", loggerName, level); ch.qos.logback.classic.Logger logger = null; try { logger = context.getLogger(loggerName); if(logger != null) { if(level.equals("null") || level.equals("none")) { logger.setLevel(null); } else { logger.setLevel(Level.toLevel(level)); } logger = context.getLogger(loggerName); return new LoggerConfig[] {new LoggerConfig(logger.getName(), logger.getLevel() + "")}; } return new LoggerConfig[] {}; } catch(Throwable t) { log.warn("Failed to change log level for logger "+loggerName+" to level "+level, t); return new LoggerConfig[] {}; } }
[ "public", "static", "LoggerConfig", "[", "]", "setLogLevel", "(", "String", "loggerName", ",", "String", "level", ")", "{", "if", "(", "StringUtils", ".", "isBlank", "(", "loggerName", ")", ")", "{", "loggerName", "=", "ch", ".", "qos", ".", "logback", "...
Updates a logger with a given name to the given level. @param loggerName @param level
[ "Updates", "a", "logger", "with", "a", "given", "name", "to", "the", "given", "level", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/util/LogUtils.java#L77-L100
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/channel/ByteDecoderChannel.java
ByteDecoderChannel.decodeNBitUnsignedInteger
public int decodeNBitUnsignedInteger(int n) throws IOException { assert (n >= 0); int bitsRead = 0; int result = 0; while (bitsRead < n) { // result = (result << 8) | is.read(); result += (decode() << bitsRead); bitsRead += 8; } return result; }
java
public int decodeNBitUnsignedInteger(int n) throws IOException { assert (n >= 0); int bitsRead = 0; int result = 0; while (bitsRead < n) { // result = (result << 8) | is.read(); result += (decode() << bitsRead); bitsRead += 8; } return result; }
[ "public", "int", "decodeNBitUnsignedInteger", "(", "int", "n", ")", "throws", "IOException", "{", "assert", "(", "n", ">=", "0", ")", ";", "int", "bitsRead", "=", "0", ";", "int", "result", "=", "0", ";", "while", "(", "bitsRead", "<", "n", ")", "{",...
Decodes and returns an n-bit unsigned integer using the minimum number of bytes required for n bits.
[ "Decodes", "and", "returns", "an", "n", "-", "bit", "unsigned", "integer", "using", "the", "minimum", "number", "of", "bytes", "required", "for", "n", "bits", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/channel/ByteDecoderChannel.java#L71-L83
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/NamedOutputsInterface.java
NamedOutputsInterface.configureJob
public Set<String> configureJob(Job job) throws FileNotFoundException, IOException, TupleMRException { Set<String> instanceFiles = new HashSet<String>(); for(Output output : getNamedOutputs()) { try { if(output.isDefault) { instanceFiles.add(PangoolMultipleOutputs.setDefaultNamedOutput(job, output.outputFormat, output.keyClass, output.valueClass)); } else { instanceFiles.add(PangoolMultipleOutputs.addNamedOutput(job, output.name, output.outputFormat, output.keyClass, output.valueClass)); } } catch(URISyntaxException e1) { throw new TupleMRException(e1); } for(Map.Entry<String, String> contextKeyValue : output.specificContext.entrySet()) { PangoolMultipleOutputs.addNamedOutputContext(job, output.name, contextKeyValue.getKey(), contextKeyValue.getValue()); } } return instanceFiles; }
java
public Set<String> configureJob(Job job) throws FileNotFoundException, IOException, TupleMRException { Set<String> instanceFiles = new HashSet<String>(); for(Output output : getNamedOutputs()) { try { if(output.isDefault) { instanceFiles.add(PangoolMultipleOutputs.setDefaultNamedOutput(job, output.outputFormat, output.keyClass, output.valueClass)); } else { instanceFiles.add(PangoolMultipleOutputs.addNamedOutput(job, output.name, output.outputFormat, output.keyClass, output.valueClass)); } } catch(URISyntaxException e1) { throw new TupleMRException(e1); } for(Map.Entry<String, String> contextKeyValue : output.specificContext.entrySet()) { PangoolMultipleOutputs.addNamedOutputContext(job, output.name, contextKeyValue.getKey(), contextKeyValue.getValue()); } } return instanceFiles; }
[ "public", "Set", "<", "String", ">", "configureJob", "(", "Job", "job", ")", "throws", "FileNotFoundException", ",", "IOException", ",", "TupleMRException", "{", "Set", "<", "String", ">", "instanceFiles", "=", "new", "HashSet", "<", "String", ">", "(", ")",...
Use this method for configuring a Job instance according to the named outputs specs that has been specified. Returns the instance files that have been created.
[ "Use", "this", "method", "for", "configuring", "a", "Job", "instance", "according", "to", "the", "named", "outputs", "specs", "that", "has", "been", "specified", ".", "Returns", "the", "instance", "files", "that", "have", "been", "created", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/NamedOutputsInterface.java#L68-L88
train
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/DeployCommand.java
DeployCommand.canCheckWar
public boolean canCheckWar(String warName, String url, HttpClient client) { HttpOptions opt = new HttpOptions(url + "/" + warName); try { HttpResponse response = client.execute(opt); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { Header allowHeader[] = response.getHeaders("Allow"); for(Header allow : allowHeader) { List<String> values = Arrays.asList(allow.getValue().toUpperCase().split(",")); if(values.contains("GET")) { return true; } } } EntityUtils.consumeQuietly(response.getEntity()); } catch (Exception e) { log.warn("Failed to check if endpoint exists.", e); } finally { opt.releaseConnection(); } return false; }
java
public boolean canCheckWar(String warName, String url, HttpClient client) { HttpOptions opt = new HttpOptions(url + "/" + warName); try { HttpResponse response = client.execute(opt); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { Header allowHeader[] = response.getHeaders("Allow"); for(Header allow : allowHeader) { List<String> values = Arrays.asList(allow.getValue().toUpperCase().split(",")); if(values.contains("GET")) { return true; } } } EntityUtils.consumeQuietly(response.getEntity()); } catch (Exception e) { log.warn("Failed to check if endpoint exists.", e); } finally { opt.releaseConnection(); } return false; }
[ "public", "boolean", "canCheckWar", "(", "String", "warName", ",", "String", "url", ",", "HttpClient", "client", ")", "{", "HttpOptions", "opt", "=", "new", "HttpOptions", "(", "url", "+", "\"/\"", "+", "warName", ")", ";", "try", "{", "HttpResponse", "res...
Checks via an http options request that the endpoint exists to check for deployment state. @param warName @param url @param client @return
[ "Checks", "via", "an", "http", "options", "request", "that", "the", "endpoint", "exists", "to", "check", "for", "deployment", "state", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/DeployCommand.java#L200-L220
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/channel/AbstractEncoderChannel.java
AbstractEncoderChannel.encodeBinary
public void encodeBinary(byte[] b) throws IOException { encodeUnsignedInteger(b.length); encode(b, 0, b.length); }
java
public void encodeBinary(byte[] b) throws IOException { encodeUnsignedInteger(b.length); encode(b, 0, b.length); }
[ "public", "void", "encodeBinary", "(", "byte", "[", "]", "b", ")", "throws", "IOException", "{", "encodeUnsignedInteger", "(", "b", ".", "length", ")", ";", "encode", "(", "b", ",", "0", ",", "b", ".", "length", ")", ";", "}" ]
Encode a binary value as a length-prefixed sequence of octets.
[ "Encode", "a", "binary", "value", "as", "a", "length", "-", "prefixed", "sequence", "of", "octets", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/channel/AbstractEncoderChannel.java#L46-L49
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/channel/AbstractEncoderChannel.java
AbstractEncoderChannel.encodeString
public void encodeString(final String s) throws IOException { final int lenChars = s.length(); final int lenCharacters = s.codePointCount(0, lenChars); encodeUnsignedInteger(lenCharacters); encodeStringOnly(s); }
java
public void encodeString(final String s) throws IOException { final int lenChars = s.length(); final int lenCharacters = s.codePointCount(0, lenChars); encodeUnsignedInteger(lenCharacters); encodeStringOnly(s); }
[ "public", "void", "encodeString", "(", "final", "String", "s", ")", "throws", "IOException", "{", "final", "int", "lenChars", "=", "s", ".", "length", "(", ")", ";", "final", "int", "lenCharacters", "=", "s", ".", "codePointCount", "(", "0", ",", "lenCha...
Encode a string as a length-prefixed sequence of UCS codepoints, each of which is encoded as an integer. Look for codepoints of more than 16 bits that are represented as UTF-16 surrogate pairs in Java.
[ "Encode", "a", "string", "as", "a", "length", "-", "prefixed", "sequence", "of", "UCS", "codepoints", "each", "of", "which", "is", "encoded", "as", "an", "integer", ".", "Look", "for", "codepoints", "of", "more", "than", "16", "bits", "that", "are", "rep...
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/channel/AbstractEncoderChannel.java#L56-L61
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/channel/AbstractEncoderChannel.java
AbstractEncoderChannel.encodeInteger
public void encodeInteger(int n) throws IOException { // signalize sign if (n < 0) { encodeBoolean(true); // For negative values, the Unsigned Integer holds the // magnitude of the value minus 1 encodeUnsignedInteger((-n) - 1); } else { encodeBoolean(false); encodeUnsignedInteger(n); } }
java
public void encodeInteger(int n) throws IOException { // signalize sign if (n < 0) { encodeBoolean(true); // For negative values, the Unsigned Integer holds the // magnitude of the value minus 1 encodeUnsignedInteger((-n) - 1); } else { encodeBoolean(false); encodeUnsignedInteger(n); } }
[ "public", "void", "encodeInteger", "(", "int", "n", ")", "throws", "IOException", "{", "// signalize sign", "if", "(", "n", "<", "0", ")", "{", "encodeBoolean", "(", "true", ")", ";", "// For negative values, the Unsigned Integer holds the", "// magnitude of the value...
Encode an arbitrary precision integer using a sign bit followed by a sequence of octets. The most significant bit of the last octet is set to zero to indicate sequence termination. Only seven bits per octet are used to store the integer's value.
[ "Encode", "an", "arbitrary", "precision", "integer", "using", "a", "sign", "bit", "followed", "by", "a", "sequence", "of", "octets", ".", "The", "most", "significant", "bit", "of", "the", "last", "octet", "is", "set", "to", "zero", "to", "indicate", "seque...
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/channel/AbstractEncoderChannel.java#L87-L98
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/channel/AbstractEncoderChannel.java
AbstractEncoderChannel.encodeUnsignedInteger
public void encodeUnsignedInteger(int n) throws IOException { if (n < 0) { throw new UnsupportedOperationException(); } if (n < 128) { // write byte as is encode(n); } else { final int n7BitBlocks = MethodsBag.numberOf7BitBlocksToRepresent(n); switch (n7BitBlocks) { case 5: encode(128 | n); n = n >>> 7; case 4: encode(128 | n); n = n >>> 7; case 3: encode(128 | n); n = n >>> 7; case 2: encode(128 | n); n = n >>> 7; case 1: // 0 .. 7 (last byte) encode(0 | n); } } }
java
public void encodeUnsignedInteger(int n) throws IOException { if (n < 0) { throw new UnsupportedOperationException(); } if (n < 128) { // write byte as is encode(n); } else { final int n7BitBlocks = MethodsBag.numberOf7BitBlocksToRepresent(n); switch (n7BitBlocks) { case 5: encode(128 | n); n = n >>> 7; case 4: encode(128 | n); n = n >>> 7; case 3: encode(128 | n); n = n >>> 7; case 2: encode(128 | n); n = n >>> 7; case 1: // 0 .. 7 (last byte) encode(0 | n); } } }
[ "public", "void", "encodeUnsignedInteger", "(", "int", "n", ")", "throws", "IOException", "{", "if", "(", "n", "<", "0", ")", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "if", "(", "n", "<", "128", ")", "{", "// write byte a...
Encode an arbitrary precision non negative integer using a sequence of octets. The most significant bit of the last octet is set to zero to indicate sequence termination. Only seven bits per octet are used to store the integer's value.
[ "Encode", "an", "arbitrary", "precision", "non", "negative", "integer", "using", "a", "sequence", "of", "octets", ".", "The", "most", "significant", "bit", "of", "the", "last", "octet", "is", "set", "to", "zero", "to", "indicate", "sequence", "termination", ...
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/channel/AbstractEncoderChannel.java#L144-L173
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/io/channel/AbstractEncoderChannel.java
AbstractEncoderChannel.encodeFloat
public void encodeFloat(FloatValue fv) throws IOException { // encode mantissa and exponent encodeIntegerValue(fv.getMantissa()); encodeIntegerValue(fv.getExponent()); }
java
public void encodeFloat(FloatValue fv) throws IOException { // encode mantissa and exponent encodeIntegerValue(fv.getMantissa()); encodeIntegerValue(fv.getExponent()); }
[ "public", "void", "encodeFloat", "(", "FloatValue", "fv", ")", "throws", "IOException", "{", "// encode mantissa and exponent", "encodeIntegerValue", "(", "fv", ".", "getMantissa", "(", ")", ")", ";", "encodeIntegerValue", "(", "fv", ".", "getExponent", "(", ")", ...
Encode a Float represented as two consecutive Integers. The first Integer represents the mantissa of the floating point number and the second Integer represents the 10-based exponent of the floating point number
[ "Encode", "a", "Float", "represented", "as", "two", "consecutive", "Integers", ".", "The", "first", "Integer", "represents", "the", "mantissa", "of", "the", "floating", "point", "number", "and", "the", "second", "Integer", "represents", "the", "10", "-", "base...
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/io/channel/AbstractEncoderChannel.java#L251-L255
train
meltmedia/cadmium
email/src/main/java/com/meltmedia/cadmium/email/Email.java
Email.addAddressHelper
private void addAddressHelper(InternetAddressSet set, String address) { if (address.contains(",") || address.contains(";")) { String[] addresses = address.split("[,;]"); for (String a : addresses) { set.add(a); } } else { set.add(address); } }
java
private void addAddressHelper(InternetAddressSet set, String address) { if (address.contains(",") || address.contains(";")) { String[] addresses = address.split("[,;]"); for (String a : addresses) { set.add(a); } } else { set.add(address); } }
[ "private", "void", "addAddressHelper", "(", "InternetAddressSet", "set", ",", "String", "address", ")", "{", "if", "(", "address", ".", "contains", "(", "\",\"", ")", "||", "address", ".", "contains", "(", "\";\"", ")", ")", "{", "String", "[", "]", "add...
Checks if the addresses need to be split either on , or ; @param set Internet address set to add the address to @param address address or addresses to add to the given set
[ "Checks", "if", "the", "addresses", "need", "to", "be", "split", "either", "on", "or", ";" ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/email/src/main/java/com/meltmedia/cadmium/email/Email.java#L59-L70
train
meltmedia/cadmium
email/src/main/java/com/meltmedia/cadmium/email/Email.java
Email.simplify
public void simplify() { // remove all addresses from the cc and bcc that are in the to address set. ccSet.removeAll(toSet); bccSet.removeAll(toSet); // remove all address from the bcc set that are in the cc set. bccSet.removeAll(ccSet); }
java
public void simplify() { // remove all addresses from the cc and bcc that are in the to address set. ccSet.removeAll(toSet); bccSet.removeAll(toSet); // remove all address from the bcc set that are in the cc set. bccSet.removeAll(ccSet); }
[ "public", "void", "simplify", "(", ")", "{", "// remove all addresses from the cc and bcc that are in the to address set.", "ccSet", ".", "removeAll", "(", "toSet", ")", ";", "bccSet", ".", "removeAll", "(", "toSet", ")", ";", "// remove all address from the bcc set that ar...
Simplifies this email by removing duplicate pieces of information. The standard implementation removes duplicate recipient emails in the to, cc, and bcc sets.
[ "Simplifies", "this", "email", "by", "removing", "duplicate", "pieces", "of", "information", ".", "The", "standard", "implementation", "removes", "duplicate", "recipient", "emails", "in", "the", "to", "cc", "and", "bcc", "sets", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/email/src/main/java/com/meltmedia/cadmium/email/Email.java#L160-L168
train
meltmedia/cadmium
email/src/main/java/com/meltmedia/cadmium/email/Email.java
Email.populate
protected void populate( MimeMessage message ) throws MessagingException { // add all of the to addresses. message.addRecipients(Message.RecipientType.TO, toSet.toInternetAddressArray()); message.addRecipients(Message.RecipientType.CC, ccSet.toInternetAddressArray()); message.addRecipients(Message.RecipientType.BCC, bccSet.toInternetAddressArray()); message.setFrom(from); if( replyTo != null ) { message.setReplyTo(new InternetAddress[] {replyTo}); } if( subject != null ) { message.setSubject(subject); } }
java
protected void populate( MimeMessage message ) throws MessagingException { // add all of the to addresses. message.addRecipients(Message.RecipientType.TO, toSet.toInternetAddressArray()); message.addRecipients(Message.RecipientType.CC, ccSet.toInternetAddressArray()); message.addRecipients(Message.RecipientType.BCC, bccSet.toInternetAddressArray()); message.setFrom(from); if( replyTo != null ) { message.setReplyTo(new InternetAddress[] {replyTo}); } if( subject != null ) { message.setSubject(subject); } }
[ "protected", "void", "populate", "(", "MimeMessage", "message", ")", "throws", "MessagingException", "{", "// add all of the to addresses.", "message", ".", "addRecipients", "(", "Message", ".", "RecipientType", ".", "TO", ",", "toSet", ".", "toInternetAddressArray", ...
Populates a mime message with the recipient addresses, from address, reply to address, and the subject.
[ "Populates", "a", "mime", "message", "with", "the", "recipient", "addresses", "from", "address", "reply", "to", "address", "and", "the", "subject", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/email/src/main/java/com/meltmedia/cadmium/email/Email.java#L173-L187
train
opentable/otj-logging
core/src/main/java/com/opentable/logging/AttachLogFilter.java
AttachLogFilter.attach
public static AttachLogFilter attach(Filter<ILoggingEvent> filter, String configKey) { return new AttachLogFilter(filter, configKey); }
java
public static AttachLogFilter attach(Filter<ILoggingEvent> filter, String configKey) { return new AttachLogFilter(filter, configKey); }
[ "public", "static", "AttachLogFilter", "attach", "(", "Filter", "<", "ILoggingEvent", ">", "filter", ",", "String", "configKey", ")", "{", "return", "new", "AttachLogFilter", "(", "filter", ",", "configKey", ")", ";", "}" ]
Create an attach log filter @param filter the filter to attach @param configKey the config key to see if this filter is enabled @return the attach log filter object
[ "Create", "an", "attach", "log", "filter" ]
eaa74c877c4721ddb9af8eb7fe1612166f7ac14d
https://github.com/opentable/otj-logging/blob/eaa74c877c4721ddb9af8eb7fe1612166f7ac14d/core/src/main/java/com/opentable/logging/AttachLogFilter.java#L101-L103
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/serialization/ThriftSerialization.java
ThriftSerialization.enableThriftSerialization
public static void enableThriftSerialization(Configuration conf) { String ser = conf.get("io.serializations").trim(); if (ser.length() !=0 ) { ser += ","; } //Adding the Thrift serialization ser += ThriftSerialization.class.getName(); conf.set("io.serializations", ser); }
java
public static void enableThriftSerialization(Configuration conf) { String ser = conf.get("io.serializations").trim(); if (ser.length() !=0 ) { ser += ","; } //Adding the Thrift serialization ser += ThriftSerialization.class.getName(); conf.set("io.serializations", ser); }
[ "public", "static", "void", "enableThriftSerialization", "(", "Configuration", "conf", ")", "{", "String", "ser", "=", "conf", ".", "get", "(", "\"io.serializations\"", ")", ".", "trim", "(", ")", ";", "if", "(", "ser", ".", "length", "(", ")", "!=", "0"...
Enables Thrift Serialization support in Hadoop.
[ "Enables", "Thrift", "Serialization", "support", "in", "Hadoop", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/serialization/ThriftSerialization.java#L121-L129
train
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/CadmiumCli.java
CadmiumCli.main
public static void main(String[] args) { try { jCommander = new JCommander(); jCommander.setProgramName("cadmium"); HelpCommand helpCommand = new HelpCommand(); jCommander.addCommand("help", helpCommand); Map<String, CliCommand> commands = wireCommands(jCommander); try { jCommander.parse(args); } catch(ParameterException pe) { System.err.println(pe.getMessage()); System.exit(1); } String commandName = jCommander.getParsedCommand(); if( commandName == null ) { System.out.println("Please use one of the following commands:"); for(String command : jCommander.getCommands().keySet() ) { String desc = jCommander.getCommands().get(command).getObjects().get(0).getClass().getAnnotation(Parameters.class).commandDescription(); System.out.format(" %16s -%s\n", command, desc); } } else if( commandName.equals("help") ) { if( helpCommand.subCommand == null || helpCommand.subCommand.size()==0 ) { jCommander.usage(); return; } else { JCommander subCommander = jCommander.getCommands().get(helpCommand.subCommand.get(0)); if( subCommander == null ) { System.out.println("Unknown sub command "+commandName); return; } subCommander.usage(); return; } } else if(commands.containsKey(commandName)){ CliCommand command = commands.get(commandName); if(command instanceof AuthorizedOnly) { setupSsh(((AuthorizedOnly) command).isAuthQuiet()); setupAuth((AuthorizedOnly) command); } command.execute(); } } catch( Exception e ) { System.err.println("Error: " + e.getMessage()); logger.debug("Cli Failed", e); e.printStackTrace(); System.exit(1); } }
java
public static void main(String[] args) { try { jCommander = new JCommander(); jCommander.setProgramName("cadmium"); HelpCommand helpCommand = new HelpCommand(); jCommander.addCommand("help", helpCommand); Map<String, CliCommand> commands = wireCommands(jCommander); try { jCommander.parse(args); } catch(ParameterException pe) { System.err.println(pe.getMessage()); System.exit(1); } String commandName = jCommander.getParsedCommand(); if( commandName == null ) { System.out.println("Please use one of the following commands:"); for(String command : jCommander.getCommands().keySet() ) { String desc = jCommander.getCommands().get(command).getObjects().get(0).getClass().getAnnotation(Parameters.class).commandDescription(); System.out.format(" %16s -%s\n", command, desc); } } else if( commandName.equals("help") ) { if( helpCommand.subCommand == null || helpCommand.subCommand.size()==0 ) { jCommander.usage(); return; } else { JCommander subCommander = jCommander.getCommands().get(helpCommand.subCommand.get(0)); if( subCommander == null ) { System.out.println("Unknown sub command "+commandName); return; } subCommander.usage(); return; } } else if(commands.containsKey(commandName)){ CliCommand command = commands.get(commandName); if(command instanceof AuthorizedOnly) { setupSsh(((AuthorizedOnly) command).isAuthQuiet()); setupAuth((AuthorizedOnly) command); } command.execute(); } } catch( Exception e ) { System.err.println("Error: " + e.getMessage()); logger.debug("Cli Failed", e); e.printStackTrace(); System.exit(1); } }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "try", "{", "jCommander", "=", "new", "JCommander", "(", ")", ";", "jCommander", ".", "setProgramName", "(", "\"cadmium\"", ")", ";", "HelpCommand", "helpCommand", "=", "new", ...
The main entry point to Cadmium cli. @param args
[ "The", "main", "entry", "point", "to", "Cadmium", "cli", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/CadmiumCli.java#L60-L117
train
meltmedia/cadmium
cli/src/main/java/com/meltmedia/cadmium/cli/CadmiumCli.java
CadmiumCli.setupSsh
private static void setupSsh(boolean noPrompt) { File sshDir = new File(System.getProperty("user.home"), ".ssh"); if(sshDir.exists()) { GitService.setupLocalSsh(sshDir.getAbsolutePath(), noPrompt); } }
java
private static void setupSsh(boolean noPrompt) { File sshDir = new File(System.getProperty("user.home"), ".ssh"); if(sshDir.exists()) { GitService.setupLocalSsh(sshDir.getAbsolutePath(), noPrompt); } }
[ "private", "static", "void", "setupSsh", "(", "boolean", "noPrompt", ")", "{", "File", "sshDir", "=", "new", "File", "(", "System", ".", "getProperty", "(", "\"user.home\"", ")", ",", "\".ssh\"", ")", ";", "if", "(", "sshDir", ".", "exists", "(", ")", ...
Sets up the ssh configuration that git will use to communicate with the remote git repositories. @param noPrompt True if there should be authentication prompts for the users username and password. If false, the program will fail with an exit code of 1 if not authorized.
[ "Sets", "up", "the", "ssh", "configuration", "that", "git", "will", "use", "to", "communicate", "with", "the", "remote", "git", "repositories", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/cli/src/main/java/com/meltmedia/cadmium/cli/CadmiumCli.java#L125-L130
train
datasalt/pangool
examples/src/main/java/com/datasalt/pangool/examples/gameoflife/GameOfLife.java
GameOfLife.emptyMatrix
public static void emptyMatrix(byte[][] matrix, int maxX, int maxY) { for(int i = 0; i < maxX; i++) { for(int j = 0; j < maxY; j++) { matrix[i][j] = 0; } } }
java
public static void emptyMatrix(byte[][] matrix, int maxX, int maxY) { for(int i = 0; i < maxX; i++) { for(int j = 0; j < maxY; j++) { matrix[i][j] = 0; } } }
[ "public", "static", "void", "emptyMatrix", "(", "byte", "[", "]", "[", "]", "matrix", ",", "int", "maxX", ",", "int", "maxY", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "maxX", ";", "i", "++", ")", "{", "for", "(", "int", "j",...
It is not very efficient but it is simple enough
[ "It", "is", "not", "very", "efficient", "but", "it", "is", "simple", "enough" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/examples/src/main/java/com/datasalt/pangool/examples/gameoflife/GameOfLife.java#L71-L77
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/values/BinaryHexValue.java
BinaryHexValue.decode
static public byte[] decode(String encoded) { if (encoded == null) return null; int lengthData = encoded.length(); if (lengthData % 2 != 0) return null; char[] binaryData = encoded.toCharArray(); int lengthDecode = lengthData / 2; byte[] decodedData = new byte[lengthDecode]; byte temp1, temp2; char tempChar; for (int i = 0; i < lengthDecode; i++) { tempChar = binaryData[i * 2]; temp1 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1; if (temp1 == -1) return null; tempChar = binaryData[i * 2 + 1]; temp2 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1; if (temp2 == -1) return null; decodedData[i] = (byte) ((temp1 << 4) | temp2); } return decodedData; }
java
static public byte[] decode(String encoded) { if (encoded == null) return null; int lengthData = encoded.length(); if (lengthData % 2 != 0) return null; char[] binaryData = encoded.toCharArray(); int lengthDecode = lengthData / 2; byte[] decodedData = new byte[lengthDecode]; byte temp1, temp2; char tempChar; for (int i = 0; i < lengthDecode; i++) { tempChar = binaryData[i * 2]; temp1 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1; if (temp1 == -1) return null; tempChar = binaryData[i * 2 + 1]; temp2 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1; if (temp2 == -1) return null; decodedData[i] = (byte) ((temp1 << 4) | temp2); } return decodedData; }
[ "static", "public", "byte", "[", "]", "decode", "(", "String", "encoded", ")", "{", "if", "(", "encoded", "==", "null", ")", "return", "null", ";", "int", "lengthData", "=", "encoded", ".", "length", "(", ")", ";", "if", "(", "lengthData", "%", "2", ...
Decode hex string to a byte array @param encoded encoded string @return return array of byte to encode
[ "Decode", "hex", "string", "to", "a", "byte", "array" ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/values/BinaryHexValue.java#L137-L161
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/values/DateTimeValue.java
DateTimeValue.parse
public static DateTimeValue parse(Calendar cal, DateTimeType type) { int sYear = 0; int sMonthDay = 0; int sTime = 0; int sFractionalSecs = 0; boolean sPresenceTimezone = false; int sTimezone; switch (type) { case gYear: // gYear Year, [Time-Zone] case gYearMonth: // gYearMonth Year, MonthDay, [TimeZone] case date: // date Year, MonthDay, [TimeZone] sYear = cal.get(Calendar.YEAR); sMonthDay = getMonthDay(cal); break; case dateTime: // dateTime Year, MonthDay, Time, [FractionalSecs], // [TimeZone] sYear = cal.get(Calendar.YEAR); sMonthDay = getMonthDay(cal); // Note: *no* break; case time: // time Time, [FractionalSecs], [TimeZone] sTime = getTime(cal); sFractionalSecs = cal.get(Calendar.MILLISECOND); break; case gMonth: // gMonth MonthDay, [TimeZone] case gMonthDay: // gMonthDay MonthDay, [TimeZone] case gDay: // gDay MonthDay, [TimeZone] sMonthDay = getMonthDay(cal); break; default: throw new UnsupportedOperationException(); } // [TimeZone] sTimezone = getTimeZoneInMinutesOffset(cal); if (sTimezone != 0) { sPresenceTimezone = true; } return new DateTimeValue(type, sYear, sMonthDay, sTime, sFractionalSecs, sPresenceTimezone, sTimezone); }
java
public static DateTimeValue parse(Calendar cal, DateTimeType type) { int sYear = 0; int sMonthDay = 0; int sTime = 0; int sFractionalSecs = 0; boolean sPresenceTimezone = false; int sTimezone; switch (type) { case gYear: // gYear Year, [Time-Zone] case gYearMonth: // gYearMonth Year, MonthDay, [TimeZone] case date: // date Year, MonthDay, [TimeZone] sYear = cal.get(Calendar.YEAR); sMonthDay = getMonthDay(cal); break; case dateTime: // dateTime Year, MonthDay, Time, [FractionalSecs], // [TimeZone] sYear = cal.get(Calendar.YEAR); sMonthDay = getMonthDay(cal); // Note: *no* break; case time: // time Time, [FractionalSecs], [TimeZone] sTime = getTime(cal); sFractionalSecs = cal.get(Calendar.MILLISECOND); break; case gMonth: // gMonth MonthDay, [TimeZone] case gMonthDay: // gMonthDay MonthDay, [TimeZone] case gDay: // gDay MonthDay, [TimeZone] sMonthDay = getMonthDay(cal); break; default: throw new UnsupportedOperationException(); } // [TimeZone] sTimezone = getTimeZoneInMinutesOffset(cal); if (sTimezone != 0) { sPresenceTimezone = true; } return new DateTimeValue(type, sYear, sMonthDay, sTime, sFractionalSecs, sPresenceTimezone, sTimezone); }
[ "public", "static", "DateTimeValue", "parse", "(", "Calendar", "cal", ",", "DateTimeType", "type", ")", "{", "int", "sYear", "=", "0", ";", "int", "sMonthDay", "=", "0", ";", "int", "sTime", "=", "0", ";", "int", "sFractionalSecs", "=", "0", ";", "bool...
Encode Date-Time as a sequence of values representing the individual components of the Date-Time. @param cal calendar @param type date-time type @return date-time value
[ "Encode", "Date", "-", "Time", "as", "a", "sequence", "of", "values", "representing", "the", "individual", "components", "of", "the", "Date", "-", "Time", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/values/DateTimeValue.java#L365-L406
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/values/DateTimeValue.java
DateTimeValue.setMonthDay
protected static void setMonthDay(int monthDay, Calendar cal) { // monthDay = month * 32 + day; int month = monthDay / MONTH_MULTIPLICATOR; cal.set(Calendar.MONTH, month - 1); int day = monthDay - month * MONTH_MULTIPLICATOR; cal.set(Calendar.DAY_OF_MONTH, day); }
java
protected static void setMonthDay(int monthDay, Calendar cal) { // monthDay = month * 32 + day; int month = monthDay / MONTH_MULTIPLICATOR; cal.set(Calendar.MONTH, month - 1); int day = monthDay - month * MONTH_MULTIPLICATOR; cal.set(Calendar.DAY_OF_MONTH, day); }
[ "protected", "static", "void", "setMonthDay", "(", "int", "monthDay", ",", "Calendar", "cal", ")", "{", "// monthDay = month * 32 + day;", "int", "month", "=", "monthDay", "/", "MONTH_MULTIPLICATOR", ";", "cal", ".", "set", "(", "Calendar", ".", "MONTH", ",", ...
Sets month and day of the given calendar making use of of the monthDay representation defined in EXI format @param monthDay monthDay @param cal calendar
[ "Sets", "month", "and", "day", "of", "the", "given", "calendar", "making", "use", "of", "of", "the", "monthDay", "representation", "defined", "in", "EXI", "format" ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/values/DateTimeValue.java#L488-L494
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/values/DateTimeValue.java
DateTimeValue.setTime
protected static void setTime(int time, Calendar cal) { // ((Hour * 64) + Minutes) * 64 + seconds int hour = time / (64 * 64); time -= hour * (64 * 64); int minute = time / 64; time -= minute * 64; // second cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.SECOND, time); }
java
protected static void setTime(int time, Calendar cal) { // ((Hour * 64) + Minutes) * 64 + seconds int hour = time / (64 * 64); time -= hour * (64 * 64); int minute = time / 64; time -= minute * 64; // second cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.SECOND, time); }
[ "protected", "static", "void", "setTime", "(", "int", "time", ",", "Calendar", "cal", ")", "{", "// ((Hour * 64) + Minutes) * 64 + seconds", "int", "hour", "=", "time", "/", "(", "64", "*", "64", ")", ";", "time", "-=", "hour", "*", "(", "64", "*", "64",...
Sets hour, minute and second of the given calendar making use of of the time representation defined in EXI format @param time time @param cal calendar
[ "Sets", "hour", "minute", "and", "second", "of", "the", "given", "calendar", "making", "use", "of", "of", "the", "time", "representation", "defined", "in", "EXI", "format" ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/values/DateTimeValue.java#L505-L514
train
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java
AbstractSecureRedirectStrategy.addPortMapping
private static void addPortMapping( Integer insecurePort, Integer securePort ) { TO_SECURE_PORT_MAP.put(insecurePort, securePort); TO_INSECURE_PORT_MAP.put(securePort, insecurePort); }
java
private static void addPortMapping( Integer insecurePort, Integer securePort ) { TO_SECURE_PORT_MAP.put(insecurePort, securePort); TO_INSECURE_PORT_MAP.put(securePort, insecurePort); }
[ "private", "static", "void", "addPortMapping", "(", "Integer", "insecurePort", ",", "Integer", "securePort", ")", "{", "TO_SECURE_PORT_MAP", ".", "put", "(", "insecurePort", ",", "securePort", ")", ";", "TO_INSECURE_PORT_MAP", ".", "put", "(", "securePort", ",", ...
Adds an entry to the secure and insecure port map.
[ "Adds", "an", "entry", "to", "the", "secure", "and", "insecure", "port", "map", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java#L52-L55
train
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java
AbstractSecureRedirectStrategy.getDefaultPort
public static int getDefaultPort( String protocol ) { if( HTTP_PROTOCOL.equals(protocol) ) { return DEFAULT_HTTP_PORT; } else if( HTTPS_PROTOCOL.equals(protocol) ) { return DEFAULT_HTTPS_PORT; } else { throw new IllegalArgumentException("No known default for "+protocol); } }
java
public static int getDefaultPort( String protocol ) { if( HTTP_PROTOCOL.equals(protocol) ) { return DEFAULT_HTTP_PORT; } else if( HTTPS_PROTOCOL.equals(protocol) ) { return DEFAULT_HTTPS_PORT; } else { throw new IllegalArgumentException("No known default for "+protocol); } }
[ "public", "static", "int", "getDefaultPort", "(", "String", "protocol", ")", "{", "if", "(", "HTTP_PROTOCOL", ".", "equals", "(", "protocol", ")", ")", "{", "return", "DEFAULT_HTTP_PORT", ";", "}", "else", "if", "(", "HTTPS_PROTOCOL", ".", "equals", "(", "...
Returns the default port for the specified protocol. @param protocol the protocol name. @return the default port for the specifed protocol.
[ "Returns", "the", "default", "port", "for", "the", "specified", "protocol", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java#L68-L72
train
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java
AbstractSecureRedirectStrategy.mapPort
public static int mapPort(Map<Integer, Integer> mapping, int port) { Integer mappedPort = mapping.get(port); if( mappedPort == null ) throw new RuntimeException("Could not map port "+port); return mappedPort; }
java
public static int mapPort(Map<Integer, Integer> mapping, int port) { Integer mappedPort = mapping.get(port); if( mappedPort == null ) throw new RuntimeException("Could not map port "+port); return mappedPort; }
[ "public", "static", "int", "mapPort", "(", "Map", "<", "Integer", ",", "Integer", ">", "mapping", ",", "int", "port", ")", "{", "Integer", "mappedPort", "=", "mapping", ".", "get", "(", "port", ")", ";", "if", "(", "mappedPort", "==", "null", ")", "t...
Looks up a corresponding port number from a port mapping. @param mapping the port mapping @param port the key in the port map. @return the corresponding port number from the port mapping. @throws RuntimeException if a value could not be found.
[ "Looks", "up", "a", "corresponding", "port", "number", "from", "a", "port", "mapping", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java#L81-L85
train
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java
AbstractSecureRedirectStrategy.secureUrl
public String secureUrl(HttpServletRequest request, HttpServletResponse response) throws IOException { String protocol = getProtocol(request); if( protocol.equalsIgnoreCase(HTTP_PROTOCOL) ) { int port = mapPort(TO_SECURE_PORT_MAP, getPort(request)); try { URI newUri = changeProtocolAndPort(HTTPS_PROTOCOL, port == DEFAULT_HTTPS_PORT ? -1 : port, request); return newUri.toString(); } catch (URISyntaxException e) { throw new IllegalStateException("Failed to create URI.", e); } } else { throw new UnsupportedProtocolException("Cannot build secure url for "+protocol); } }
java
public String secureUrl(HttpServletRequest request, HttpServletResponse response) throws IOException { String protocol = getProtocol(request); if( protocol.equalsIgnoreCase(HTTP_PROTOCOL) ) { int port = mapPort(TO_SECURE_PORT_MAP, getPort(request)); try { URI newUri = changeProtocolAndPort(HTTPS_PROTOCOL, port == DEFAULT_HTTPS_PORT ? -1 : port, request); return newUri.toString(); } catch (URISyntaxException e) { throw new IllegalStateException("Failed to create URI.", e); } } else { throw new UnsupportedProtocolException("Cannot build secure url for "+protocol); } }
[ "public", "String", "secureUrl", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "IOException", "{", "String", "protocol", "=", "getProtocol", "(", "request", ")", ";", "if", "(", "protocol", ".", "equalsIgnoreCase", "(...
Returns the secure version of the original URL for the request. @param request the insecure request that was made. @param response the response for the request. @return the secure version of the original URL for the request. @throws IOException if the url could not be created.
[ "Returns", "the", "secure", "version", "of", "the", "original", "URL", "for", "the", "request", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java#L109-L123
train
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java
AbstractSecureRedirectStrategy.insecureUrl
public String insecureUrl(HttpServletRequest request, HttpServletResponse response) throws IOException { String protocol = getProtocol(request); if( protocol.equalsIgnoreCase(HTTPS_PROTOCOL) ) { int port = mapPort(TO_INSECURE_PORT_MAP, getPort(request)); try { return changeProtocolAndPort(HTTP_PROTOCOL, port == DEFAULT_HTTP_PORT ? -1 : port, request).toString(); } catch (URISyntaxException e) { throw new IllegalStateException("Failed to create URI.", e); } } else { throw new UnsupportedProtocolException("Cannot build insecure url for "+protocol); } }
java
public String insecureUrl(HttpServletRequest request, HttpServletResponse response) throws IOException { String protocol = getProtocol(request); if( protocol.equalsIgnoreCase(HTTPS_PROTOCOL) ) { int port = mapPort(TO_INSECURE_PORT_MAP, getPort(request)); try { return changeProtocolAndPort(HTTP_PROTOCOL, port == DEFAULT_HTTP_PORT ? -1 : port, request).toString(); } catch (URISyntaxException e) { throw new IllegalStateException("Failed to create URI.", e); } } else { throw new UnsupportedProtocolException("Cannot build insecure url for "+protocol); } }
[ "public", "String", "insecureUrl", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "IOException", "{", "String", "protocol", "=", "getProtocol", "(", "request", ")", ";", "if", "(", "protocol", ".", "equalsIgnoreCase", ...
Returns the insecure version of the original URL for the request. @param request the secure request that was made. @param response the response for the request. @return the insecure version of the original URL for the request. @throws IOException if the url could not be created.
[ "Returns", "the", "insecure", "version", "of", "the", "original", "URL", "for", "the", "request", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java#L133-L146
train
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java
AbstractSecureRedirectStrategy.makeSecure
@Override public void makeSecure(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", secureUrl(request, response)); response.getOutputStream().flush(); response.getOutputStream().close(); }
java
@Override public void makeSecure(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", secureUrl(request, response)); response.getOutputStream().flush(); response.getOutputStream().close(); }
[ "@", "Override", "public", "void", "makeSecure", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "IOException", "{", "response", ".", "setStatus", "(", "HttpServletResponse", ".", "SC_MOVED_PERMANENTLY", ")", ";", "response...
Sends a moved perminately redirect to the secure form of the request URL. @request the request to make secure. @response the response for the request.
[ "Sends", "a", "moved", "perminately", "redirect", "to", "the", "secure", "form", "of", "the", "request", "URL", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java#L154-L162
train
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java
AbstractSecureRedirectStrategy.makeInsecure
@Override public void makeInsecure(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", insecureUrl(request, response)); response.getOutputStream().flush(); response.getOutputStream().close(); }
java
@Override public void makeInsecure(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", insecureUrl(request, response)); response.getOutputStream().flush(); response.getOutputStream().close(); }
[ "@", "Override", "public", "void", "makeInsecure", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "IOException", "{", "response", ".", "setStatus", "(", "HttpServletResponse", ".", "SC_MOVED_PERMANENTLY", ")", ";", "respon...
Sends a moved perminately redirect to the insecure form of the request URL. @request the request to make secure. @response the response for the request.
[ "Sends", "a", "moved", "perminately", "redirect", "to", "the", "insecure", "form", "of", "the", "request", "URL", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/AbstractSecureRedirectStrategy.java#L170-L176
train
datasalt/pangool
examples/src/main/java/com/datasalt/pangool/examples/naivebayes/NaiveBayesClassifier.java
NaiveBayesClassifier.init
public void init(Configuration conf, Path generatedModel) throws IOException, InterruptedException { FileSystem fileSystem = FileSystem.get(conf); for(Category category : Category.values()) { wordCountPerCategory.put(category, new HashMap<String, Integer>()); // init token count } // Use a HashSet to calculate the total vocabulary size Set<String> vocabulary = new HashSet<String>(); // Read tuples from generate job for(FileStatus fileStatus : fileSystem.globStatus(generatedModel)) { TupleFile.Reader reader = new TupleFile.Reader(fileSystem, conf, fileStatus.getPath()); Tuple tuple = new Tuple(reader.getSchema()); while(reader.next(tuple)) { // Read Tuple Integer count = (Integer) tuple.get("count"); Category category = (Category) tuple.get("category"); String word = tuple.get("word").toString(); vocabulary.add(word); tokensPerCategory.put(category, MapUtils.getInteger(tokensPerCategory, category, 0) + count); wordCountPerCategory.get(category).put(word, count); } reader.close(); } V = vocabulary.size(); }
java
public void init(Configuration conf, Path generatedModel) throws IOException, InterruptedException { FileSystem fileSystem = FileSystem.get(conf); for(Category category : Category.values()) { wordCountPerCategory.put(category, new HashMap<String, Integer>()); // init token count } // Use a HashSet to calculate the total vocabulary size Set<String> vocabulary = new HashSet<String>(); // Read tuples from generate job for(FileStatus fileStatus : fileSystem.globStatus(generatedModel)) { TupleFile.Reader reader = new TupleFile.Reader(fileSystem, conf, fileStatus.getPath()); Tuple tuple = new Tuple(reader.getSchema()); while(reader.next(tuple)) { // Read Tuple Integer count = (Integer) tuple.get("count"); Category category = (Category) tuple.get("category"); String word = tuple.get("word").toString(); vocabulary.add(word); tokensPerCategory.put(category, MapUtils.getInteger(tokensPerCategory, category, 0) + count); wordCountPerCategory.get(category).put(word, count); } reader.close(); } V = vocabulary.size(); }
[ "public", "void", "init", "(", "Configuration", "conf", ",", "Path", "generatedModel", ")", "throws", "IOException", ",", "InterruptedException", "{", "FileSystem", "fileSystem", "=", "FileSystem", ".", "get", "(", "conf", ")", ";", "for", "(", "Category", "ca...
Read the Naive Bayes Model from HDFS
[ "Read", "the", "Naive", "Bayes", "Model", "from", "HDFS" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/examples/src/main/java/com/datasalt/pangool/examples/naivebayes/NaiveBayesClassifier.java#L49-L72
train
datasalt/pangool
examples/src/main/java/com/datasalt/pangool/examples/naivebayes/NaiveBayesClassifier.java
NaiveBayesClassifier.classify
public Category classify(String text) { StringTokenizer itr = new StringTokenizer(text); Map<Category, Double> scorePerCategory = new HashMap<Category, Double>(); double bestScore = Double.NEGATIVE_INFINITY; Category bestCategory = null; while(itr.hasMoreTokens()) { String token = NaiveBayesGenerate.normalizeWord(itr.nextToken()); for(Category category : Category.values()) { int count = MapUtils.getInteger(wordCountPerCategory.get(category), token, 0) + 1; double wordScore = Math.log(count / (double) (tokensPerCategory.get(category) + V)); double totalScore = MapUtils.getDouble(scorePerCategory, category, 0.) + wordScore; if(totalScore > bestScore) { bestScore = totalScore; bestCategory = category; } scorePerCategory.put(category, totalScore); } } return bestCategory; }
java
public Category classify(String text) { StringTokenizer itr = new StringTokenizer(text); Map<Category, Double> scorePerCategory = new HashMap<Category, Double>(); double bestScore = Double.NEGATIVE_INFINITY; Category bestCategory = null; while(itr.hasMoreTokens()) { String token = NaiveBayesGenerate.normalizeWord(itr.nextToken()); for(Category category : Category.values()) { int count = MapUtils.getInteger(wordCountPerCategory.get(category), token, 0) + 1; double wordScore = Math.log(count / (double) (tokensPerCategory.get(category) + V)); double totalScore = MapUtils.getDouble(scorePerCategory, category, 0.) + wordScore; if(totalScore > bestScore) { bestScore = totalScore; bestCategory = category; } scorePerCategory.put(category, totalScore); } } return bestCategory; }
[ "public", "Category", "classify", "(", "String", "text", ")", "{", "StringTokenizer", "itr", "=", "new", "StringTokenizer", "(", "text", ")", ";", "Map", "<", "Category", ",", "Double", ">", "scorePerCategory", "=", "new", "HashMap", "<", "Category", ",", ...
Naive Bayes Text Classification with Add-1 Smoothing @param text Input text @return the best {@link Category}
[ "Naive", "Bayes", "Text", "Classification", "with", "Add", "-", "1", "Smoothing" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/examples/src/main/java/com/datasalt/pangool/examples/naivebayes/NaiveBayesClassifier.java#L79-L98
train
EXIficient/exificient-core
src/main/java/com/siemens/ct/exi/core/util/MethodsBag.java
MethodsBag.numberOf7BitBlocksToRepresent
public static int numberOf7BitBlocksToRepresent(final long l) { if (l < 0xffffffff) { return numberOf7BitBlocksToRepresent((int) l); } // 35 bits else if (l < 0x800000000L) { return 5; } // 42 bits else if (l < 0x40000000000L) { return 6; } // 49 bits else if (l < 0x2000000000000L) { return 7; } // 56 bits else if (l < 0x100000000000000L) { return 8; } // 63 bits else if (l < 0x8000000000000000L) { return 9; } // 70 bits else { // long, 64 bits return 10; } }
java
public static int numberOf7BitBlocksToRepresent(final long l) { if (l < 0xffffffff) { return numberOf7BitBlocksToRepresent((int) l); } // 35 bits else if (l < 0x800000000L) { return 5; } // 42 bits else if (l < 0x40000000000L) { return 6; } // 49 bits else if (l < 0x2000000000000L) { return 7; } // 56 bits else if (l < 0x100000000000000L) { return 8; } // 63 bits else if (l < 0x8000000000000000L) { return 9; } // 70 bits else { // long, 64 bits return 10; } }
[ "public", "static", "int", "numberOf7BitBlocksToRepresent", "(", "final", "long", "l", ")", "{", "if", "(", "l", "<", "0xffffffff", ")", "{", "return", "numberOf7BitBlocksToRepresent", "(", "(", "int", ")", "l", ")", ";", "}", "// 35 bits", "else", "if", "...
Returns the least number of 7 bit-blocks that is needed to represent the parameter l. Returns 1 if parameter l is 0. @param l long value @return number of 7Bit blocks
[ "Returns", "the", "least", "number", "of", "7", "bit", "-", "blocks", "that", "is", "needed", "to", "represent", "the", "parameter", "l", ".", "Returns", "1", "if", "parameter", "l", "is", "0", "." ]
b6026c5fd39e9cc3d7874caa20f084e264e0ddc7
https://github.com/EXIficient/exificient-core/blob/b6026c5fd39e9cc3d7874caa20f084e264e0ddc7/src/main/java/com/siemens/ct/exi/core/util/MethodsBag.java#L85-L114
train
meltmedia/cadmium
email/src/main/java/com/meltmedia/cadmium/email/EmailUtil.java
EmailUtil.newMultipartBodyPart
public static MimeBodyPart newMultipartBodyPart( Multipart multipart ) throws MessagingException { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(multipart); return mimeBodyPart; }
java
public static MimeBodyPart newMultipartBodyPart( Multipart multipart ) throws MessagingException { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(multipart); return mimeBodyPart; }
[ "public", "static", "MimeBodyPart", "newMultipartBodyPart", "(", "Multipart", "multipart", ")", "throws", "MessagingException", "{", "MimeBodyPart", "mimeBodyPart", "=", "new", "MimeBodyPart", "(", ")", ";", "mimeBodyPart", ".", "setContent", "(", "multipart", ")", ...
Creates a body part for a multipart.
[ "Creates", "a", "body", "part", "for", "a", "multipart", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/email/src/main/java/com/meltmedia/cadmium/email/EmailUtil.java#L75-L81
train
meltmedia/cadmium
email/src/main/java/com/meltmedia/cadmium/email/EmailUtil.java
EmailUtil.newHtmlAttachmentBodyPart
public static MimeBodyPart newHtmlAttachmentBodyPart( URL contentUrl, String contentId ) throws MessagingException { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setDataHandler(new DataHandler(contentUrl)); if( contentId != null ) { mimeBodyPart.setHeader("Content-ID", contentId); } return mimeBodyPart; }
java
public static MimeBodyPart newHtmlAttachmentBodyPart( URL contentUrl, String contentId ) throws MessagingException { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setDataHandler(new DataHandler(contentUrl)); if( contentId != null ) { mimeBodyPart.setHeader("Content-ID", contentId); } return mimeBodyPart; }
[ "public", "static", "MimeBodyPart", "newHtmlAttachmentBodyPart", "(", "URL", "contentUrl", ",", "String", "contentId", ")", "throws", "MessagingException", "{", "MimeBodyPart", "mimeBodyPart", "=", "new", "MimeBodyPart", "(", ")", ";", "mimeBodyPart", ".", "setDataHan...
Creates a body part for an attachment that is used by an html body part.
[ "Creates", "a", "body", "part", "for", "an", "attachment", "that", "is", "used", "by", "an", "html", "body", "part", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/email/src/main/java/com/meltmedia/cadmium/email/EmailUtil.java#L102-L111
train
meltmedia/cadmium
email/src/main/java/com/meltmedia/cadmium/email/EmailUtil.java
EmailUtil.fileNameForUrl
public static String fileNameForUrl( URL contentUrl ) { String fileName = null; Matcher matcher = FILE_NAME_PATTERN.matcher(contentUrl.getPath()); if( matcher.find() ) { fileName = matcher.group(1); } return fileName; }
java
public static String fileNameForUrl( URL contentUrl ) { String fileName = null; Matcher matcher = FILE_NAME_PATTERN.matcher(contentUrl.getPath()); if( matcher.find() ) { fileName = matcher.group(1); } return fileName; }
[ "public", "static", "String", "fileNameForUrl", "(", "URL", "contentUrl", ")", "{", "String", "fileName", "=", "null", ";", "Matcher", "matcher", "=", "FILE_NAME_PATTERN", ".", "matcher", "(", "contentUrl", ".", "getPath", "(", ")", ")", ";", "if", "(", "m...
Returns the content disposition file name for a url. If a file name cannot be parsed from this url, then null is returned.
[ "Returns", "the", "content", "disposition", "file", "name", "for", "a", "url", ".", "If", "a", "file", "name", "cannot", "be", "parsed", "from", "this", "url", "then", "null", "is", "returned", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/email/src/main/java/com/meltmedia/cadmium/email/EmailUtil.java#L156-L164
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/SerializationInfo.java
SerializationInfo.initCommonAndGroupSchemaSerialization
private void initCommonAndGroupSchemaSerialization() { //TODO Should SerializationInfo contain Configuration ? commonSerializers = getSerializers(commonSchema, null); commonDeserializers = getDeserializers(commonSchema, commonSchema, null); groupSerializers = getSerializers(groupSchema, null); groupDeserializers = getDeserializers(groupSchema, groupSchema, null); }
java
private void initCommonAndGroupSchemaSerialization() { //TODO Should SerializationInfo contain Configuration ? commonSerializers = getSerializers(commonSchema, null); commonDeserializers = getDeserializers(commonSchema, commonSchema, null); groupSerializers = getSerializers(groupSchema, null); groupDeserializers = getDeserializers(groupSchema, groupSchema, null); }
[ "private", "void", "initCommonAndGroupSchemaSerialization", "(", ")", "{", "//TODO Should SerializationInfo contain Configuration ?", "commonSerializers", "=", "getSerializers", "(", "commonSchema", ",", "null", ")", ";", "commonDeserializers", "=", "getDeserializers", "(", "...
This serializers have been defined by the user in an OBJECT field
[ "This", "serializers", "have", "been", "defined", "by", "the", "user", "in", "an", "OBJECT", "field" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/SerializationInfo.java#L188-L195
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/SerializationInfo.java
SerializationInfo.checkFieldInAllSchemas
private Field checkFieldInAllSchemas(String name) throws TupleMRException { Field field = null; for (int i = 0; i < mrConfig.getIntermediateSchemas().size(); i++) { Field fieldInSource = checkFieldInSchema(name, i); if (field == null) { field = fieldInSource; } else if (field.getType() != fieldInSource.getType() || field.getObjectClass() != fieldInSource.getObjectClass()) { throw new TupleMRException("The type for field '" + name + "' is not the same in all the sources"); } else if (fieldInSource.isNullable()) { // IMPORTANT CASE. Nullable fields must be returned when present nullable and non nullable fields mixed field = fieldInSource; } } return field; }
java
private Field checkFieldInAllSchemas(String name) throws TupleMRException { Field field = null; for (int i = 0; i < mrConfig.getIntermediateSchemas().size(); i++) { Field fieldInSource = checkFieldInSchema(name, i); if (field == null) { field = fieldInSource; } else if (field.getType() != fieldInSource.getType() || field.getObjectClass() != fieldInSource.getObjectClass()) { throw new TupleMRException("The type for field '" + name + "' is not the same in all the sources"); } else if (fieldInSource.isNullable()) { // IMPORTANT CASE. Nullable fields must be returned when present nullable and non nullable fields mixed field = fieldInSource; } } return field; }
[ "private", "Field", "checkFieldInAllSchemas", "(", "String", "name", ")", "throws", "TupleMRException", "{", "Field", "field", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "mrConfig", ".", "getIntermediateSchemas", "(", ")", ".", "siz...
Checks that the field with the given name is in all schemas, and select a representative field that will be used for serializing. In the case of having a mixture of fields, some of them nullable and some others no nullables, a nullable Field will be returned.
[ "Checks", "that", "the", "field", "with", "the", "given", "name", "is", "in", "all", "schemas", "and", "select", "a", "representative", "field", "that", "will", "be", "used", "for", "serializing", ".", "In", "the", "case", "of", "having", "a", "mixture", ...
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/SerializationInfo.java#L348-L363
train
meltmedia/cadmium
maven/src/main/java/com/meltmedia/cadmium/maven/ArtifactResolver.java
ArtifactResolver.resolveMavenArtifact
public File resolveMavenArtifact(String artifact) throws ArtifactResolutionException { // NOTE: This page on Aether (https://docs.sonatype.org/display/AETHER/Home) states that // the plexus container uses the context class loader. ClassLoader oldContext = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); RepositorySystem repoSystem = newRepositorySystem(); RepositorySystemSession session = newSession( repoSystem ); Artifact artifactObj = new DefaultArtifact( artifact ); RemoteRepository repo = new RemoteRepository( "cadmium-central", "default", remoteMavenRepository ); // TODO: we should remove the snapshot policy in production mode. repo.setPolicy(true, new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_ALWAYS, RepositoryPolicy.CHECKSUM_POLICY_WARN)); repo.setPolicy(false, new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_DAILY, RepositoryPolicy.CHECKSUM_POLICY_WARN)); ArtifactRequest artifactRequest = new ArtifactRequest(); artifactRequest.setArtifact( artifactObj ); artifactRequest.addRepository( repo ); ArtifactResult artifactResult = repoSystem.resolveArtifact( session, artifactRequest ); artifactObj = artifactResult.getArtifact(); return artifactObj.getFile(); } finally { Thread.currentThread().setContextClassLoader(oldContext); } }
java
public File resolveMavenArtifact(String artifact) throws ArtifactResolutionException { // NOTE: This page on Aether (https://docs.sonatype.org/display/AETHER/Home) states that // the plexus container uses the context class loader. ClassLoader oldContext = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); RepositorySystem repoSystem = newRepositorySystem(); RepositorySystemSession session = newSession( repoSystem ); Artifact artifactObj = new DefaultArtifact( artifact ); RemoteRepository repo = new RemoteRepository( "cadmium-central", "default", remoteMavenRepository ); // TODO: we should remove the snapshot policy in production mode. repo.setPolicy(true, new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_ALWAYS, RepositoryPolicy.CHECKSUM_POLICY_WARN)); repo.setPolicy(false, new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_DAILY, RepositoryPolicy.CHECKSUM_POLICY_WARN)); ArtifactRequest artifactRequest = new ArtifactRequest(); artifactRequest.setArtifact( artifactObj ); artifactRequest.addRepository( repo ); ArtifactResult artifactResult = repoSystem.resolveArtifact( session, artifactRequest ); artifactObj = artifactResult.getArtifact(); return artifactObj.getFile(); } finally { Thread.currentThread().setContextClassLoader(oldContext); } }
[ "public", "File", "resolveMavenArtifact", "(", "String", "artifact", ")", "throws", "ArtifactResolutionException", "{", "// NOTE: This page on Aether (https://docs.sonatype.org/display/AETHER/Home) states that", "// the plexus container uses the context class loader.", "ClassLoader", "oldC...
Fetches a maven artifact and returns a File Object that points to its location. @param artifact The maven coordinates in the format of <code>groupId:artifactId:type:version</code> @return A File Object that points to the artifact. @throws ArtifactResolutionException
[ "Fetches", "a", "maven", "artifact", "and", "returns", "a", "File", "Object", "that", "points", "to", "its", "location", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/maven/src/main/java/com/meltmedia/cadmium/maven/ArtifactResolver.java#L79-L109
train
meltmedia/cadmium
maven/src/main/java/com/meltmedia/cadmium/maven/ArtifactResolver.java
ArtifactResolver.newSession
protected RepositorySystemSession newSession( RepositorySystem system ) { MavenRepositorySystemSession session = new MavenRepositorySystemSession(); LocalRepository localRepo = new LocalRepository( localRepository ); session.setLocalRepositoryManager( system.newLocalRepositoryManager( localRepo ) ); return session; }
java
protected RepositorySystemSession newSession( RepositorySystem system ) { MavenRepositorySystemSession session = new MavenRepositorySystemSession(); LocalRepository localRepo = new LocalRepository( localRepository ); session.setLocalRepositoryManager( system.newLocalRepositoryManager( localRepo ) ); return session; }
[ "protected", "RepositorySystemSession", "newSession", "(", "RepositorySystem", "system", ")", "{", "MavenRepositorySystemSession", "session", "=", "new", "MavenRepositorySystemSession", "(", ")", ";", "LocalRepository", "localRepo", "=", "new", "LocalRepository", "(", "lo...
Creates a new RepositorySystemSession. @param system A RepositorySystem to get a LocalRepositoryManager from. @return The new instance of a RespositorySystemSession.
[ "Creates", "a", "new", "RepositorySystemSession", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/maven/src/main/java/com/meltmedia/cadmium/maven/ArtifactResolver.java#L123-L131
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/utils/InstancesDistributor.java
InstancesDistributor.locateFileInCache
private static Path locateFileInCache(Configuration conf, String filename) throws IOException { return new Path(getInstancesFolder(FileSystem.get(conf), conf), filename); }
java
private static Path locateFileInCache(Configuration conf, String filename) throws IOException { return new Path(getInstancesFolder(FileSystem.get(conf), conf), filename); }
[ "private", "static", "Path", "locateFileInCache", "(", "Configuration", "conf", ",", "String", "filename", ")", "throws", "IOException", "{", "return", "new", "Path", "(", "getInstancesFolder", "(", "FileSystem", ".", "get", "(", "conf", ")", ",", "conf", ")",...
Locates a file in the temporal folder @param conf The Hadoop Configuration. @param filename The file name. @throws IOException
[ "Locates", "a", "file", "in", "the", "temporal", "folder" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/utils/InstancesDistributor.java#L149-L151
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/FileSystemManager.java
FileSystemManager.getWritableDirectoryWithFailovers
public static File getWritableDirectoryWithFailovers(String... directories) throws FileNotFoundException { File logDir = null; for(String directory : directories) { if(directory != null) { try { logDir = ensureDirectoryWriteable(new File(directory)); } catch(FileNotFoundException e) { log.debug("Failed to get writeable directory: "+directory, e); continue; } break; } } if(logDir == null) { throw new FileNotFoundException("Could not get a writeable directory!"); } return logDir; }
java
public static File getWritableDirectoryWithFailovers(String... directories) throws FileNotFoundException { File logDir = null; for(String directory : directories) { if(directory != null) { try { logDir = ensureDirectoryWriteable(new File(directory)); } catch(FileNotFoundException e) { log.debug("Failed to get writeable directory: "+directory, e); continue; } break; } } if(logDir == null) { throw new FileNotFoundException("Could not get a writeable directory!"); } return logDir; }
[ "public", "static", "File", "getWritableDirectoryWithFailovers", "(", "String", "...", "directories", ")", "throws", "FileNotFoundException", "{", "File", "logDir", "=", "null", ";", "for", "(", "String", "directory", ":", "directories", ")", "{", "if", "(", "di...
Gets the first writable directory that exists or can be created. @param directories The directories to try @return A File object that represents a writable directory. @throws FileNotFoundException Thrown if no directory can be written to.
[ "Gets", "the", "first", "writable", "directory", "that", "exists", "or", "can", "be", "created", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/FileSystemManager.java#L393-L410
train
meltmedia/cadmium
core/src/main/java/com/meltmedia/cadmium/core/FileSystemManager.java
FileSystemManager.ensureDirectoryWriteable
public static File ensureDirectoryWriteable(File logDir) throws FileNotFoundException { try { FileUtils.forceMkdir(logDir); } catch(IOException e){ log.debug("Failed to create directory " + logDir, e); throw new FileNotFoundException("Failed to create directory: " + logDir + " IOException: " + e.getMessage()); } if(!logDir.canWrite()) { log.debug("Init param log dir cannot be used!"); throw new FileNotFoundException("Directory is not writable: " + logDir); } return logDir; }
java
public static File ensureDirectoryWriteable(File logDir) throws FileNotFoundException { try { FileUtils.forceMkdir(logDir); } catch(IOException e){ log.debug("Failed to create directory " + logDir, e); throw new FileNotFoundException("Failed to create directory: " + logDir + " IOException: " + e.getMessage()); } if(!logDir.canWrite()) { log.debug("Init param log dir cannot be used!"); throw new FileNotFoundException("Directory is not writable: " + logDir); } return logDir; }
[ "public", "static", "File", "ensureDirectoryWriteable", "(", "File", "logDir", ")", "throws", "FileNotFoundException", "{", "try", "{", "FileUtils", ".", "forceMkdir", "(", "logDir", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "log", ".", "deb...
Try's to create a directory and ensures that it is writable. @param logDir The File object to check. @return The File object passed in for chaining call to it. This value will never be null. @throws FileNotFoundException Thrown if logDir is null, exists, is not a directory, cannot be created, or cannot be written to.
[ "Try", "s", "to", "create", "a", "directory", "and", "ensures", "that", "it", "is", "writable", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/core/src/main/java/com/meltmedia/cadmium/core/FileSystemManager.java#L418-L430
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/TupleHashPartitioner.java
TupleHashPartitioner.getPartition
@Override public int getPartition(DatumWrapper<ITuple> key, NullWritable value, int numPartitions) { if(numPartitions == 1) { // in this case the schema is not checked if it's valid return 0; } else { ITuple tuple = key.datum(); String sourceName = tuple.getSchema().getName(); Integer schemaId = tupleMRConfig.getSchemaIdByName(sourceName); if(schemaId == null) { throw new RuntimeException("Schema name '" + sourceName + "' is unknown. Known schemas are : " + tupleMRConfig.getIntermediateSchemaNames()); } int[] fieldsToPartition = serInfo.getPartitionFieldsIndexes().get(schemaId); if(fieldsToPartition.length == 0) { throw new RuntimeException("Fields to partition is 0. Something has been wrongly configured."); } return (partialHashCode(tuple, fieldsToPartition) & Integer.MAX_VALUE) % numPartitions; } }
java
@Override public int getPartition(DatumWrapper<ITuple> key, NullWritable value, int numPartitions) { if(numPartitions == 1) { // in this case the schema is not checked if it's valid return 0; } else { ITuple tuple = key.datum(); String sourceName = tuple.getSchema().getName(); Integer schemaId = tupleMRConfig.getSchemaIdByName(sourceName); if(schemaId == null) { throw new RuntimeException("Schema name '" + sourceName + "' is unknown. Known schemas are : " + tupleMRConfig.getIntermediateSchemaNames()); } int[] fieldsToPartition = serInfo.getPartitionFieldsIndexes().get(schemaId); if(fieldsToPartition.length == 0) { throw new RuntimeException("Fields to partition is 0. Something has been wrongly configured."); } return (partialHashCode(tuple, fieldsToPartition) & Integer.MAX_VALUE) % numPartitions; } }
[ "@", "Override", "public", "int", "getPartition", "(", "DatumWrapper", "<", "ITuple", ">", "key", ",", "NullWritable", "value", ",", "int", "numPartitions", ")", "{", "if", "(", "numPartitions", "==", "1", ")", "{", "// in this case the schema is not checked if it...
to perform hashCode of strings
[ "to", "perform", "hashCode", "of", "strings" ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/TupleHashPartitioner.java#L42-L63
train
datasalt/pangool
core/src/main/java/com/datasalt/pangool/tuplemr/mapred/TupleHashPartitioner.java
TupleHashPartitioner.partialHashCode
public int partialHashCode(ITuple tuple, int[] fields) { int result = 0; for(int field : fields) { Object o = tuple.get(field); if(o == null) { // nulls don't account for hashcode continue; } int hashCode; if(o instanceof String) { // since String.hashCode() != Utf8.hashCode() HELPER_UTF8.set((String) o); hashCode = HELPER_UTF8.hashCode(); } else if(o instanceof Text) { HELPER_UTF8.set((Text) o); hashCode = HELPER_UTF8.hashCode(); } else if(o instanceof byte[]){ hashCode = hashBytes((byte[])o,0,((byte[]) o).length); } else if(o instanceof ByteBuffer){ ByteBuffer buffer = (ByteBuffer)o; int offset = buffer.arrayOffset() + buffer.position(); int length = buffer.limit() - buffer.position(); hashCode = hashBytes(buffer.array(),offset,length); } else { hashCode = o.hashCode(); } result = result * 31 + hashCode; } return result; }
java
public int partialHashCode(ITuple tuple, int[] fields) { int result = 0; for(int field : fields) { Object o = tuple.get(field); if(o == null) { // nulls don't account for hashcode continue; } int hashCode; if(o instanceof String) { // since String.hashCode() != Utf8.hashCode() HELPER_UTF8.set((String) o); hashCode = HELPER_UTF8.hashCode(); } else if(o instanceof Text) { HELPER_UTF8.set((Text) o); hashCode = HELPER_UTF8.hashCode(); } else if(o instanceof byte[]){ hashCode = hashBytes((byte[])o,0,((byte[]) o).length); } else if(o instanceof ByteBuffer){ ByteBuffer buffer = (ByteBuffer)o; int offset = buffer.arrayOffset() + buffer.position(); int length = buffer.limit() - buffer.position(); hashCode = hashBytes(buffer.array(),offset,length); } else { hashCode = o.hashCode(); } result = result * 31 + hashCode; } return result; }
[ "public", "int", "partialHashCode", "(", "ITuple", "tuple", ",", "int", "[", "]", "fields", ")", "{", "int", "result", "=", "0", ";", "for", "(", "int", "field", ":", "fields", ")", "{", "Object", "o", "=", "tuple", ".", "get", "(", "field", ")", ...
Calculates a combinated hashCode using the specified number of fields.
[ "Calculates", "a", "combinated", "hashCode", "using", "the", "specified", "number", "of", "fields", "." ]
bfd312dd78cba03febaf7988ae96a3d4bc585408
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/tuplemr/mapred/TupleHashPartitioner.java#L87-L114
train
meltmedia/cadmium
servlets/src/main/java/com/meltmedia/cadmium/servlets/ErrorPageFilter.java
ErrorPageFilter.init
@Override public void init(FilterConfig config) throws ServletException { if(config.getInitParameter("ignorePrefix") != null) { ignorePath = config.getInitParameter("ignorePrefix"); } }
java
@Override public void init(FilterConfig config) throws ServletException { if(config.getInitParameter("ignorePrefix") != null) { ignorePath = config.getInitParameter("ignorePrefix"); } }
[ "@", "Override", "public", "void", "init", "(", "FilterConfig", "config", ")", "throws", "ServletException", "{", "if", "(", "config", ".", "getInitParameter", "(", "\"ignorePrefix\"", ")", "!=", "null", ")", "{", "ignorePath", "=", "config", ".", "getInitPara...
Configures the ignore prefix.
[ "Configures", "the", "ignore", "prefix", "." ]
bca585030e141803a73b58abb128d130157b6ddf
https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/ErrorPageFilter.java#L81-L87
train