code
stringlengths
73
34.1k
label
stringclasses
1 value
@SuppressWarnings("rawtypes") @Override public int compare(ITuple w1, ITuple w2) { int schemaId1 = tupleMRConf.getSchemaIdByName(w1.getSchema().getName()); int schemaId2 = tupleMRConf.getSchemaIdByName(w2.getSchema().getName()); int[] indexes1 = serInfo.getGroupSchemaIndexTranslation(schemaId1); int[] indexe...
java
public void encodeNBitUnsignedInteger(int b, int n) throws IOException { if (b < 0 || n < 0) { throw new IllegalArgumentException( "Encode negative value as unsigned integer is invalid!"); } assert (b >= 0); assert (n >= 0); ostream.writeBits(b, n); }
java
public static Schema subSetOf(Schema schema, String... subSetFields) { return subSetOf("subSetSchema" + (COUNTER++), schema, subSetFields); }
java
public static Schema subSetOf(String newName, Schema schema, String... subSetFields) { List<Field> newSchema = new ArrayList<Field>(); for(String subSetField: subSetFields) { newSchema.add(schema.getField(subSetField)); } return new Schema(newName, newSchema); }
java
public static Schema superSetOf(Schema schema, Field... newFields) { return superSetOf("superSetSchema" + (COUNTER++), schema, newFields); }
java
public static Schema superSetOf(String newName, Schema schema, Field... newFields) { List<Field> newSchema = new ArrayList<Field>(); newSchema.addAll(schema.getFields()); for(Field newField: newFields) { newSchema.add(newField); } return new Schema(newName, newSchema); }
java
@PostConstruct public void setupScheduler() { for(SchedulerTask task : tasks) { if(task.getDelay() > 0 && task.getInterval() > 0) { executor.scheduleWithFixedDelay(task.getTask(), task.getDelay(), task.getInterval(), task.getTimeUnit()); } else if(task.isImmediate() && task.getInterval() > 0) ...
java
public File getAlternateContentDirectory(String userAgent) { Configuration config = liveConfig; for(AlternateContent configuration: config.configs) { try { if(configuration.compiledPattern.matcher(userAgent).matches()) { return new File(config.metaDir, configuration.getContentDirectory()...
java
public void addIntermediateSchema(Schema schema) throws TupleMRException { if (schemaAlreadyExists(schema.getName())) { throw new TupleMRException("There's a schema with that name '" + schema.getName() + "'"); } schemas.add(schema); }
java
public void setOrderBy(OrderBy ordering) throws TupleMRException { failIfNull(ordering, "OrderBy can't be null"); failIfEmpty(ordering.getElements(), "OrderBy can't be empty"); failIfEmpty(schemas, "Need to specify source schemas"); failIfEmpty(groupByFields, "Need to specify group by fields"); if (...
java
public void setSpecificOrderBy(String schemaName, OrderBy ordering) throws TupleMRException { // TODO failIfNull(schemaName, "Not able to set specific orderBy for null source"); if (!schemaAlreadyExists(schemaName)) { throw new TupleMRException("Unknown source '" + schemaName + "' in s...
java
private void initComparators() { TupleMRConfigBuilder.initializeComparators(context.getHadoopContext() .getConfiguration(), tupleMRConfig); customComparators = new RawComparator<?>[maxDepth + 1]; for(int i = minDepth; i <= maxDepth; i++) { SortElement element = tupleMRConfig.getCommonCriteria().getElemen...
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public Record toRecord(ITuple tuple, Record reuse) throws IOException { Record record = reuse; if (record == null){ record = new Record(avroSchema); } if (schemaValidation && !tuple.getSchema().equals(pangoolSchema)){ throw new IOException("Tuple '"+tuple +...
java
public Properties appendToDefaultProperties(File configFile) { if(defaultProperties != null && configFile.canRead()) { defaultProperties = appendProperties(defaultProperties, configFile); } return defaultProperties; }
java
public Properties appendProperties(Properties properties, File configFile) { if(!configFile.exists()) { return properties; } return reader.appendProperties(properties, configFile, log); }
java
public Properties getSystemProperties() { Properties properties = new Properties(); properties.putAll(System.getenv()); properties.putAll(System.getProperties()); return properties; }
java
public Properties getPropertiesByContext(ServletContext context, String path) { return reader.getProperties(context, path, log); }
java
public synchronized void persistProperties(Properties properties, File propsFile, String message) { Properties toWrite = new Properties(); for(String key : properties.stringPropertyNames()) { if(System.getProperties().containsKey(key) && !properties.getProperty(key).equals(System.getProperty(key))) { ...
java
public void makeConfigParserLive() { if(stagedConfigParser != null) { notifyListeners(listeners, stagedConfigParser, log); liveConfigParser = stagedConfigParser; latch.countDown(); } }
java
private static Class<?>[] getListenerGenericTypes(Class<?> listenerClass, Logger log) { List<Class<?>> configClasses = new ArrayList<Class<?>>(); Type[] typeVars = listenerClass.getGenericInterfaces(); if(typeVars != null) { for(Type interfaceClass : typeVars) { if(interfaceClass instanceof Pa...
java
protected void doSanityCheck() throws EXIException { // Self-contained elements do not work with re-ordered if (fidelityOptions.isFidelityEnabled(FidelityOptions.FEATURE_SC) && (codingMode == CodingMode.COMPRESSION || codingMode == CodingMode.PRE_COMPRESSION)) { throw new EXIException( "(Pre-)Com...
java
static public int zipDirectory(final Configuration conf, final ZipOutputStream zos, final String baseName, final String root, final Path itemToZip) throws IOException { LOG.info(String.format("zipDirectory: %s %s %s", baseName, root, itemToZip)); LocalFileSystem localFs = FileSystem.getLocal(conf); int count...
java
public static void addListener(Document doc, Element root) { Element listener = doc.createElement("listener"); Element listenerClass = doc.createElement("listener-class"); listener.appendChild(listenerClass); listenerClass.appendChild(doc .createTextNode("org.apache.shiro.web.env.EnvironmentLoad...
java
public static void addContextParam(Document doc, Element root) { Element ctxParam = doc.createElement("context-param"); Element paramName = doc.createElement("param-name"); paramName.appendChild(doc.createTextNode("shiroConfigLocations")); ctxParam.appendChild(paramName); Element paramValue = doc.cr...
java
public static void addEnvContextParam(Document doc, Element root) { Element ctxParam = doc.createElement("context-param"); Element paramName = doc.createElement("param-name"); paramName.appendChild(doc.createTextNode("shiroEnvironmentClass")); ctxParam.appendChild(paramName); Element paramValue = do...
java
public static void addFilter(Document doc, Element root) { Element filter = doc.createElement("filter"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filter.appendChild(filterName); Element filterClass = doc.createElement("filter-c...
java
public static void addFilterMapping(Document doc, Element root) { Element filterMapping = doc.createElement("filter-mapping"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filterMapping.appendChild(filterName); Element urlPattern =...
java
public static void addDispatchers(Document doc, Element filterMapping, String... names) { if (names != null) { for (String name : names) { Element dispatcher = doc.createElement("dispatcher"); dispatcher.appendChild(doc.createTextNode(name)); filterMapping.appendChild(dispatcher)...
java
public static void storeXmlDocument(ZipOutputStream outZip, ZipEntry jbossWeb, Document doc) throws IOException, TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { jbossWeb = new ZipEntry(jbossWeb.getName()); outZip.putNextEntry(jbossWeb); Tran...
java
public static void removeNodesByTagName(Element doc, String tagname) { NodeList nodes = doc.getElementsByTagName(tagname); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); doc.removeChild(n); } }
java
public static void storeProperties(ZipOutputStream outZip, ZipEntry cadmiumPropertiesEntry, Properties cadmiumProps, List<String> newWarNames) throws IOException { ZipEntry newCadmiumEntry = new ZipEntry(cadmiumPropertiesEntry.getName()); outZip.putNextEntry(newCadmiumEntry); cadmiumProps.store(...
java
public static String getWarName( ServletContext context ) { String[] pathSegments = context.getRealPath("/WEB-INF/web.xml").split("/"); String warName = pathSegments[pathSegments.length - 3]; if(!warName.endsWith(".war")) { URL webXml = WarUtils.class.getClassLoader().getResource("/cadmium-version.pro...
java
public final int decodeUnsignedInteger() throws IOException { // 0XXXXXXX ... 1XXXXXXX 1XXXXXXX int result = decode(); // < 128: just one byte, optimal case // ELSE: multiple bytes... if (result >= 128) { result = (result & 127); int mShift = 7; int b; do { // 1. Read the next octet b =...
java
public DateTimeValue decodeDateTimeValue(DateTimeType type) throws IOException { int year = 0, monthDay = 0, time = 0, fractionalSecs = 0; switch (type) { case gYear: // Year, [Time-Zone] year = decodeInteger() + DateTimeValue.YEAR_OFFSET; break; case gYearMonth: // Year, MonthDay, [TimeZone] case d...
java
public Set<String> configureJob(Job job) throws FileNotFoundException, IOException { Set<String> instanceFiles = new HashSet<String>(); for (Map.Entry<Path, List<Input>> entry : multiInputs.entrySet()) { for (int inputId = 0; inputId < entry.getValue().size(); inputId++) { Input input = entry.getV...
java
public static void waitForToken(String siteUri, String token, Long since, Long timeout) throws Exception { if(!siteUri.endsWith("/system/history")) { siteUri += "/system/history"; } siteUri += "/" + token; if(since != null) { siteUri += "/" + since; } HttpClient httpClient = ht...
java
public static List<HistoryEntry> getHistory(String siteUri, int limit, boolean filter, String token) throws URISyntaxException, IOException, ClientProtocolException, Exception { if(!siteUri.endsWith("/system/history")) { siteUri += "/system/history"; } List<HistoryEntry> history = null; ...
java
private static void printComments(String comment) { int index = 0; int nextIndex = 154; while(index < comment.length()) { nextIndex = nextIndex <= comment.length() ? nextIndex : comment.length(); String commentSegment = comment.substring(index, nextIndex); int lastSpace = commentSegment.la...
java
private static String formatTimeLive(long timeLive) { String timeString = "ms"; timeString = (timeLive % 1000) + timeString; timeLive = timeLive / 1000; if(timeLive > 0) { timeString = (timeLive % 60) + "s" + timeString; timeLive = timeLive / 60; if(timeLive > 0) { timeString =...
java
@Override public boolean isSecure(HttpServletRequest request) { String proto = request.getHeader(X_FORWARED_PROTO); if( proto != null ) return proto.equalsIgnoreCase(HTTPS_PROTOCOL); return super.isSecure(request); }
java
@Override public String getProtocol(HttpServletRequest request) { String proto = request.getHeader(X_FORWARED_PROTO); if( proto != null ) return proto; return super.getProtocol(request); }
java
@Override public int getPort(HttpServletRequest request) { String portValue = request.getHeader(X_FORWARED_PORT); if( portValue != null ) return Integer.parseInt(portValue); return super.getPort(request); }
java
public String contentTypeOf( String path ) throws IOException { File file = findFile(path); return lookupMimeType(file.getName()); }
java
public File findFile( String path ) throws IOException { File base = new File(getBasePath()); File pathFile = new File(base, "."+path); if( !pathFile.exists()) throw new FileNotFoundException("No file or directory at "+pathFile.getCanonicalPath()); if( pathFile.isFile()) return pathFile; pathFile = new F...
java
public void setGitService(GitService git) { if(git != null) { logger.debug("Setting git service"); this.git = git; latch.countDown(); } }
java
@Override public void close() throws IOException { if(git != null) { IOUtils.closeQuietly(git); git = null; } latch.countDown(); try { latch.notifyAll(); } catch(Exception e) { logger.trace("Failed to notifyAll"); } try { locker.notifyAll(); } catch(Except...
java
public int read(byte[] b, int off, int len) throws IOException { ensureOpen(); if ((off | len | (off + len) | (b.length - (off + len))) < 0) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } try { int n; while ((n = inf.inflate(b, off, len)) == 0) { if (inf.finished()...
java
public static void writeTXT(String string, File file) throws IOException { BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(string); out.close(); }
java
public void setOption(String key) throws UnsupportedOption { if (key.equals(IGNORE_SCHEMA_ID)) { options.add(key); } else { throw new UnsupportedOption("DecodingOption '" + key + "' is unknown!"); } }
java
public void encodeNBitUnsignedInteger(int b, int n) throws IOException { if (b < 0 || n < 0) { throw new IllegalArgumentException( "Negative value as unsigned integer!"); } assert (b >= 0); assert (n >= 0); if (n == 0) { // 0 bytes } else if (n < 9) { // 1 byte encode(b & 0xff); } else i...
java
@SuppressWarnings("rawtypes") public void addClass(String name, Class mainClass, String description) throws Throwable { programs.put(name, new ProgramDescription(mainClass, description)); }
java
public void driver(String[] args) throws Throwable { // Make sure they gave us a program name. if(args.length == 0) { System.out.println("An example program must be given as the" + " first argument."); printUsage(programs); throw new IllegalArgumentException("An example program must be given " + "as the fi...
java
public void ser(Object datum, OutputStream output) throws IOException { Map<Class, Serializer> serializers = cachedSerializers.get(); Serializer ser = serializers.get(datum.getClass()); if(ser == null) { ser = serialization.getSerializer(datum.getClass()); if(ser == null) { throw new IOException("Serial...
java
public <T> T deser(Object obj, InputStream in) throws IOException { Map<Class, Deserializer> deserializers = cachedDeserializers.get(); Deserializer deSer = deserializers.get(obj.getClass()); if(deSer == null) { deSer = serialization.getDeserializer(obj.getClass()); deserializers.put(obj.getClass(), deSer);...
java
public <T> T deser(Object obj, byte[] array, int offset, int length) throws IOException { Map<Class, Deserializer> deserializers = cachedDeserializers.get(); Deserializer deSer = deserializers.get(obj.getClass()); if(deSer == null) { deSer = serialization.getDeserializer(obj.getClass()); deserializers.put(o...
java
public static void copyPartialContent(InputStream in, OutputStream out, Range r) throws IOException { IOUtils.copyLarge(in, out, r.start, r.length); }
java
public static Long calculateRangeLength(FileRequestContext context, Range range) { if(range.start == -1) range.start = 0; if(range.end == -1) range.end = context.file.length() - 1; range.length = range.end - range.start + 1; return range.length; }
java
protected boolean checkAccepts(FileRequestContext context) throws IOException { if (!canAccept(context.request.getHeader(ACCEPT_HEADER), false, context.contentType)) { notAcceptable(context); return true; } if (!(canAccept(context.request.getHeader(ACCEPT_ENCODING_HEADER), false, "identity"...
java
public boolean locateFileToServe( FileRequestContext context ) throws IOException { context.file = new File( contentDir, context.path); // if the path is not on the file system, send a 404. if( !context.file.exists() ) { context.response.sendError(HttpServletResponse.SC_NOT_FOUND); return t...
java
public static void invalidRanges(FileRequestContext context) throws IOException { context.response.setHeader(CONTENT_RANGE_HEADER, "*/" + context.file.length()); context.response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); }
java
public static boolean canAccept(String headerValue, boolean strict, String type) { if(headerValue != null && type != null) { String availableTypes[] = headerValue.split(","); for(String availableType : availableTypes) { String typeParams[] = availableType.split(";"); double qValue = 1.0...
java
private static boolean hasMatch(String[] typeParams, String... type) { boolean matches = false; for(String t : type) { for(String typeParam : typeParams) { if(typeParam.contains("/")) { String typePart = typeParam.replace("*", ""); if(t.startsWith(typePart) || t.endsWith(typePa...
java
public boolean handleWelcomeRedirect( FileRequestContext context ) throws IOException { if( context.file.isFile() && context.file.getName().equals("index.html")) { resolveContentType(context); String location = context.path.replaceFirst("/index.html\\Z", ""); if( location.isEmpty() ) location = "/...
java
public void resolveContentType(FileRequestContext context) { String contentType = lookupMimeType(context.file.getName()); if(contentType != null) { context.contentType = contentType; if(contentType.equals("text/html")) { context.contentType += ";charset=UTF-8"; } } }
java
protected void flushBuffer() throws IOException { if (capacity == 0) { ostream.write(buffer); capacity = BITS_IN_BYTE; buffer = 0; len++; } }
java
public void align() throws IOException { if (capacity < BITS_IN_BYTE) { ostream.write(buffer << capacity); capacity = BITS_IN_BYTE; buffer = 0; len++; } }
java
public void writeBits(int b, int n) throws IOException { if (n <= capacity) { // all bits fit into the current buffer buffer = (buffer << n) | (b & (0xff >> (BITS_IN_BYTE - n))); capacity -= n; if (capacity == 0) { ostream.write(buffer); capacity = BITS_IN_BYTE; len++; } } else { // fi...
java
protected void writeDirectBytes(byte[] b, int off, int len) throws IOException { ostream.write(b, off, len); len += len; }
java
private static String adaptNumber(String number) { String n = number.trim(); if(n.startsWith("+")) { return n.substring(1); } else { return n; } }
java
private void persistRealmChanges() { configManager.persistProperties(realm.getProperties(), new File(applicationContentDir, PersistablePropertiesRealm.REALM_FILE_NAME), null); }
java
public static void stringToFile(FileSystem fs, Path path, String string) throws IOException { OutputStream os = fs.create(path, true); PrintWriter pw = new PrintWriter(os); pw.append(string); pw.close(); }
java
public static String fileToString(FileSystem fs, Path path) throws IOException { if(!fs.exists(path)) { return null; } InputStream is = fs.open(path); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); char[] buff = new char[256]; StringBuilder sb = new Str...
java
public static HashMap<Integer, Integer> readIntIntMap(Path path, FileSystem fs) throws IOException { SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, fs.getConf()); IntWritable topic = new IntWritable(); IntWritable value = new IntWritable(); HashMap<Integer, Integer> ret = new HashMap<Inte...
java
static Scenario scenario(String text) { reset(); final Scenario scenario = new Scenario(text); sRoot = scenario; return scenario; }
java
static Given given(String text) { reset(); final Given given = new Given(text); sRoot = given; return given; }
java
public static void insertMessage(Throwable onObject, String msg) { try { Field field = Throwable.class.getDeclaredField("detailMessage"); //Method("initCause", new Class[]{Throwable.class}); field.setAccessible(true); if (onObject.getMessage() != null) { field...
java
public Stylesheet parse() throws ParseException { while (tokenizer.more()) { if (tokenizer.current().isKeyword(KEYWORD_IMPORT)) { // Handle @import parseImport(); } else if (tokenizer.current().isKeyword(KEYWORD_MIXIN)) { // Handle @mixin ...
java
private Section parseSection(boolean mediaQuery) { Section section = new Section(); parseSectionSelector(mediaQuery, section); tokenizer.consumeExpectedSymbol("{"); while (tokenizer.more()) { if (tokenizer.current().isSymbol("}")) { tokenizer.consumeExpectedSy...
java
private Object[] getValues(Map<String, Object> annotationAtts) { if (null == annotationAtts) { throw new DuraCloudRuntimeException("Arg annotationAtts is null."); } List<Object> values = new ArrayList<Object>(); for (String key : annotationAtts.keySet()) { Objec...
java
private Set<Role> getOtherRolesArg(Object[] arguments) { if (arguments.length <= NEW_ROLES_INDEX) { log.error("Illegal number of args: " + arguments.length); } Set<Role> roles = new HashSet<Role>(); Object[] rolesArray = (Object[]) arguments[NEW_ROLES_INDEX]; if (nul...
java
private Long getOtherUserIdArg(Object[] arguments) { if (arguments.length <= OTHER_USER_ID_INDEX) { log.error("Illegal number of args: " + arguments.length); } return (Long) arguments[OTHER_USER_ID_INDEX]; }
java
private Long getUserIdArg(Object[] arguments) { if (arguments.length <= USER_ID_INDEX) { log.error("Illegal number of args: " + arguments.length); } return (Long) arguments[USER_ID_INDEX]; }
java
private Long getAccountIdArg(Object[] arguments) { if (arguments.length <= ACCT_ID_INDEX) { log.error("Illegal number of args: " + arguments.length); } return (Long) arguments[ACCT_ID_INDEX]; }
java
public static Expression rgb(Generator generator, FunctionCall input) { return new Color(input.getExpectedIntParam(0), input.getExpectedIntParam(1), input.getExpectedIntParam(2)); }
java
public static Expression rgba(Generator generator, FunctionCall input) { if (input.getParameters().size() == 4) { return new Color(input.getExpectedIntParam(0), input.getExpectedIntParam(1), input.getExpectedIntParam(2), ...
java
public static Expression adjusthue(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int changeInDegrees = input.getExpectedIntParam(1); Color.HSL hsl = color.getHSL(); hsl.setH(hsl.getH() + changeInDegrees); return hsl.getColor(); }
java
public static Expression lighten(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int increase = input.getExpectedIntParam(1); return changeLighteness(color, increase); }
java
public static Expression alpha(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); return new Number(color.getA(), String.valueOf(color.getA()), ""); }
java
public static Expression darken(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int decrease = input.getExpectedIntParam(1); return changeLighteness(color, -decrease); }
java
public static Expression saturate(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int increase = input.getExpectedIntParam(1); return changeSaturation(color, increase); }
java
public static Expression desaturate(Generator generator, FunctionCall input) { Color color = input.getExpectedColorParam(0); int decrease = input.getExpectedIntParam(1); return changeSaturation(color, -decrease); }
java
@SuppressWarnings("squid:S00100") public static Expression fade_out(Generator generator, FunctionCall input) { return opacify(generator, input); }
java
public static Expression mix(Generator generator, FunctionCall input) { Color color1 = input.getExpectedColorParam(0); Color color2 = input.getExpectedColorParam(1); float weight = input.getParameters().size() > 2 ? input.getExpectedFloatParam(2) : 0.5f; return new Color((int) Math.round...
java
public Output lineBreak() throws IOException { writer.write("\n"); if (!skipOptionalOutput) { for (int i = 0; i < indentLevel; i++) { writer.write(indentDepth); } } return this; }
java
@SuppressWarnings("squid:S1244") public HSL getHSL() { // Convert the RGB values to the range 0-1 double red = r / 255.0; double green = g / 255.0; double blue = b / 255.0; // Find the minimum and maximum values of R, G and B. double min = Math.min(red, Math.min(gree...
java
public String getMediaQuery(Scope scope, Generator gen) { StringBuilder sb = new StringBuilder(); for (Expression expr : mediaQueries) { if (sb.length() > 0) { sb.append(" and "); } sb.append(expr.eval(scope, gen)); } return sb.toString...
java
public String getSelectorString() { StringBuilder sb = new StringBuilder(); for (List<String> selector : selectors) { if (sb.length() > 0) { sb.append(","); } for (String s : selector) { if (sb.length() > 0) { sb.app...
java
public void importStylesheet(Stylesheet sheet) { if (sheet == null) { return; } if (importedSheets.contains(sheet.getName())) { return; } importedSheets.add(sheet.getName()); for (String imp : sheet.getImports()) { importStylesheet(imp)...
java
protected final boolean isGroupNameValid(String name) { if (name == null) { return false; } if (!name.startsWith(DuracloudGroup.PREFIX)) { return false; } if (DuracloudGroup.PUBLIC_GROUP_NAME.equalsIgnoreCase(name)) { return false; } ...
java
public List<DuplicationInfo> getDupIssues() { List<DuplicationInfo> dupIssues = new LinkedList<>(); for (DuplicationInfo dupInfo : dupInfos.values()) { if (dupInfo.hasIssues()) { dupIssues.add(dupInfo); } } return dupIssues; }
java