_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q174700
InvDataset.findDatasetByName
test
public InvDatasetImpl findDatasetByName(String name) { for (InvDataset ds : getDatasets()) { if (ds.getName().equals(name)) return (InvDatasetImpl) ds; } return null; }
java
{ "resource": "" }
q174701
InvDataset.getParentCatalog
test
public InvCatalog getParentCatalog() { if (catalog != null) return catalog; return (parent != null) ? parent.getParentCatalog() : null; }
java
{ "resource": "" }
q174702
InvDataset.getMetadata
test
public java.util.List<InvMetadata> getMetadata(thredds.catalog.MetadataType want) { List<InvMetadata> result = new ArrayList<InvMetadata>(); for (InvMetadata m : getMetadata()) { MetadataType mtype = MetadataType.getType(m.getMetadataType()); if (mtype == want) result.add(m); } return result; }
java
{ "resource": "" }
q174703
InvDataset.findService
test
public InvService findService(String name) { if (name == null) return null; // search local (but expanded) services for (InvService p : services) { if (p.getName().equals(name)) return p; } // not found, look in parent if (parent != null) return parent.findService(name); return (catalog == null) ? null : catalog.findService(name); }
java
{ "resource": "" }
q174704
InvDataset.getVariables
test
public ThreddsMetadata.Variables getVariables(String vocab) { ThreddsMetadata.Variables result = new ThreddsMetadata.Variables(vocab, null, null, null, null); if (variables == null) return result; for (ThreddsMetadata.Variables vs : variables) { if (vs.getVocabulary().equals(vocab)) result.getVariableList().addAll(vs.getVariableList()); } return result; }
java
{ "resource": "" }
q174705
CatalogUtils.findAllCatRefsInDatasetTree
test
public static List<InvCatalogRef> findAllCatRefsInDatasetTree( List<InvDataset> datasets, StringBuilder log, boolean onlyRelativeUrls ) { List<InvCatalogRef> catRefList = new ArrayList<InvCatalogRef>(); for ( InvDataset invds : datasets ) { InvDatasetImpl curDs = (InvDatasetImpl) invds; if ( curDs instanceof InvDatasetScan) continue; if ( curDs instanceof InvCatalogRef ) { InvCatalogRef catRef = (InvCatalogRef) curDs; String name = catRef.getName(); String href = catRef.getXlinkHref(); URI uri; try { uri = new URI( href ); } catch ( URISyntaxException e ) { log.append( log.length() > 0 ? "\n" : "" ) .append( "***WARN - CatalogRef [").append(name) .append("] with bad HREF [" ).append( href ).append( "] " ); continue; } if ( onlyRelativeUrls && uri.isAbsolute() ) continue; catRefList.add( catRef ); continue; } if ( curDs.hasNestedDatasets() ) catRefList.addAll( findAllCatRefsInDatasetTree( curDs.getDatasets(), log, onlyRelativeUrls ) ); } return catRefList; }
java
{ "resource": "" }
q174706
CatalogUtils.escapePathForURL
test
static public String escapePathForURL(String path) { try { return new URI(null, null, path, null).toString(); } catch (URISyntaxException e) { return path; } }
java
{ "resource": "" }
q174707
WRFEta.addStagger
test
private ArrayDouble.D3 addStagger(ArrayDouble.D3 array, int dimIndex) { //ADD: assert 0<=dimIndex<=2 int[] shape = array.getShape(); int[] newShape = new int[3]; System.arraycopy(shape, 0, newShape, 0, 3); newShape[dimIndex]++; int ni = newShape[0]; int nj = newShape[1]; int nk = newShape[2]; ArrayDouble.D3 newArray = new ArrayDouble.D3(ni, nj, nk); //Index newIndex = newArray.getIndex(); //extract 1d array to be extended int n = shape[dimIndex]; //length of extracted array double[] d = new double[n]; //tmp array to hold extracted values int[] eshape = new int[3]; //shape of extracted array int[] neweshape = new int[3]; //shape of new array slice to write into for (int i = 0; i < 3; i++) { eshape[i] = (i == dimIndex) ? n : 1; neweshape[i] = (i == dimIndex) ? n + 1 : 1; } int[] origin = new int[3]; try { //loop through the other 2 dimensions and "extrapinterpolate" the other for (int i = 0; i < ((dimIndex == 0) ? 1 : ni); i++) { for (int j = 0; j < ((dimIndex == 1) ? 1 : nj); j++) { for (int k = 0; k < ((dimIndex == 2) ? 1 : nk); k++) { origin[0] = i; origin[1] = j; origin[2] = k; IndexIterator it = array.section(origin, eshape).getIndexIterator(); for (int l = 0; l < n; l++) { d[l] = it.getDoubleNext(); //get the original values } double[] d2 = extrapinterpolate(d); //compute new values //define slice of new array to write into IndexIterator newit = newArray.section(origin, neweshape).getIndexIterator(); for (int l = 0; l < n + 1; l++) { newit.setDoubleNext(d2[l]); } } } } } catch (InvalidRangeException e) { //ADD: report error? return null; } return newArray; }
java
{ "resource": "" }
q174708
WRFEta.extrapinterpolate
test
private double[] extrapinterpolate(double[] array) { int n = array.length; double[] d = new double[n + 1]; //end points from linear extrapolation //equations confirmed by Christopher Lindholm d[0] = 1.5 * array[0] - 0.5 * array[1]; d[n] = 1.5 * array[n - 1] - 0.5 * array[n - 2]; //inner points from simple average for (int i = 1; i < n; i++) { d[i] = 0.5 * (array[i - 1] + array[i]); } return d; }
java
{ "resource": "" }
q174709
AlbersEqualArea.computeRho
test
private double computeRho(double lat) { return earth_radius * Math.sqrt(C - 2 * n * Math.sin(lat)) / n; }
java
{ "resource": "" }
q174710
GempakStationFileIOSP.getDetailInfo
test
public String getDetailInfo() { Formatter ff = new Formatter(); ff.format("%s", super.getDetailInfo()); ff.format("%s", parseInfo); return ff.toString(); }
java
{ "resource": "" }
q174711
GempakStationFileIOSP.makeStructure
test
protected Structure makeStructure(String partName, List<Dimension> dimensions, boolean includeMissing) { List<GempakParameter> params = gemreader.getParameters(partName); if (params == null) { return null; } Structure sVar = new Structure(ncfile, null, null, partName); sVar.setDimensions(dimensions); for (GempakParameter param : params) { sVar.addMemberVariable(makeParamVariable(param, null)); } if (includeMissing) { sVar.addMemberVariable(makeMissingVariable()); } return sVar; }
java
{ "resource": "" }
q174712
GempakStationFileIOSP.makeMissingVariable
test
protected Variable makeMissingVariable() { Variable var = new Variable(ncfile, null, null, MISSING_VAR); var.setDataType(DataType.BYTE); var.setDimensions((List<Dimension>) null); var.addAttribute(new Attribute("description", "missing flag - 1 means all params are missing")); var.addAttribute(new Attribute(CDM.MISSING_VALUE, (byte) 1)); return var; }
java
{ "resource": "" }
q174713
GempakStationFileIOSP.makeParamVariable
test
protected Variable makeParamVariable(GempakParameter param, List<Dimension> dims) { Variable var = new Variable(ncfile, null, null, param.getName()); var.setDataType(DataType.FLOAT); var.setDimensions(dims); var.addAttribute(new Attribute(CDM.LONG_NAME, param.getDescription())); String units = param.getUnit(); if ((units != null) && !units.equals("")) { var.addAttribute(new Attribute(CDM.UNITS, units)); } var.addAttribute(new Attribute(CDM.MISSING_VALUE, RMISS)); return var; }
java
{ "resource": "" }
q174714
GempakStationFileIOSP.addGlobalAttributes
test
protected void addGlobalAttributes() { // global stuff ncfile.addAttribute(null, new Attribute(CDM.CONVENTIONS, getConventions())); String fileType = "GEMPAK " + gemreader.getFileType(); ncfile.addAttribute(null, new Attribute("file_format", fileType)); ncfile.addAttribute(null, new Attribute("history", "Direct read of " + fileType + " into NetCDF-Java API")); ncfile.addAttribute(null, new Attribute(CF.FEATURE_TYPE, getCFFeatureType())); }
java
{ "resource": "" }
q174715
GempakStationFileIOSP.getStnVarSize
test
protected int getStnVarSize(String name) { int size = -1; for (int i = 0; i < stnVarNames.length; i++) { if (name.equals(stnVarNames[i])) { size = stnVarSizes[i]; break; } } return size; }
java
{ "resource": "" }
q174716
GempakStationFileIOSP.get1DArray
test
private Array get1DArray(DataType type, int len) { Array varArray = null; if (type.equals(DataType.FLOAT)) { varArray = new ArrayFloat.D1(len); } else if (type.equals(DataType.DOUBLE)) { varArray = new ArrayDouble.D1(len); } else if (type.equals(DataType.INT)) { varArray = new ArrayInt.D1(len, false); } return varArray; }
java
{ "resource": "" }
q174717
CeParser.yy_lr_goto_state_
test
private int yy_lr_goto_state_ (int yystate, int yysym) { int yyr = yypgoto_[yysym - yyntokens_] + yystate; if (0 <= yyr && yyr <= yylast_ && yycheck_[yyr] == yystate) return yytable_[yyr]; else return yydefgoto_[yysym - yyntokens_]; }
java
{ "resource": "" }
q174718
CeParser.yysyntax_error
test
private String yysyntax_error (int yystate, int tok) { if (yyErrorVerbose) { /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in tok) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. (However, yychar is currently out of scope during semantic actions.) - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (tok != yyempty_) { /* FIXME: This method of building the message is not compatible with internationalization. */ StringBuffer res = new StringBuffer ("syntax error, unexpected "); res.append (yytnamerr_ (yytname_[tok])); int yyn = yypact_[yystate]; if (!yy_pact_value_is_default_ (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = yylast_ - yyn + 1; int yyxend = yychecklim < yyntokens_ ? yychecklim : yyntokens_; int count = 0; for (int x = yyxbegin; x < yyxend; ++x) if (yycheck_[x + yyn] == x && x != yyterror_ && !yy_table_value_is_error_ (yytable_[x + yyn])) ++count; if (count < 5) { count = 0; for (int x = yyxbegin; x < yyxend; ++x) if (yycheck_[x + yyn] == x && x != yyterror_ && !yy_table_value_is_error_ (yytable_[x + yyn])) { res.append (count++ == 0 ? ", expecting " : " or "); res.append (yytnamerr_ (yytname_[x])); } } } return res.toString (); } } return "syntax error"; }
java
{ "resource": "" }
q174719
CeParser.yy_reduce_print
test
private void yy_reduce_print (int yyrule, YYStack yystack) { if (yydebug == 0) return; int yylno = yyrline_[yyrule]; int yynrhs = yyr2_[yyrule]; /* Print the symbols being reduced, and their result. */ yycdebug ("Reducing stack by rule " + (yyrule - 1) + " (line " + yylno + "), "); /* The symbols being reduced. */ for (int yyi = 0; yyi < yynrhs; yyi++) yy_symbol_print (" $" + (yyi + 1) + " =", yystos_[yystack.stateAt(yynrhs - (yyi + 1))], ((yystack.valueAt (yynrhs-(yyi + 1))))); }
java
{ "resource": "" }
q174720
ChunkInputStream.readDMR
test
public String readDMR() throws DapException { try { if(state != State.INITIAL) throw new DapException("Attempt to read DMR twice"); byte[] dmr8 = null; if(requestmode == RequestMode.DMR) { // The whole buffer is the dmr; // but we do not know the length ByteArrayOutputStream baos = new ByteArrayOutputStream(); int c; while((c = input.read()) >= 0) { baos.write(c); } baos.close(); dmr8 = baos.toByteArray(); } else if(requestmode == RequestMode.DAP) { // Pull in the DMR chunk header if(!readHeader(input)) throw new DapException("Malformed chunk count"); // Read the DMR databuffer dmr8 = new byte[this.chunksize]; int red = read(dmr8, 0, this.chunksize); if(red < this.chunksize) throw new DapException("Short chunk"); } else assert false : "Internal error"; // Convert DMR to a string String dmr = new String(dmr8, DapUtil.UTF8); // Clean it up dmr = dmr.trim(); // Make sure it has trailing \r\n" if(dmr.endsWith("\r\n")) { // do nothing } else if(dmr.endsWith("\n")) dmr = dmr.substring(0,dmr.length()-2) + "\r\n"; else dmr = dmr + "\r\n"; // Figure out the endian-ness of the response this.remoteorder = (flags & DapUtil.CHUNK_LITTLE_ENDIAN) == 0 ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; this.nochecksum = (flags & DapUtil.CHUNK_NOCHECKSUM) != 0; // Set the state if((flags & DapUtil.CHUNK_ERROR) != 0) state = State.ERROR; else if((flags & DapUtil.CHUNK_END) != 0) state = State.END; else state = State.DATA; return dmr; //return the DMR } catch (IOException ioe) { throw new DapException(ioe.getMessage()); } }
java
{ "resource": "" }
q174721
ChunkInputStream.readError
test
public String readError() throws IOException { state = State.ERROR; // Read the error body databuffer byte[] bytes = new byte[this.chunksize]; try { if(read(bytes, 0, this.chunksize) < this.chunksize) throw new ErrorException("Short chunk"); } catch (IOException ioe) { throw new ErrorException(ioe); } String document = new String(bytes, DapUtil.UTF8); return document; }
java
{ "resource": "" }
q174722
ChunkInputStream.read
test
public int read(byte[] buf, int off, int len) throws IOException { // Sanity check if(off < 0 || len < 0) throw new IndexOutOfBoundsException();// Runtime if(off >= buf.length || buf.length < (off + len)) throw new IndexOutOfBoundsException(); //Runtime if(requestmode == RequestMode.DMR) throw new UnsupportedOperationException("Attempt to read databuffer when DMR only"); // Runtime // Attempt to read len bytes out of a sequence of chunks int count = len; int pos = off; while(count > 0) { if(avail <= 0) { if((flags & DapUtil.CHUNK_END) != 0 || !readHeader(input)) return (len - count); // return # databuffer read // See if we have an error chunk, // and if so, turn it into an exception if((flags & DapUtil.CHUNK_ERROR) != 0) { String document = readError(); throwError(document); } } else { int actual = (this.avail < count ? this.avail : count); int red = input.read(buf, pos, actual); if(red < 0) throw new IOException("Unexpected EOF"); pos += red; count -= red; this.avail -= red; } } return len; }
java
{ "resource": "" }
q174723
ChunkInputStream.readHeader
test
boolean readHeader(InputStream input) throws IOException { byte[] bytehdr = new byte[4]; int red = input.read(bytehdr); if(red == -1) return false; if(red < 4) throw new IOException("Short binary chunk count"); this.flags = ((int) bytehdr[0]) & 0xFF; // Keep unsigned bytehdr[0] = 0; ByteBuffer buf = ByteBuffer.wrap(bytehdr).order(ByteOrder.BIG_ENDIAN); this.chunksize = buf.getInt(); this.avail = this.chunksize; return true; }
java
{ "resource": "" }
q174724
CalendarDateFormatter.isoStringToDate
test
static public Date isoStringToDate(String iso) throws IllegalArgumentException { CalendarDate dt = isoStringToCalendarDate(null, iso); return dt.toDate(); }
java
{ "resource": "" }
q174725
TableParser.readTable
test
static public List<Record> readTable(String urlString, String format, int maxLines) throws IOException, NumberFormatException { InputStream ios; if (urlString.startsWith("http:")) { URL url = new URL(urlString); ios = url.openStream(); } else { ios = new FileInputStream(urlString); } return readTable(ios, format, maxLines); }
java
{ "resource": "" }
q174726
DatasetConstructor.transferGroup
test
static private void transferGroup(NetcdfFile ds, NetcdfDataset targetDs, Group src, Group targetGroup, ReplaceVariableCheck replaceCheck) { boolean unlimitedOK = true; // LOOK why not allowed? // group attributes transferGroupAttributes(src, targetGroup); // dimensions for (Dimension d : src.getDimensions()) { if (null == targetGroup.findDimensionLocal(d.getShortName())) { Dimension newd = new Dimension(d.getShortName(), d.getLength(), d.isShared(), unlimitedOK && d.isUnlimited(), d.isVariableLength()); targetGroup.addDimension(newd); } } // variables for (Variable v : src.getVariables()) { Variable targetV = targetGroup.findVariable(v.getShortName()); VariableEnhanced targetVe = (VariableEnhanced) targetV; boolean replace = (replaceCheck != null) && replaceCheck.replace(v); // replaceCheck not currently used if (replace || (null == targetV)) { // replace it if ((v instanceof Structure) && !(v instanceof StructureDS)) { v = new StructureDS(targetGroup, (Structure) v); // else if (!(v instanceof VariableDS) && !(v instanceof StructureDS)) Doug Lindolm } else if (!(v instanceof VariableDS)) { v = new VariableDS(targetGroup, v, false); // enhancement done by original variable, this is just to reparent to target dataset. } if (null != targetV) targetGroup.remove(targetV); targetGroup.addVariable(v); // reparent group v.resetDimensions(); // dimensions will be different } else if (!targetV.hasCachedData() && (targetVe.getOriginalVariable() == null)) { // this is the case where we defined the variable, but didnt set its data. we now set it with the first nested // dataset that has a variable with the same name targetVe.setOriginalVariable(v); } } // nested groups - check if target already has it for (Group srcNested : src.getGroups()) { Group nested = targetGroup.findGroup(srcNested.getShortName()); if (null == nested) { nested = new Group(ds, targetGroup, srcNested.getShortName()); targetGroup.addGroup(nested); } transferGroup(ds, targetDs, srcNested, nested, replaceCheck); } }
java
{ "resource": "" }
q174727
IgraPor.getStnFile
test
private File getStnFile(String location) { File file = new File(location); File stnFile = new File(file.getParentFile(), STN_FILE); if (!stnFile.exists()) { if (file.getParentFile() == null) return null; stnFile = new File(file.getParentFile().getParentFile(), STN_FILE); if (!stnFile.exists()) return null; } return stnFile; }
java
{ "resource": "" }
q174728
IgraPor.open
test
@Override public void open(RandomAccessFile raff, NetcdfFile ncfile, CancelTask cancelTask) throws IOException { super.open(raff, ncfile, cancelTask); int pos = location.lastIndexOf("."); String ext = location.substring(pos); File file = new File(location); File stnFile = getStnFile(location); if (stnFile == null) throw new FileNotFoundException("Station File does not exist="+location); if (ext.equals(IDX_EXT)) { stnRaf = RandomAccessFile.acquire(stnFile.getPath()); } else if (ext.equals(DAT_EXT)) { stnRaf = RandomAccessFile.acquire(stnFile.getPath()); dataRaf = raff; //extract the station id String name = file.getName(); stationId = name.substring(0, name.length() - DAT_EXT.length()); } else { // pointed to the station file stnRaf = raff; dataDir = new File(file.getParentFile(), DAT_DIR); } NcmlConstructor ncmlc = new NcmlConstructor(); if (!ncmlc.populateFromResource("resources/nj22/iosp/igra-por.ncml", ncfile)) { throw new IllegalStateException(ncmlc.getErrlog().toString()); } ncfile.finish(); //dataVinfo = setVinfo(dataRaf, ncfile, dataPattern, "all_data"); stnVinfo = setVinfo(stnRaf, ncfile, stnPattern, "station"); seriesVinfo = setVinfo(stnRaf, ncfile, dataHeaderPattern, "station.time_series"); profileVinfo = setVinfo(stnRaf, ncfile, dataPattern, "station.time_series.levels"); StructureMembers.Member m = stnVinfo.sm.findMember(STNID); StructureDataRegexp.VinfoField f = (StructureDataRegexp.VinfoField) m.getDataObject(); stn_fldno = f.fldno; /* make index file if needed File idxFile = new File(base + IDX_EXT); if (!idxFile.exists()) makeIndex(stnVinfo, dataVinfo, idxFile); else readIndex(idxFile.getPath()); */ }
java
{ "resource": "" }
q174729
SimpleGeometryIndexFinder.getBeginning
test
public int getBeginning(int index) { //Test if the last end is the new beginning if(index == (pastIndex + 1 )) { return previousEnd + 1; } // Otherwise, find it! int newBeginning = 0; for(int i = 0; i < index; i++) { newBeginning += getNodeCount(i); } pastIndex = index; previousBegin = newBeginning; return newBeginning; }
java
{ "resource": "" }
q174730
SimpleGeometryIndexFinder.getEnd
test
public int getEnd(int index) { // Test if the last beginning is the new end if(index == (pastIndex - 1)) { return previousBegin - 1; } // Otherwise find it! int new_end = 0; for(int i = 0; i < index + 1; i++) { new_end += getNodeCount(i); } pastIndex = index; previousEnd = new_end; return new_end - 1; }
java
{ "resource": "" }
q174731
GribCollectionBuilder.createAllRuntimeCollections
test
private boolean createAllRuntimeCollections(Formatter errlog) throws IOException { long start = System.currentTimeMillis(); this.type = GribCollectionImmutable.Type.SRC; boolean ok = true; List<MFile> files = new ArrayList<>(); List<? extends Group> groups = makeGroups(files, true, errlog); List<MFile> allFiles = Collections.unmodifiableList(files); // gather into collections with a single runtime Map<Long, List<Group>> runGroups = new HashMap<>(); for (Group g : groups) { List<Group> runGroup = runGroups .computeIfAbsent(g.getRuntime().getMillis(), k -> new ArrayList<>()); runGroup.add(g); } // write each rungroup separately boolean multipleRuntimes = runGroups.values().size() > 1; List<MFile> partitions = new ArrayList<>(); for (List<Group> runGroupList : runGroups.values()) { Group g = runGroupList.get(0); // if multiple Runtimes, we will write a partition. otherwise, we need to use the standard name (without runtime) so we know the filename from the collection String gcname = multipleRuntimes ? GribCollectionMutable.makeName(this.name, g.getRuntime()) : this.name; MFile indexFileForRuntime = GribCollectionMutable.makeIndexMFile(gcname, directory); // not using disk cache LOOK why ? partitions.add(indexFileForRuntime); // create the master runtimes, consisting of the single runtime List<Long> runtimes = new ArrayList<>(1); runtimes.add(g.getRuntime().getMillis()); CoordinateRuntime masterRuntimes = new CoordinateRuntime(runtimes, null); CalendarDateRange calendarDateRangeAll = null; for (Coordinate coord : g.getCoordinates()) { if (coord instanceof CoordinateTimeAbstract) { CalendarDateRange calendarDateRange = ((CoordinateTimeAbstract) coord).makeCalendarDateRange(null); if (calendarDateRangeAll == null) calendarDateRangeAll = calendarDateRange; else calendarDateRangeAll = calendarDateRangeAll.extend(calendarDateRange); } } assert calendarDateRangeAll != null; // for each Group write an index file ok &= writeIndex(gcname, indexFileForRuntime.getPath(), masterRuntimes, runGroupList, allFiles, calendarDateRangeAll); logger.info("GribCollectionBuilder write {} ok={}", indexFileForRuntime.getPath(), ok); } // if theres more than one runtime, create a partition collection to collect all the runtimes together if (multipleRuntimes) { Collections.sort(partitions); // ?? PartitionManager part = new PartitionManagerFromIndexList(dcm, partitions, logger); part.putAuxInfo(FeatureCollectionConfig.AUX_CONFIG, dcm.getAuxInfo(FeatureCollectionConfig.AUX_CONFIG)); ok &= GribCdmIndex.updateGribCollectionFromPCollection(isGrib1, part, CollectionUpdateType.always, errlog, logger); } long took = System.currentTimeMillis() - start; logger.debug("That took {} msecs", took); return ok; }
java
{ "resource": "" }
q174732
DurationField.setEditValue
test
protected void setEditValue(Object value) { if (value == null) tf.setText(""); else tf.setText(value.toString()); // tf.repaint(); }
java
{ "resource": "" }
q174733
Doradeheader.getDataType
test
DataType getDataType(int format) { DataType p; switch (format) { case 1: // 8-bit signed integer format. p = DataType.SHORT; break; case 2: // 16-bit signed integer format. p = DataType.FLOAT; break; case 3: // 32-bit signed integer format. p = DataType.LONG; break; case 4: // 32-bit IEEE float format. p = DataType.FLOAT; break; case 5: // 16-bit IEEE float format. p = DataType.DOUBLE; break; default: p = null; break; } //end of switch return p; }
java
{ "resource": "" }
q174734
Cosmic1Convention.ECFtoLLA
test
public static double[] ECFtoLLA(double x, double y, double z, double a, double b) { double longitude = Math.atan2(y, x); double ePrimeSquared = (a * a - b * b) / (b * b); double p = Math.sqrt(x * x + y * y); double theta = Math.atan((z * a) / (p * b)); double sineTheta = Math.sin(theta); double cosTheta = Math.cos(theta); double f = 1 / 298.257223563; double e2 = 2 * f - f * f; double top = z + ePrimeSquared * b * sineTheta * sineTheta * sineTheta; double bottom = p - e2 * a * cosTheta * cosTheta * cosTheta; double geodeticLat = Math.atan(top / bottom); double sineLat = Math.sin(geodeticLat); double N = a / Math.sqrt(1 - e2 * sineLat * sineLat); double altitude = (p / Math.cos(geodeticLat)) - N; // maintain longitude btw -PI and PI if (longitude > Math.PI) { longitude -= 2 * Math.PI; } else if (longitude < -Math.PI) { longitude += 2 * Math.PI; } return new double[]{geodeticLat, longitude, altitude}; }
java
{ "resource": "" }
q174735
Util.cleanUnit
test
public static String cleanUnit(String unit) { if (unit == null) return null; // These specific words become dimensionless if (unit.equalsIgnoreCase("Proportion") || unit.equalsIgnoreCase("Numeric")) unit = ""; // So does '-' else if (unit.equalsIgnoreCase("-")) { unit = ""; // Make sure degree(s) true gets concatenated with '_' } else if (unit.startsWith("degree") && unit.endsWith("true")) { unit = unit.replace(' ', '_'); // And only do the rest of the conversion if it's not a "* table *" entry } else if (!unit.contains(" table ")) { if (unit.startsWith("/")) unit = "1" + unit; unit = unit.trim(); unit = StringUtil2.remove(unit, "**"); StringBuilder sb = new StringBuilder(unit); StringUtil2.remove(sb, "^[]"); StringUtil2.replace(sb, ' ', "."); StringUtil2.replace(sb, '*', "."); unit = sb.toString(); } return unit; }
java
{ "resource": "" }
q174736
Util.cleanName
test
public static String cleanName(String name) { if (name == null) return null; int pos = name.indexOf("(see"); if (pos < 0) pos = name.indexOf("(See"); if (pos > 0) name = name.substring(0,pos); name = StringUtil2.replace(name, '/', "-"); StringBuilder sb = new StringBuilder(name); StringUtil2.replace(sb, '+', "plus"); StringUtil2.remove(sb, ".;,=[]()/*\""); return StringUtil2.collapseWhitespace(sb.toString().trim()); }
java
{ "resource": "" }
q174737
Util.isUnitless
test
public static boolean isUnitless(String unit) { if (unit == null) return true; String munge = unit.toLowerCase().trim(); munge = StringUtil2.remove(munge, '('); return munge.length() == 0 || munge.startsWith("numeric") || munge.startsWith("non-dim") || munge.startsWith("see") || munge.startsWith("proportion") || munge.startsWith("code") || munge.startsWith("0=") || munge.equals("1") ; }
java
{ "resource": "" }
q174738
Nc4Notes.factory
test
static Notes factory(NoteSort ns, int g, int id, Nc4DSP dsp) { Notes note = null; switch (ns) { case TYPE: note = new TypeNotes(g, id, dsp); break; case VAR: note = new VarNotes(g, id, dsp); break; case DIM: note = new DimNotes(g, id, dsp); break; case GROUP: note = new GroupNotes(g, id, dsp); break; } return note; }
java
{ "resource": "" }
q174739
Nc4Notes.getVarId
test
static public long getVarId(VarNotes note) { return getVarId(note.gid, note.id, note.getFieldIndex()); }
java
{ "resource": "" }
q174740
DodsV.parseDAS
test
void parseDAS(DAS das) throws IOException { Enumeration tableNames = das.getNames(); while (tableNames.hasMoreElements()) { String tableName = (String) tableNames.nextElement(); AttributeTable attTable = das.getAttributeTableN(tableName); if (tableName.equals("NC_GLOBAL") || tableName.equals("HDF_GLOBAL")) { addAttributeTable(this, attTable, tableName, true); } else if (tableName.equals("DODS_EXTRA") || tableName.equals("EXTRA_DIMENSION")) { // handled seperately in DODSNetcdfFile continue; } else { DodsV dodsV = findDodsV(tableName, false); // short name matches the table name if (dodsV != null) { addAttributeTable(dodsV, attTable, tableName, true); } else { dodsV = findTableDotDelimited(tableName); if (dodsV != null) { addAttributeTable(dodsV, attTable, tableName, true); } else { if (debugAttributes) System.out.println("DODSNetcdf getAttributes CANT find <" + tableName + "> add to globals"); addAttributeTable(this, attTable, tableName, false); } } } } }
java
{ "resource": "" }
q174741
DodsV.findDodsV
test
DodsV findDodsV(String name, boolean useDone) { for (DodsV dodsV : children) { if (useDone && dodsV.isDone) continue; // LOOK useDone ?? if ((name == null) || (dodsV == null) || (dodsV.bt == null)) { logger.warn("Corrupted structure"); continue; } if (name.equals(dodsV.bt.getEncodedName())) return dodsV; } return null; }
java
{ "resource": "" }
q174742
DodsV.findDataV
test
DodsV findDataV(DodsV ddsV) { if (ddsV.parent.bt != null) { DodsV parentV = findDataV(ddsV.parent); if (parentV == null) // dataDDS may not have the structure wrapper return findDodsV(ddsV.bt.getEncodedName(), true); return parentV.findDodsV(ddsV.bt.getEncodedName(), true); } DodsV dataV = findDodsV(ddsV.bt.getEncodedName(), true); /* if ((dataV == null) && (ddsV.bt instanceof DGrid)) { // when asking for the Grid array DodsV gridArray = (DodsV) ddsV.children.get(0); return findDodsV( gridArray.bt.getName(), dataVlist, true); } */ return dataV; }
java
{ "resource": "" }
q174743
DodsV.findByIndex
test
DodsV findByIndex(int index) { if (children.size() <= index) return null; return children.get(index); }
java
{ "resource": "" }
q174744
Variable.getParentGroup
test
public Group getParentGroup() { Group g = super.getParentGroup(); if (g == null) { g = ncfile.getRootGroup(); super.setParentGroup(g); } assert g != null; return g; }
java
{ "resource": "" }
q174745
Variable.getDimension
test
public Dimension getDimension(int i) { if ((i < 0) || (i >= getRank())) return null; return dimensions.get(i); }
java
{ "resource": "" }
q174746
Variable.findDimensionIndex
test
public int findDimensionIndex(String name) { for (int i = 0; i < dimensions.size(); i++) { Dimension d = dimensions.get(i); if (name.equals(d.getShortName())) return i; } return -1; }
java
{ "resource": "" }
q174747
Variable.getUnitsString
test
public String getUnitsString() { String units = null; Attribute att = findAttribute(CDM.UNITS); if (att == null) att = findAttributeIgnoreCase(CDM.UNITS); if ((att != null) && att.isString()) { units = att.getStringValue(); if (units != null) units = units.trim(); } return units; }
java
{ "resource": "" }
q174748
Variable.getShapeAsSection
test
public Section getShapeAsSection() { if (shapeAsSection == null) { try { List<Range> list = new ArrayList<>(); for (Dimension d : dimensions) { int len = d.getLength(); if (len > 0) list.add(new Range(d.getShortName(), 0, len - 1)); else if (len == 0) list.add( Range.EMPTY); // LOOK empty not named else { assert d.isVariableLength(); list.add( Range.VLEN); // LOOK vlen not named } } shapeAsSection = new Section(list).makeImmutable(); } catch (InvalidRangeException e) { log.error("Bad shape in variable " + getFullName(), e); throw new IllegalStateException(e.getMessage()); } } return shapeAsSection; }
java
{ "resource": "" }
q174749
Variable.slice
test
public Variable slice(int dim, int value) throws InvalidRangeException { if ((dim < 0) || (dim >= shape.length)) throw new InvalidRangeException("Slice dim invalid= " + dim); // ok to make slice of record dimension with length 0 boolean recordSliceOk = false; if ((dim == 0) && (value == 0)) { Dimension d = getDimension(0); recordSliceOk = d.isUnlimited(); } // otherwise check slice in range if (!recordSliceOk) { if ((value < 0) || (value >= shape[dim])) throw new InvalidRangeException("Slice value invalid= " + value + " for dimension " + dim); } // create a copy of this variable with a proxy reader Variable sliceV = copy(); // subclasses must override Section slice = new Section(getShapeAsSection()); slice.replaceRange(dim, new Range(value, value)).makeImmutable(); sliceV.setProxyReader(new SliceReader(this, dim, slice)); sliceV.createNewCache(); // dont share the cache sliceV.setCaching(false); // dont cache // remove that dimension - reduce rank sliceV.dimensions.remove(dim); sliceV.resetShape(); return sliceV; }
java
{ "resource": "" }
q174750
Variable.setEnumTypedef
test
public void setEnumTypedef(EnumTypedef enumTypedef) { if (immutable) throw new IllegalStateException("Cant modify"); if (!dataType.isEnum()) throw new UnsupportedOperationException("Can only call Variable.setEnumTypedef() on enum types"); this.enumTypedef = enumTypedef; }
java
{ "resource": "" }
q174751
Variable.read
test
public Array read(List<Range> ranges) throws IOException, InvalidRangeException { if (null == ranges) return _read(); return read(new Section(ranges)); }
java
{ "resource": "" }
q174752
Variable.readScalarString
test
public String readScalarString() throws IOException { Array data = getScalarData(); if (dataType == DataType.STRING) return (String) data.getObject(Index.scalarIndexImmutable); else if (dataType == DataType.CHAR) { ArrayChar dataC = (ArrayChar) data; return dataC.getString(); } else throw new IllegalArgumentException("readScalarString not STRING or CHAR " + getFullName()); }
java
{ "resource": "" }
q174753
Variable._read
test
protected Array _read() throws IOException { // caching overrides the proxyReader // check if already cached if (cache.data != null) { if (debugCaching) System.out.println("got data from cache " + getFullName()); return cache.data.copy(); } Array data = proxyReader.reallyRead(this, null); // optionally cache it if (isCaching()) { setCachedData(data); if (debugCaching) System.out.println("cache " + getFullName()); return cache.data.copy(); // dont let users get their nasty hands on cached data } else { return data; } }
java
{ "resource": "" }
q174754
Variable._read
test
protected Array _read(Section section) throws IOException, InvalidRangeException { // check if its really a full read if ((null == section) || section.computeSize() == getSize()) return _read(); // full read was cached if (isCaching()) { if (cache.data == null) { setCachedData(_read()); // read and cache entire array if (debugCaching) System.out.println("cache " + getFullName()); } if (debugCaching) System.out.println("got data from cache " + getFullName()); return cache.data.sectionNoReduce(section.getRanges()).copy(); // subset it, return copy } return proxyReader.reallyRead(this, section, null); }
java
{ "resource": "" }
q174755
Variable.writeCDL
test
public String writeCDL(boolean useFullName, boolean strict) { Formatter buf = new Formatter(); writeCDL(buf, new Indent(2), useFullName, strict); return buf.toString(); }
java
{ "resource": "" }
q174756
Variable.toStringDebug
test
public String toStringDebug() { Formatter f = new Formatter(); f.format("Variable %s", getFullName()); if (ncfile != null) { f.format(" in file %s", getDatasetLocation()); String extra = ncfile.toStringDebug(this); if (extra != null) f.format(" %s", extra); } return f.toString(); }
java
{ "resource": "" }
q174757
Variable.setDataType
test
public void setDataType(DataType dataType) { if (immutable) throw new IllegalStateException("Cant modify"); this.dataType = dataType; this.elementSize = getDataType().getSize(); /* why is this needed ?? EnumTypedef etd = getEnumTypedef(); if (etd != null) { DataType etdtype = etd.getBaseType(); if (dataType != etdtype) log.error("Variable.setDataType: enum basetype mismatch: {} != {}", etdtype, dataType); /* DataType basetype = null; if (dataType == DataType.ENUM1) basetype = DataType.BYTE; else if (dataType == DataType.ENUM2) basetype = DataType.SHORT; else if (dataType == DataType.ENUM4) basetype = DataType.INT; else basetype = etdtype; if (etdtype != null && dataType != etdtype) else etd.setBaseType(basetype); } */ }
java
{ "resource": "" }
q174758
Variable.setDimensions
test
public void setDimensions(List<Dimension> dims) { if (immutable) throw new IllegalStateException("Cant modify"); this.dimensions = (dims == null) ? new ArrayList<>() : new ArrayList<>(dims); resetShape(); }
java
{ "resource": "" }
q174759
Variable.resetShape
test
public void resetShape() { // if (immutable) throw new IllegalStateException("Cant modify"); LOOK allow this for unlimited dimension updating this.shape = new int[dimensions.size()]; for (int i = 0; i < dimensions.size(); i++) { Dimension dim = dimensions.get(i); shape[i] = dim.getLength(); //shape[i] = Math.max(dim.getLength(), 0); // LOOK // if (dim.isUnlimited() && (i != 0)) // LOOK only true for Netcdf-3 // throw new IllegalArgumentException("Unlimited dimension must be outermost"); if (dim.isVariableLength()) { //if (dimensions.size() != 1) // throw new IllegalArgumentException("Unknown dimension can only be used in 1 dim array"); //else isVariableLength = true; } } this.shapeAsSection = null; // recalc next time its asked for }
java
{ "resource": "" }
q174760
Variable.setDimensions
test
public void setDimensions(String dimString) { if (immutable) throw new IllegalStateException("Cant modify"); try { setDimensions(Dimension.makeDimensionsList(getParentGroup(), dimString)); //this.dimensions = Dimension.makeDimensionsList(getParentGroup(), dimString); resetShape(); } catch (IllegalStateException e) { throw new IllegalArgumentException("Variable " + getFullName() + " setDimensions = '" + dimString + "' FAILED: " + e.getMessage() + " file = " + getDatasetLocation()); } }
java
{ "resource": "" }
q174761
Variable.resetDimensions
test
public void resetDimensions() { if (immutable) throw new IllegalStateException("Cant modify"); ArrayList<Dimension> newDimensions = new ArrayList<>(); for (Dimension dim : dimensions) { if (dim.isShared()) { Dimension newD = getParentGroup().findDimension(dim.getShortName()); if (newD == null) throw new IllegalArgumentException("Variable " + getFullName() + " resetDimensions FAILED, dim doesnt exist in parent group=" + dim); newDimensions.add(newD); } else { newDimensions.add(dim); } } this.dimensions = newDimensions; resetShape(); }
java
{ "resource": "" }
q174762
Variable.setDimension
test
public void setDimension(int idx, Dimension dim) { if (immutable) throw new IllegalStateException("Cant modify"); dimensions.set(idx, dim); resetShape(); }
java
{ "resource": "" }
q174763
Variable.setCachedData
test
public void setCachedData(Array cacheData, boolean isMetadata) { if ((cacheData != null) && (cacheData.getElementType() != getDataType().getPrimitiveClassType())) throw new IllegalArgumentException("setCachedData type=" + cacheData.getElementType() + " incompatible with variable type=" + getDataType()); this.cache.data = cacheData; this.isMetadata = isMetadata; this.cache.cachingSet = true; this.cache.isCaching = true; }
java
{ "resource": "" }
q174764
Variable.getDimensionsAll
test
public List<Dimension> getDimensionsAll() { List<Dimension> dimsAll = new ArrayList<>(); addDimensionsAll(dimsAll, this); return dimsAll; }
java
{ "resource": "" }
q174765
AbstractRadialAdapter.setBoundingBox
test
protected void setBoundingBox() { LatLonRect largestBB = null; // look through all the coord systems for (Object o : csHash.values()) { RadialCoordSys sys = (RadialCoordSys) o; sys.setOrigin(origin); LatLonRect bb = sys.getBoundingBox(); if (largestBB == null) largestBB = bb; else if (bb != null) largestBB.extend(bb); } boundingBox = largestBB; }
java
{ "resource": "" }
q174766
FmrInv.finish
test
void finish() { gridList = new ArrayList<>(uvHash.values()); Collections.sort(gridList); // find the common coordinates for (GridVariable grid : gridList) { grid.finish(); } // assign sequence number for time int seqno = 0; for (TimeCoord tc : timeCoords) tc.setId(seqno++); // assign sequence number for vertical coords with same name HashMap<String, List<VertCoord>> map = new HashMap<>(); for (VertCoord vc : vertCoords) { List<VertCoord> list = map.get(vc.getName()); if (list == null) { list = new ArrayList<>(); map.put(vc.getName(), list); } list.add(vc); } for (List<VertCoord> list : map.values()) { if (list.size() > 0) { int count = 0; for (VertCoord vc : list) { if (count > 0) vc.setName(vc.getName()+count); count++; } } } }
java
{ "resource": "" }
q174767
Catalog.getAllDatasets
test
public Iterable<Dataset> getAllDatasets() { List<Dataset> all = new ArrayList<>(); addAll(this, all); return all; }
java
{ "resource": "" }
q174768
SynDSP.dspMatch
test
public boolean dspMatch(String path, DapContext context) { for(String ext : SYNEXTENSIONS) { if(path.endsWith(ext)) return true; } return false; }
java
{ "resource": "" }
q174769
CDMDSP.open
test
public CDMDSP open(NetcdfDataset ncd) throws DapException { assert this.context != null; this.dmrfactory = new DMRFactory(); this.ncdfile = ncd; setLocation(this.ncdfile.getLocation()); buildDMR(); return this; }
java
{ "resource": "" }
q174770
CDMDSP.buildDMR
test
public void buildDMR() throws DapException { if (getDMR() != null) return; try { if (DUMPCDL) { System.out.println("writecdl:"); this.ncdfile.writeCDL(System.out, false); System.out.flush(); } // Use the file path to define the dataset name String name = this.ncdfile.getLocation(); // Normalize the name name = DapUtil.canonicalpath(name); // Remove any path prefix int index = name.lastIndexOf('/'); if (index >= 0) name = name.substring(index + 1, name.length()); // Initialize the root dataset node setDMR((DapDataset) dmrfactory.newDataset(name).annotate(NetcdfDataset.class, this.ncdfile)); // Map the CDM root group to this group recordNode(this.ncdfile.getRootGroup(), getDMR()); getDMR().setBase(DapUtil.canonicalpath(this.ncdfile.getLocation())); // Now recursively build the tree. Start by // Filling the dataset with the contents of the ncfile // root group. fillgroup(getDMR(), this.ncdfile.getRootGroup()); // Add an order index to the tree getDMR().sort(); // Now locate the coordinate variables for maps /* Walk looking for VariableDS instances */ processmappedvariables(this.ncdfile.getRootGroup()); // Now set the view getDMR().finish(); } catch (DapException e) { setDMR(null); throw new DapException(e); } }
java
{ "resource": "" }
q174771
CDMDSP.buildseqtypes
test
protected void buildseqtypes(Variable cdmvar) throws DapException { if (CDMUtil.hasVLEN(cdmvar)) { buildseqtype(cdmvar); } if (cdmvar.getDataType() == DataType.STRUCTURE || cdmvar.getDataType() == DataType.SEQUENCE) { Structure struct = (Structure) cdmvar; List<Variable> fields = struct.getVariables(); for (int i = 0; i < fields.size(); i++) { Variable field = fields.get(i); buildseqtypes(field); // recurse for inner vlen dims } } }
java
{ "resource": "" }
q174772
CDMDSP.builddimrefs
test
protected void builddimrefs(DapVariable dapvar, List<Dimension> cdmdims) throws DapException { if (cdmdims == null || cdmdims.size() == 0) return; // It is unfortunately the case that the dimensions // associated with the variable are not // necessarily the same object as those dimensions // as declared, so we need to use a non-trivial // matching algorithm. for (Dimension cdmdim : cdmdims) { DapDimension dapdim = null; if (cdmdim.isShared()) { Dimension declareddim = finddimdecl(cdmdim); if (declareddim == null) throw new DapException("Unprocessed cdm dimension: " + cdmdim); dapdim = (DapDimension) this.nodemap.get(declareddim); assert dapdim != null; } else if (cdmdim.isVariableLength()) {// ignore continue; } else {//anonymous dapdim = builddim(cdmdim); } assert (dapdim != null) : "Internal error"; dapvar.addDimension(dapdim); } }
java
{ "resource": "" }
q174773
CDMDSP.findMatchingEnum
test
protected EnumTypedef findMatchingEnum(EnumTypedef varenum) throws DapException { List<EnumTypedef> candidates = new ArrayList<>(); for (Map.Entry<DapNode, CDMNode> entry : this.nodemap.getCDMMap().entrySet()) { CDMNode cdmnode = entry.getValue(); if (cdmnode.getSort() != CDMSort.ENUMERATION) continue; // Compare the enumeration (note names will differ) EnumTypedef target = (EnumTypedef) cdmnode; /* Ideally, we should test the types of the enums, but, unfortunately, the var enum is always enum4. if(target.getBaseType() != varenum.getBaseType()) continue; */ Map<Integer, String> targetmap = target.getMap(); Map<Integer, String> varmap = varenum.getMap(); if (targetmap.size() != varmap.size()) continue; boolean match = true; // until otherwise shown for (Map.Entry<Integer, String> tpair : targetmap.entrySet()) { String tname = tpair.getValue(); int value = (int) tpair.getKey(); boolean found = false; for (Map.Entry<Integer, String> vpair : varmap.entrySet()) { if (tname.equals(vpair.getValue()) && value == (int) vpair.getKey()) { found = true; break; } } if (!found) { match = false; break; } } if (!match) continue; // Save it unless it is shadowed by a closer enum boolean shadowed = false; for (EnumTypedef etd : candidates) { if (shadows(etd.getGroup(), target.getGroup())) { shadowed = true; break; } } if (!shadowed) candidates.add(target); } switch (candidates.size()) { case 0: throw new DapException("CDMDSP: No matching enum type decl: " + varenum.getShortName()); case 1: break; default: throw new DapException("CDMDSP: Multiple matching enum type decls: " + varenum.getShortName()); } return candidates.get(0); }
java
{ "resource": "" }
q174774
CDMDSP.getCoreDimset
test
static List<Dimension> getCoreDimset(List<Dimension> dimset) throws DapException { if (dimset == null) return null; List<Dimension> core = new ArrayList<>(); int pos = -1; int count = 0; for (int i = 0; i < dimset.size(); i++) { if (dimset.get(i).isVariableLength()) { pos = i; count++; } else core.add(dimset.get(i)); } if ((pos != dimset.size() - 1) || count > 1) throw new DapException("Unsupported use of (*) Dimension"); return core; }
java
{ "resource": "" }
q174775
BufrDataProcess.scanBufrFile
test
public int scanBufrFile(String filename, Counter total) throws Exception { int count = 0; try (RandomAccessFile raf = new RandomAccessFile(filename, "r")) { MessageScanner scan = new MessageScanner(raf); while (scan.hasNext()) { Message m = scan.next(); if (m == null) continue; try { if (showMess) out.format("%sMessage %d header=%s%n", indent, count, m.getHeader()); count++; Counter counter = new Counter(); processBufrMessageAsDataset(scan, m, counter); if (showMess) out.format("%scount=%d miss=%d%n", indent, counter.nvals, counter.nmiss); total.add(counter); } catch (Exception e) { System.out.printf(" BARF:%s on %s%n", e.getMessage(), m.getHeader()); indent.setIndentLevel(0); } } } return count; }
java
{ "resource": "" }
q174776
BufrDataProcess.processBufrMessageAsDataset
test
private void processBufrMessageAsDataset(MessageScanner scan, Message m, Counter counter) throws Exception { byte[] mbytes = scan.getMessageBytes(m); NetcdfFile ncfile = NetcdfFile.openInMemory("test", mbytes, "ucar.nc2.iosp.bufr.BufrIosp"); Sequence obs = (Sequence) ncfile.findVariable(BufrIosp2.obsRecord); StructureDataIterator sdataIter = obs.getStructureIterator(-1); processSequence(obs, sdataIter, counter); }
java
{ "resource": "" }
q174777
CdmValidatorController.doPost
test
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.info("doPost(): " + UsageLog.setupRequestContext(req)); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { log.info("doPost(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, 0)); res.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } //Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(this.cdmValidatorContext.getFileuploadFileItemFactory()); upload.setSizeMax(this.cdmValidatorContext.getMaxFileUploadSize()); // maximum bytes before a FileUploadException will be thrown List<FileItem> fileItems; try { fileItems = (List<FileItem>) upload.parseRequest(req); } catch (FileUploadException e) { log.info("doPost(): Validator FileUploadException", e); log.info("doPost(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, 0)); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } //Process the uploaded items String username = null; boolean wantXml = false; for (FileItem item : fileItems) { if (item.isFormField()) { if ("username".equals(item.getFieldName())) username = item.getString(); if ("xml".equals(item.getFieldName())) wantXml = item.getString().equals("true"); } } for (FileItem item : fileItems) { if (!item.isFormField()) { try { processUploadedFile(req, res, (DiskFileItem) item, username, wantXml); return; } catch (Exception e) { log.info("doPost(): Validator processUploadedFile", e); log.info("doPost(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, 0)); res.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } } } }
java
{ "resource": "" }
q174778
Navigation.getTransform
test
public AffineTransform getTransform() { at.setTransform( pix_per_world, 0.0, 0.0, -pix_per_world, pix_x0, pix_y0); if (debug) { System.out.println("Navigation getTransform = "+ pix_per_world +" "+ pix_x0+" "+ pix_y0); System.out.println(" transform = "+ at); } return at; }
java
{ "resource": "" }
q174779
Navigation.wantRotate
test
public boolean wantRotate(double displayWidth, double displayHeight) { getMapArea( bb); // current world bounding box boolean aspectDisplay = displayHeight < displayWidth; boolean aspectWorldBB = bb.getHeight() < bb.getWidth(); return (aspectDisplay ^ aspectWorldBB); // aspects are different }
java
{ "resource": "" }
q174780
Navigation.getMapArea
test
public ProjectionRect getMapArea(ProjectionRect rect) { if (rect == null) rect = new ProjectionRect(); double width = pwidth/pix_per_world; double height = pheight/pix_per_world; // center point double wx0 = (pwidth/2-pix_x0)/pix_per_world; double wy0 = (pix_y0-pheight/2)/pix_per_world; rect.setRect(wx0-width/2, wy0-height/2, // minx, miny width, height); // width, height return rect; }
java
{ "resource": "" }
q174781
Navigation.worldToScreen
test
public Point2D worldToScreen(ProjectionPointImpl w, Point2D p) { p.setLocation( pix_per_world*w.getX() + pix_x0, -pix_per_world*w.getY() + pix_y0); return p; }
java
{ "resource": "" }
q174782
Navigation.pan
test
public void pan( double deltax, double deltay) { zoom.push(); pix_x0 -= deltax; pix_y0 -= deltay; fireMapAreaEvent(); }
java
{ "resource": "" }
q174783
Navigation.zoom
test
public void zoom(double startx, double starty, double width, double height) { if (debugZoom) System.out.println("zoom "+ startx+ " "+starty+ " "+width+ " "+height+ " "); if ((width < 5) || (height < 5)) return; zoom.push(); pix_x0 -= startx+width/2 - pwidth/2; pix_y0 -= starty+height/2 - pheight/2; zoom(pwidth / width); }
java
{ "resource": "" }
q174784
Navigation.recalcFromBoundingBox
test
private void recalcFromBoundingBox() { if (debugRecalc) { System.out.println("Navigation recalcFromBoundingBox= "+ bb); System.out.println(" "+ pwidth +" "+ pheight); } // decide which dimension is limiting double pixx_per_wx = (bb.getWidth() == 0.0) ? 1 : pwidth / bb.getWidth(); double pixy_per_wy = (bb.getHeight() == 0.0) ? 1 : pheight / bb.getHeight(); pix_per_world = Math.min(pixx_per_wx, pixy_per_wy); // calc the center point double wx0 = bb.getX() + bb.getWidth()/2; double wy0 = bb.getY() + bb.getHeight()/2; // calc offset based on center point pix_x0 = pwidth/2 - pix_per_world * wx0; pix_y0 = pheight/2 + pix_per_world * wy0; if (debugRecalc) { System.out.println("Navigation recalcFromBoundingBox done= "+ pix_per_world +" "+ pix_x0+" "+ pix_y0); System.out.println(" "+ pwidth +" "+ pheight+" "+ bb); } }
java
{ "resource": "" }
q174785
ListenerManager.addListener
test
public synchronized void addListener(Object l) { if (!listeners.contains(l)) { listeners.add(l); hasListeners = true; } else logger.warn("ListenerManager.addListener already has Listener " + l); }
java
{ "resource": "" }
q174786
ListenerManager.removeListener
test
public synchronized void removeListener(Object l) { if (listeners.contains(l)) { listeners.remove(l); hasListeners = (listeners.size() > 0); } else logger.warn("ListenerManager.removeListener couldnt find Listener " + l); }
java
{ "resource": "" }
q174787
ListenerManager.sendEvent
test
public synchronized void sendEvent(java.util.EventObject event) { if (!hasListeners || !enabled) return; Object[] args = new Object[1]; args[0] = event; // send event to all listeners ListIterator iter = listeners.listIterator(); while (iter.hasNext()) { Object client = iter.next(); try { method.invoke(client, args); } catch (IllegalAccessException e) { logger.error("ListenerManager IllegalAccessException", e); iter.remove(); } catch (IllegalArgumentException e) { logger.error("ListenerManager IllegalArgumentException", e); iter.remove(); } catch (InvocationTargetException e) { // logger.error("ListenerManager InvocationTargetException on " + method+ " threw exception " + e.getTargetException(), e); throw new RuntimeException(e.getCause()); // pass exception to the caller of sendEvent() } } }
java
{ "resource": "" }
q174788
ListenerManager.sendEventExcludeSource
test
public synchronized void sendEventExcludeSource(java.util.EventObject event) { if (!hasListeners || !enabled) return; Object source = event.getSource(); Object[] args = new Object[1]; args[0] = event; // send event to all listeners except the source ListIterator iter = listeners.listIterator(); while (iter.hasNext()) { Object client = iter.next(); if (client == source) continue; try { method.invoke(client, args); } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { e.printStackTrace(); if (e.getCause() != null) e.getCause().printStackTrace(); // iter.remove(); logger.error("ListenerManager calling " + method + " threw exception ", e); } } }
java
{ "resource": "" }
q174789
NCdumpW.print
test
public static boolean print(String command, Writer out, ucar.nc2.util.CancelTask ct) throws IOException { // pull out the filename from the command String filename; StringTokenizer stoke = new StringTokenizer(command); if (stoke.hasMoreTokens()) filename = stoke.nextToken(); else { out.write(usage); return false; } try (NetcdfFile nc = NetcdfDataset.openFile(filename, ct)) { // the rest of the command int pos = command.indexOf(filename); command = command.substring(pos + filename.length()); return print(nc, command, out, ct); } catch (java.io.FileNotFoundException e) { out.write("file not found= "); out.write(filename); return false; } finally { out.close(); } }
java
{ "resource": "" }
q174790
NCdumpW.print
test
public static boolean print(NetcdfFile nc, String command, Writer out, ucar.nc2.util.CancelTask ct) throws IOException { WantValues showValues = WantValues.none; boolean ncml = false; boolean strict = false; String varNames = null; String trueDataset = null; String fakeDataset = null; if (command != null) { StringTokenizer stoke = new StringTokenizer(command); while (stoke.hasMoreTokens()) { String toke = stoke.nextToken(); if (toke.equalsIgnoreCase("-help")) { out.write(usage); out.write('\n'); return true; } if (toke.equalsIgnoreCase("-vall")) showValues = WantValues.all; if (toke.equalsIgnoreCase("-c") && (showValues == WantValues.none)) showValues = WantValues.coordsOnly; if (toke.equalsIgnoreCase("-ncml")) ncml = true; if (toke.equalsIgnoreCase("-cdl") || toke.equalsIgnoreCase("-strict")) strict = true; if(toke.equalsIgnoreCase("-v") && stoke.hasMoreTokens()) varNames = stoke.nextToken(); if (toke.equalsIgnoreCase("-datasetname") && stoke.hasMoreTokens()) { fakeDataset = stoke.nextToken(); if(fakeDataset.length() == 0) fakeDataset = null; if(fakeDataset != null) { trueDataset = nc.getLocation(); nc.setLocation(fakeDataset); } } } } boolean ok = print(nc, out, showValues, ncml, strict, varNames, ct); if(trueDataset != null && fakeDataset != null) nc.setLocation(trueDataset); return ok; }
java
{ "resource": "" }
q174791
NCdumpW.printVariableData
test
static public String printVariableData(VariableIF v, ucar.nc2.util.CancelTask ct) throws IOException { Array data = v.read(); /* try { data = v.isMemberOfStructure() ? v.readAllStructures(null, true) : v.read(); } catch (InvalidRangeException ex) { return ex.getMessage(); } */ StringWriter writer = new StringWriter(10000); printArray(data, v.getFullName(), new PrintWriter(writer), new Indent(2), ct); return writer.toString(); }
java
{ "resource": "" }
q174792
NCdumpW.printVariableDataSection
test
static public String printVariableDataSection(Variable v, String sectionSpec, ucar.nc2.util.CancelTask ct) throws IOException, InvalidRangeException { Array data = v.read(sectionSpec); StringWriter writer = new StringWriter(20000); printArray(data, v.getFullName(), new PrintWriter(writer), new Indent(2), ct); return writer.toString(); }
java
{ "resource": "" }
q174793
NCdumpW.printStructureData
test
static public void printStructureData(PrintWriter out, StructureData sdata) throws IOException { printStructureData(out, sdata, new Indent(2), null); out.flush(); }
java
{ "resource": "" }
q174794
NCdumpW.printArrayPlain
test
static public void printArrayPlain(Array ma, PrintWriter out) { ma.resetLocalIterator(); while (ma.hasNext()) { out.print(ma.next()); out.print(' '); } }
java
{ "resource": "" }
q174795
NCdumpW.printArray
test
static public void printArray(Array array, PrintWriter pw) { printArray(array, null, null, pw, new Indent(2), null, true); }
java
{ "resource": "" }
q174796
NCdumpW.writeNcML
test
static public void writeNcML(NetcdfFile ncfile, Writer writer, WantValues showValues, String url) throws IOException { Preconditions.checkNotNull(ncfile); Preconditions.checkNotNull(writer); Preconditions.checkNotNull(showValues); Predicate<Variable> writeVarsPred; switch (showValues) { case none: writeVarsPred = NcMLWriter.writeNoVariablesPredicate; break; case coordsOnly: writeVarsPred = NcMLWriter.writeCoordinateVariablesPredicate; break; case all: writeVarsPred = NcMLWriter.writeAllVariablesPredicate; break; default: String message = String.format( "CAN'T HAPPEN: showValues (%s) != null and checked all possible enum values.", showValues); throw new AssertionError(message); } NcMLWriter ncmlWriter = new NcMLWriter(); ncmlWriter.setWriteVariablesPredicate(writeVarsPred); Element netcdfElement = ncmlWriter.makeNetcdfElement(ncfile, url); ncmlWriter.writeToWriter(netcdfElement, writer); }
java
{ "resource": "" }
q174797
AbstractTransformBuilder.readAttributeDouble
test
protected double readAttributeDouble(AttributeContainer v, String attname, double defValue) { Attribute att = v.findAttributeIgnoreCase(attname); if (att == null) return defValue; if (att.isString()) return Double.parseDouble(att.getStringValue()); else return att.getNumericValue().doubleValue(); }
java
{ "resource": "" }
q174798
AbstractTransformBuilder.addParameter
test
protected boolean addParameter(CoordinateTransform rs, String paramName, NetcdfFile ds, String varNameEscaped) { if (null == (ds.findVariable(varNameEscaped))) { if (null != errBuffer) errBuffer.format("CoordTransBuilder %s: no Variable named %s%n", getTransformName(), varNameEscaped); return false; } rs.addParameter(new Parameter(paramName, varNameEscaped)); return true; }
java
{ "resource": "" }
q174799
AccessLogParser.main
test
public static void main(String[] args) throws IOException { AccessLogParser p = new AccessLogParser(); String line = "24.18.236.132 - - [04/Feb/2011:17:49:03 -0700] \"GET /thredds/fileServer//nexrad/level3/N0R/YUX/20110205/Level3_YUX_N0R_20110205_0011.nids \" 200 10409 \"-\" \"-\" 17"; Matcher m = regPattern.matcher(line); System.out.printf("%s %s%n", m.matches(), m); for (int i=0; i<m.groupCount(); i++) { System.out.println(" "+i+ " "+m.group(i)); } LogReader.Log log = p.parseLog(line); System.out.printf("%s%n", log); }
java
{ "resource": "" }