_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q174300 | DateRange.setEnd | test | public void setEnd(DateType end) {
this.end = end;
useEnd = true;
if (useStart) {
this.isMoving = this.start.isPresent() || this.end.isPresent();
useDuration = false;
recalcDuration();
} else {
this.isMoving = this.end.isPresent();
this.start = this.end.subtract(duration);
}
checkIfEmpty();
} | java | {
"resource": ""
} |
q174301 | DateRange.setDuration | test | public void setDuration(TimeDuration duration) {
this.duration = duration;
useDuration = true;
if (useStart) {
this.isMoving = this.start.isPresent();
this.end = this.start.add(duration);
useEnd = false;
} else {
this.isMoving = this.end.isPresent();
this.start = this.end.subtract(duration);
}
checkIfEmpty();
} | java | {
"resource": ""
} |
q174302 | DateRange.recalcDuration | test | private void recalcDuration() {
long min = getStart().getDate().getTime();
long max = getEnd().getDate().getTime();
double secs = .001 * (max - min);
if (secs < 0)
secs = 0;
if (duration == null) {
try {
duration = new TimeDuration(chooseResolution(secs));
} catch (ParseException e) {
// cant happen
throw new RuntimeException(e);
}
}
if (resolution == null) {
duration.setValueInSeconds(secs);
} else {
// make it a multiple of resolution
double resSecs = resolution.getValueInSeconds();
double closest = Math.round(secs / resSecs);
secs = closest * resSecs;
duration.setValueInSeconds(secs);
}
hashCode = 0;
} | java | {
"resource": ""
} |
q174303 | GridUI.addMapBean | test | public void addMapBean( MapBean mb) {
mapBeanMenu.addAction( mb.getActionDesc(), mb.getIcon(), mb.getAction());
// first one is the "default"
if (mapBeanCount == 0) {
setMapRenderer( mb.getRenderer());
}
mapBeanCount++;
mb.addPropertyChangeListener( new PropertyChangeListener() {
public void propertyChange( java.beans.PropertyChangeEvent e) {
if (e.getPropertyName().equals("Renderer")) {
setMapRenderer( (Renderer) e.getNewValue());
}
}
});
} | java | {
"resource": ""
} |
q174304 | CELexer.yyerror | test | public void yyerror(String s)
{
System.err.println("CEParserImpl.yyerror: " + s + "; parse failed at char: " + charno + "; near: ");
String context = getInput();
int show = (context.length() < CONTEXTLEN ? context.length() : CONTEXTLEN);
System.err.println(context.substring(context.length() - show) + "^");
new Exception().printStackTrace(System.err);
} | java | {
"resource": ""
} |
q174305 | DtCoverageDataset.getName | test | public String getName() {
String loc = ncd.getLocation();
int pos = loc.lastIndexOf('/');
if (pos < 0)
pos = loc.lastIndexOf('\\');
return (pos < 0) ? loc : loc.substring(pos + 1);
} | java | {
"resource": ""
} |
q174306 | LambertConformalConicEllipse.paramsToString | test | public String paramsToString() {
Formatter f = new Formatter();
f.format("origin lat,lon=%f,%f parellels=%f,%f earth=%s", lat0deg, lon0deg, par1deg, par2deg, earth );
return f.toString();
} | java | {
"resource": ""
} |
q174307 | FileDSP.open | test | public FileDSP
open(byte[] rawdata)
throws DapException
{
try {
this.raw = rawdata;
ByteArrayInputStream stream = new ByteArrayInputStream(this.raw);
ChunkInputStream rdr = new ChunkInputStream(stream, RequestMode.DAP);
String document = rdr.readDMR();
byte[] serialdata = DapUtil.readbinaryfile(rdr);
super.build(document, serialdata, rdr.getRemoteByteOrder());
return this;
} catch (IOException ioe) {
throw new DapException(ioe).setCode(DapCodes.SC_INTERNAL_SERVER_ERROR);
}
} | java | {
"resource": ""
} |
q174308 | HorizCoordSys2D.computeBounds | test | private Optional<List<RangeIterator>> computeBounds(LatLonRect llbb, int horizStride) {
synchronized (this) {
if (edges == null) edges = new Edges();
}
return edges.computeBoundsExhaustive(llbb, horizStride);
} | java | {
"resource": ""
} |
q174309 | RangeDateSelector.synchUI | test | private void synchUI(boolean slidersOK) {
eventOK = false;
if (slidersOK) minSlider.setValue(scale.world2slider(dateRange.getStart()));
minField.setValue(dateRange.getStart());
if (maxField != null) {
if (slidersOK) maxSlider.setValue(scale.world2slider(dateRange.getEnd()));
maxField.setValue(dateRange.getEnd());
}
if (durationField != null)
durationField.setValue(dateRange.getDuration());
eventOK = true;
} | java | {
"resource": ""
} |
q174310 | Nc4ChunkingDefault.computeUnlimitedChunking | test | public int[] computeUnlimitedChunking(List<Dimension> dims, int elemSize) {
int maxElements = defaultChunkSize / elemSize;
int[] result = fillRightmost(convertUnlimitedShape(dims), maxElements);
long resultSize = new Section(result).computeSize();
if (resultSize < minChunksize) {
maxElements = minChunksize / elemSize;
result = incrUnlimitedShape(dims, result, maxElements);
}
return result;
} | java | {
"resource": ""
} |
q174311 | CatalogWatcher.register | test | public void register(Path dir) throws IOException {
if (!enable) return;
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
if (trace) {
Path prev = keys.get(key);
if (prev == null) {
System.out.format("CatalogWatcher register: %s%n", dir);
} else {
if (!dir.equals(prev)) {
System.out.format("update: %s -> %s%n", prev, dir);
}
}
}
keys.put(key, dir);
} | java | {
"resource": ""
} |
q174312 | CatalogWatcher.processEvents | test | public void processEvents() {
if (!enable) return;
for (; ; ) {
// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
System.err.println("WatchKey not recognized!!");
continue;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
// TBD - provide example of how OVERFLOW event is handled
if (kind == OVERFLOW) {
continue;
}
// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
// print out event
System.out.format("%s: %s%n", event.kind().name(), child);
// if directory is created, and watching recursively, then
// register it and its sub-directories
if (recursive && (kind == ENTRY_CREATE)) {
try {
if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
registerAll(child);
}
} catch (IOException x) {
// ignore to keep sample readbale
}
}
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
} | java | {
"resource": ""
} |
q174313 | TimeHelper.setReferenceDate | test | public TimeHelper setReferenceDate(CalendarDate refDate) {
CalendarDateUnit cdUnit = CalendarDateUnit.of(dateUnit.getCalendar(), dateUnit.getCalendarField(), refDate);
return new TimeHelper(cdUnit);
} | java | {
"resource": ""
} |
q174314 | FeatureDatasetFactoryManager.open | test | static public FeatureDataset open(FeatureType wantFeatureType, String location, ucar.nc2.util.CancelTask task, Formatter errlog) throws IOException {
// special processing for thredds: datasets
if (location.startsWith(DataFactory.SCHEME)) {
DataFactory.Result result = new DataFactory().openFeatureDataset(wantFeatureType, location, task);
errlog.format("%s", result.errLog);
if (!featureTypeOk(wantFeatureType, result.featureType)) {
errlog.format("wanted %s but dataset is of type %s%n", wantFeatureType, result.featureType);
result.close();
return null;
}
return result.featureDataset;
// special processing for cdmrFeature: datasets
} else if (location.startsWith(CdmrFeatureDataset.SCHEME)) {
Optional<FeatureDataset> opt = CdmrFeatureDataset.factory(wantFeatureType, location);
if (opt.isPresent()) return opt.get();
errlog.format("%s", opt.getErrorMessage());
return null;
// special processing for collection: datasets
} else if (location.startsWith(ucar.nc2.ft.point.collection.CompositeDatasetFactory.SCHEME)) {
String spec = location.substring(CompositeDatasetFactory.SCHEME.length());
MFileCollectionManager dcm = MFileCollectionManager.open(spec, spec, null, errlog); // LOOK we dont have a name
return CompositeDatasetFactory.factory(location, wantFeatureType, dcm, errlog);
}
DatasetUrl durl = DatasetUrl.findDatasetUrl(location); // Cache ServiceType so we don't have to keep figuring it out
if (durl.serviceType == null) { // skip GRIB check for anything not a plain ole file
// check if its GRIB, may not have to go through NetcdfDataset
Optional<FeatureDatasetCoverage> opt = CoverageDatasetFactory.openGrib(location);
if (opt.isPresent()) { // its a GRIB file
return opt.get();
} else if (!opt.getErrorMessage().startsWith(CoverageDatasetFactory.NOT_GRIB_FILE) &&
!opt.getErrorMessage().startsWith(CoverageDatasetFactory.NO_GRIB_CLASS)) {
errlog.format("%s%n", opt.getErrorMessage()); // its a GRIB file with an error
return null;
}
}
// otherwise open as NetcdfDataset and run it through the FeatureDatasetFactories
NetcdfDataset ncd = NetcdfDataset.acquireDataset(durl, true, task);
FeatureDataset fd = wrap(wantFeatureType, ncd, task, errlog);
if (fd == null)
ncd.close();
return fd;
} | java | {
"resource": ""
} |
q174315 | FeatureDatasetFactoryManager.wrap | test | static public FeatureDataset wrap(FeatureType wantFeatureType, NetcdfDataset ncd, ucar.nc2.util.CancelTask task, Formatter errlog) throws IOException {
if (debug) System.out.println("wrap " + ncd.getLocation() + " want = " + wantFeatureType);
// the case where we dont know what type it is
if ((wantFeatureType == null) || (wantFeatureType == FeatureType.ANY)) {
return wrapUnknown(ncd, task, errlog);
}
// find a Factory that claims this dataset by passing back an "analysis result" object
Object analysis = null;
FeatureDatasetFactory useFactory = null;
for (Factory fac : factoryList) {
if (!featureTypeOk(wantFeatureType, fac.featureType)) continue;
if (debug) System.out.println(" wrap try factory " + fac.factory.getClass().getName());
analysis = fac.factory.isMine(wantFeatureType, ncd, errlog);
if (analysis != null) {
useFactory = fac.factory;
break;
}
}
if (null == useFactory) {
errlog.format("**Failed to find FeatureDatasetFactory for= %s datatype=%s%n", ncd.getLocation(), wantFeatureType);
return null;
}
// this call must be thread safe - done by implementation
return useFactory.open(wantFeatureType, ncd, analysis, task, errlog);
} | java | {
"resource": ""
} |
q174316 | FeatureDatasetFactoryManager.featureTypeOk | test | static public boolean featureTypeOk(FeatureType want, FeatureType facType) {
if (want == null) return true;
if (want == facType) return true;
if (want == FeatureType.ANY_POINT) {
return facType.isPointFeatureType();
}
if (facType == FeatureType.ANY_POINT) {
return want.isPointFeatureType();
}
if (want == FeatureType.COVERAGE) {
return facType.isCoverageFeatureType();
}
if (want == FeatureType.GRID) { // for backwards compatibility
return facType.isCoverageFeatureType();
}
if (want == FeatureType.SIMPLE_GEOMETRY) {
return facType.isCoverageFeatureType();
}
if (want == FeatureType.UGRID) {
return facType.isUnstructuredGridFeatureType();
}
return false;
} | java | {
"resource": ""
} |
q174317 | FeatureDatasetFactoryManager.findFeatureType | test | static public FeatureType findFeatureType(NetcdfFile ncd) {
// search for explicit featureType global attribute
String cdm_datatype = ncd.findAttValueIgnoreCase(null, CF.FEATURE_TYPE, null);
if (cdm_datatype == null)
cdm_datatype = ncd.findAttValueIgnoreCase(null, "cdm_data_type", null);
if (cdm_datatype == null)
cdm_datatype = ncd.findAttValueIgnoreCase(null, "cdm_datatype", null);
if (cdm_datatype == null)
cdm_datatype = ncd.findAttValueIgnoreCase(null, "thredds_data_type", null);
if (cdm_datatype != null) {
for (FeatureType ft : FeatureType.values())
if (cdm_datatype.equalsIgnoreCase(ft.name())) {
if (debug) System.out.println(" wrapUnknown found cdm_datatype " + cdm_datatype);
return ft;
}
}
CF.FeatureType cff = CF.FeatureType.getFeatureTypeFromGlobalAttribute(ncd);
if (cff != null) return CF.FeatureType.convert(cff);
return null;
} | java | {
"resource": ""
} |
q174318 | ConfigCatalogHtmlWriter.writeCatalog | test | public int writeCatalog(HttpServletRequest req, HttpServletResponse res, Catalog cat, boolean isLocalCatalog) throws IOException {
String catHtmlAsString = convertCatalogToHtml(cat, isLocalCatalog);
// Once this header is set, we know the encoding, and thus the actual
// number of *bytes*, not characters, to encode
res.setContentType(ContentType.html.getContentHeader());
int len = ServletUtil.setResponseContentLength(res, catHtmlAsString);
if (!req.getMethod().equals("HEAD")) {
PrintWriter writer = res.getWriter();
writer.write(catHtmlAsString);
writer.flush();
}
return len;
} | java | {
"resource": ""
} |
q174319 | ConfigCatalogHtmlWriter.convertCatalogToHtml | test | String convertCatalogToHtml(Catalog cat, boolean isLocalCatalog) {
StringBuilder sb = new StringBuilder(10000);
String uri = cat.getUriString();
if (uri == null) uri = cat.getName();
if (uri == null) uri = "unknown";
String catname = Escape.html(uri);
// Render the page header
sb.append(getHtmlDoctypeAndOpenTag()); // "<html>\n" );
sb.append("<head>\r\n");
sb.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
sb.append("<title>");
//if (cat.isStatic())
// sb.append("TdsStaticCatalog ").append(catname); // for searching
//else
sb.append("Catalog ").append(catname);
sb.append("</title>\r\n");
sb.append(getTdsCatalogCssLink()).append("\n");
sb.append(this.getGoogleTrackingContent());
sb.append("</head>\r\n");
sb.append("<body>");
sb.append("<h1>");
// Logo
//String logoUrl = this.htmlConfig.getInstallLogoUrl();
String logoUrl = htmlConfig.prepareUrlStringForHtml(htmlConfig.getInstallLogoUrl());
if (logoUrl != null) {
sb.append("<img src='").append(logoUrl);
String logoAlt = htmlConfig.getInstallLogoAlt();
if (logoAlt != null) sb.append("' alt='").append(logoAlt);
sb.append("' align='left' valign='top'").append(">\n");
}
sb.append(" Catalog ").append(catname);
sb.append("</h1>");
sb.append("<HR size='1' noshade='noshade'>");
sb.append("<table width='100%' cellspacing='0' cellpadding='5' align='center'>\r\n");
// Render the column headings
sb.append("<tr>\r\n");
sb.append("<th align='left'><font size='+1'>");
sb.append("Dataset");
sb.append("</font></th>\r\n");
sb.append("<th align='center'><font size='+1'>");
sb.append("Size");
sb.append("</font></th>\r\n");
sb.append("<th align='right'><font size='+1'>");
sb.append("Last Modified");
sb.append("</font></th>\r\n");
sb.append("</tr>");
// Recursively render the datasets
doDatasets(cat, cat.getDatasetsLocal(), sb, false, 0, isLocalCatalog);
// Render the page footer
sb.append("</table>\r\n");
sb.append("<HR size='1' noshade='noshade'>");
appendSimpleFooter(sb);
sb.append("</body>\r\n");
sb.append("</html>\r\n");
return (sb.toString());
} | java | {
"resource": ""
} |
q174320 | ConfigCatalogHtmlWriter.getUserCSS | test | public String getUserCSS() {
return new StringBuilder()
.append("<link rel='stylesheet' href='")
.append(this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getPageCssUrl()))
.append("' type='text/css' >").toString();
} | java | {
"resource": ""
} |
q174321 | ConfigCatalogHtmlWriter.getUserHead | test | public String getUserHead() {
return new StringBuilder()
.append("<table width='100%'><tr><td>\n")
.append(" <img src='").append(this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getHostInstLogoUrl()))
.append("'\n")
.append(" alt='").append(this.htmlConfig.getHostInstLogoAlt()).append("'\n")
.append(" align='left' valign='top'\n")
.append(" hspace='10' vspace='2'>\n")
.append(" <h3><strong>").append(this.tdsContext.getWebappDisplayName()).append("</strong></h3>\n")
.append("</td></tr></table>\n")
.toString();
} | java | {
"resource": ""
} |
q174322 | CatalogManager.makeDynamicCatalog | test | private Object makeDynamicCatalog(String path, URI baseURI) throws IOException {
boolean isLatest = path.endsWith("/latest.xml");
// strip off the filename
int pos = path.lastIndexOf("/");
String workPath = (pos >= 0) ? path.substring(0, pos) : path;
String filename = (pos > 0) ? path.substring(pos + 1) : path;
// now look through the data roots for a maximal match
DataRootManager.DataRootMatch match = dataRootManager.findDataRootMatch(workPath);
if (match == null)
return null;
// Feature Collection
if (match.dataRoot.getFeatureCollection() != null) {
InvDatasetFeatureCollection fc = featureCollectionCache.get(match.dataRoot.getFeatureCollection());
if (isLatest)
return fc.makeLatest(match.remaining, path, baseURI);
else
return fc.makeCatalog(match.remaining, path, baseURI);
}
// DatasetScan
DatasetScan dscan = match.dataRoot.getDatasetScan();
if (dscan != null) {
if (log.isDebugEnabled()) log.debug("makeDynamicCatalog(): Calling DatasetScan.makeCatalogForDirectory( " + baseURI + ", " + path + ").");
CatalogBuilder cat;
if (isLatest)
cat = dscan.makeCatalogForLatest(workPath, baseURI);
else
cat = dscan.makeCatalogForDirectory(workPath, baseURI);
if (null == cat)
log.error("makeDynamicCatalog(): DatasetScan.makeCatalogForDirectory failed = " + workPath);
return cat;
}
// CatalogScan
CatalogScan catScan = match.dataRoot.getCatalogScan();
if (catScan != null) {
if (!filename.equalsIgnoreCase(CatalogScan.CATSCAN)) { // its an actual catalog
return catScan.getCatalog(tdsContext.getThreddsDirectory(), match.remaining, filename, ccc);
}
if (log.isDebugEnabled()) log.debug("makeDynamicCatalog(): Calling CatalogScan.makeCatalogForDirectory( " + baseURI + ", " + path + ").");
CatalogBuilder cat = catScan.makeCatalogFromDirectory(tdsContext.getThreddsDirectory(), match.remaining, baseURI);
if (null == cat)
log.error("makeDynamicCatalog(): CatalogScan.makeCatalogForDirectory failed = " + workPath);
return cat;
}
log.warn("makeDynamicCatalog() failed for =" + workPath + " request path= " + path);
return null;
} | java | {
"resource": ""
} |
q174323 | CatalogManager.addGlobalServices | test | private void addGlobalServices(CatalogBuilder cat) {
// look for datasets that want to use global services
Set<String> allServiceNames = new HashSet<>();
findServices(cat.getDatasets(), allServiceNames); // all services used
if (!allServiceNames.isEmpty()) {
List<Service> servicesMissing = new ArrayList<>(); // all services missing
for (String name : allServiceNames) {
if (cat.hasServiceInDataset(name)) continue;
Service s = globalServices.findGlobalService(name);
if (s != null) servicesMissing.add(s);
}
servicesMissing.forEach(cat::addService);
}
// look for datasets that want to use standard services
for (DatasetBuilder node : cat.getDatasets()) {
String sname = (String) node.getFldOrInherited(Dataset.ServiceName);
String urlPath = (String) node.get(Dataset.UrlPath);
String ftypeS = (String) node.getFldOrInherited(Dataset.FeatureType);
if (sname == null && urlPath != null && ftypeS != null) {
Service s = globalServices.getStandardServices(ftypeS);
if (s != null) {
node.put(Dataset.ServiceName, s.getName());
cat.addService(s);
}
}
}
} | java | {
"resource": ""
} |
q174324 | HttpClientManager.init | test | static public void init(CredentialsProvider provider, String userAgent)
{
if (provider != null)
try {
HTTPSession.setGlobalCredentialsProvider(provider);
} catch (HTTPException e) {
throw new IllegalArgumentException(e);
}
if (userAgent != null)
HTTPSession.setGlobalUserAgent(userAgent + "/NetcdfJava/HttpClient");
else
HTTPSession.setGlobalUserAgent("NetcdfJava/HttpClient");
} | java | {
"resource": ""
} |
q174325 | HttpClientManager.getContentAsString | test | @Urlencoded
@Deprecated
public static String getContentAsString(HTTPSession session, String urlencoded) throws IOException
{
HTTPSession useSession = session;
try {
if (useSession == null)
useSession = HTTPFactory.newSession(urlencoded);
try (HTTPMethod m = HTTPFactory.Get(useSession, urlencoded)) {
m.execute();
return m.getResponseAsString();
}
} finally {
if ((session == null) && (useSession != null))
useSession.close();
}
} | java | {
"resource": ""
} |
q174326 | HttpClientManager.putContent | test | public static int putContent(String urlencoded, String content) throws IOException
{
try (HTTPMethod m = HTTPFactory.Put(urlencoded)) {
m.setRequestContent(new StringEntity(content, "application/text", "UTF-8"));
m.execute();
int resultCode = m.getStatusCode();
// followRedirect wont work for PUT
if (resultCode == 302) {
String redirectLocation;
Header locationHeader = m.getResponseHeader("location");
if (locationHeader != null) {
redirectLocation = locationHeader.getValue();
resultCode = putContent(redirectLocation, content);
}
}
return resultCode;
}
} | java | {
"resource": ""
} |
q174327 | D4TSServlet.getFrontPage | test | protected FrontPage
getFrontPage(DapRequest drq, DapContext cxt)
throws DapException
{
if(this.defaultroots == null) {
// Figure out the directory containing
// the files to display.
String pageroot;
pageroot = getResourcePath(drq, "");
if(pageroot == null)
throw new DapException("Cannot locate resources directory");
this.defaultroots = new ArrayList<>();
this.defaultroots.add(
new Root("testfiles",pageroot));
}
return new FrontPage(this.defaultroots, drq);
} | java | {
"resource": ""
} |
q174328 | InvDatasetFcGrib.makeCatalog | test | @Override
public CatalogBuilder makeCatalog(String match, String reqPath, URI catURI) throws IOException {
StateGrib localState = (StateGrib) checkState();
if (localState == null) return null; // not ready yet maybe
if (localState.gribCollection == null) return null; // not ready yet maybe
try {
// case 0
if ((match == null) || (match.length() == 0)) {
return makeCatalogTop(catURI, localState); // top catalog : uses state.top previously made in checkState()
}
// case 1
if (localState.gribCollection instanceof PartitionCollectionImmutable) {
String[] paths = match.split("/");
PartitionCollectionImmutable pc = (PartitionCollectionImmutable) localState.gribCollection;
return makeCatalogFromPartition(pc, paths, 0, catURI);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Error making catalog for " + configPath, e);
}
return null;
} | java | {
"resource": ""
} |
q174329 | InvDatasetFcGrib.extractGeospatial | test | private ThreddsMetadata.GeospatialCoverage extractGeospatial(GribCollectionImmutable.GroupGC group) {
GdsHorizCoordSys gdsCoordSys = group.getGdsHorizCoordSys();
LatLonRect llbb = GridCoordSys.getLatLonBoundingBox(gdsCoordSys.proj, gdsCoordSys.getStartX(), gdsCoordSys.getStartY(),
gdsCoordSys.getEndX(), gdsCoordSys.getEndY());
double dx = 0.0, dy = 0.0;
if (gdsCoordSys.isLatLon()) {
dx = Math.abs(gdsCoordSys.dx);
dy = Math.abs(gdsCoordSys.dy);
}
return new ThreddsMetadata.GeospatialCoverage(llbb, null, dx, dy);
} | java | {
"resource": ""
} |
q174330 | InvDatasetFcGrib.getSingleDatasetOrByTypeName | test | public GribCollectionImmutable.Dataset getSingleDatasetOrByTypeName(GribCollectionImmutable gc, String typeName) {
if (gc.getDatasets().size() == 1) return gc.getDataset(0);
for (GribCollectionImmutable.Dataset ds : gc.getDatasets())
if (ds.getType().toString().equalsIgnoreCase(typeName)) return ds;
return null;
} | java | {
"resource": ""
} |
q174331 | VertCoordValue.nearlyEquals | test | public boolean nearlyEquals(VertCoordValue other) {
return Misc.nearlyEquals(value1, other.value1) && Misc.nearlyEquals(value2, other.value2);
} | java | {
"resource": ""
} |
q174332 | UnitID.newUnitID | test | public static UnitID newUnitID(final String name, final String plural,
final String symbol) {
UnitID id;
try {
id = name == null
? new UnitSymbol(symbol)
: UnitName.newUnitName(name, plural, symbol);
}
catch (final NameException e) {
id = null; // can't happen
}
return id;
} | java | {
"resource": ""
} |
q174333 | GradsAttribute.parseAttribute | test | public static GradsAttribute parseAttribute(String attrSpec) {
String[] toks = attrSpec.split("\\s+");
StringBuffer buf = new StringBuffer();
for (int i = 4; i < toks.length; i++) {
buf.append(toks[i]);
buf.append(" ");
}
// toks[0] is "@"
return new GradsAttribute(toks[1], toks[2], toks[3],
buf.toString().trim());
} | java | {
"resource": ""
} |
q174334 | NOWRadheader.readTop | test | int readTop(ucar.unidata.io.RandomAccessFile raf) throws IOException {
int pos = 0;
// long actualSize = 0;
raf.seek(pos);
int readLen = 35;
// Read in the contents of the NEXRAD Level III product head
byte[] b = new byte[readLen];
int rc = raf.read(b);
if (rc != readLen) {
return 0;
}
// check
if ((convertunsignedByte2Short(b[0]) != 0x00) || (convertunsignedByte2Short(b[1]) != 0xF0)
|| (convertunsignedByte2Short(b[2]) != 0x09)) {
return 0;
}
String pidd = new String(b, 15, 5, CDM.utf8Charset);
if (pidd.contains("NOWRA") || pidd.contains("USRAD") || pidd.contains("NEX")) {
return 1;
} else {
return 0;
}
} | java | {
"resource": ""
} |
q174335 | NOWRadheader.shortsToInt | test | public static int shortsToInt(short s1, short s2, boolean swapBytes) {
byte[] b = new byte[4];
b[0] = (byte) (s1 >>> 8);
b[1] = (byte) (s1 >>> 0);
b[2] = (byte) (s2 >>> 8);
b[3] = (byte) (s2 >>> 0);
return bytesToInt(b, false);
} | java | {
"resource": ""
} |
q174336 | NOWRadheader.bytesToInt | test | public static int bytesToInt(byte[] bytes, boolean swapBytes) {
byte a = bytes[0];
byte b = bytes[1];
byte c = bytes[2];
byte d = bytes[3];
if (swapBytes) {
return ((a & 0xff)) + ((b & 0xff) << 8) + ((c & 0xff) << 16) + ((d & 0xff) << 24);
} else {
return ((a & 0xff) << 24) + ((b & 0xff) << 16) + ((c & 0xff) << 8) + ((d & 0xff));
}
} | java | {
"resource": ""
} |
q174337 | NOWRadheader.getDate | test | static public java.util.Date getDate(int julianDays, int msecs) {
long total = ((long) (julianDays - 1)) * 24 * 3600 * 1000 + msecs;
return new Date(total);
} | java | {
"resource": ""
} |
q174338 | N3iosp.makeValidNetcdfObjectName | test | public static String makeValidNetcdfObjectName(String name) {
StringBuilder sb = new StringBuilder(name);
while (sb.length() > 0) {
int cp = sb.codePointAt(0);
// First char must be [a-z][A-Z][0-9]_ | UTF8
if (cp <= 0x7f) {
if (!('A' <= cp && cp <= 'Z')
&& !('a' <= cp && cp <= 'z')
&& !('0' <= cp && cp <= '9')
&& cp != '_') {
sb.deleteCharAt(0);
continue;
}
}
break;
}
for (int pos = 1; pos < sb.length(); ++pos) {
int cp = sb.codePointAt(pos);
// handle simple 0x00-0x7F characters here
if (cp <= 0x7F) {
if (cp < ' ' || cp > 0x7E || cp == '/') { // control char, DEL, or forward-slash
sb.deleteCharAt(pos);
--pos;
}
}
}
while (sb.length() > 0) {
int cp = sb.codePointAt(sb.length() - 1);
if (cp <= 0x7f && Character.isWhitespace(cp)) {
sb.deleteCharAt(sb.length() - 1);
} else {
break;
}
}
if (sb.length() == 0) {
throw new IllegalArgumentException(String.format("Illegal NetCDF object name: '%s'", name));
}
return sb.toString();
} | java | {
"resource": ""
} |
q174339 | N3iosp.isValidNetcdf3ObjectName | test | static public boolean isValidNetcdf3ObjectName(String name) {
Matcher m = objectNamePatternOld.matcher(name);
return m.matches();
} | java | {
"resource": ""
} |
q174340 | N3iosp.openForWriting | test | @Override
public void openForWriting(ucar.unidata.io.RandomAccessFile raf, ucar.nc2.NetcdfFile ncfile,
ucar.nc2.util.CancelTask cancelTask) throws IOException {
open(raf, ncfile, cancelTask);
} | java | {
"resource": ""
} |
q174341 | N3iosp.readRecordData | test | private ucar.ma2.Array readRecordData(ucar.nc2.Structure s, Section section) throws java.io.IOException {
//if (s.isSubset())
// return readRecordDataSubset(s, section);
// has to be 1D
Range recordRange = section.getRange(0);
// create the ArrayStructure
StructureMembers members = s.makeStructureMembers();
for (StructureMembers.Member m : members.getMembers()) {
Variable v2 = s.findVariable(m.getName());
N3header.Vinfo vinfo = (N3header.Vinfo) v2.getSPobject();
m.setDataParam((int) (vinfo.begin - header.recStart));
}
// protect agains too large of reads
if (header.recsize > Integer.MAX_VALUE)
throw new IllegalArgumentException("Cant read records when recsize > "+Integer.MAX_VALUE);
long nrecs = section.computeSize();
if (nrecs * header.recsize > Integer.MAX_VALUE)
throw new IllegalArgumentException("Too large read: nrecs * recsize= "+(nrecs * header.recsize) +"bytes exceeds "+Integer.MAX_VALUE);
members.setStructureSize((int) header.recsize);
ArrayStructureBB structureArray = new ArrayStructureBB(members, new int[]{recordRange.length()});
// note dependency on raf; should probably defer to subclass
// loop over records
byte[] result = structureArray.getByteBuffer().array();
int count = 0;
for (int recnum : recordRange) {
if (debugRecord) System.out.println(" read record " + recnum);
raf.seek(header.recStart + recnum * header.recsize); // where the record starts
if (recnum != header.numrecs - 1)
raf.readFully(result, (int) (count * header.recsize), (int) header.recsize);
else
raf.read(result, (int) (count * header.recsize), (int) header.recsize); // "wart" allows file to be one byte short. since its always padding, we allow
count++;
}
return structureArray;
} | java | {
"resource": ""
} |
q174342 | N3iosp.readRecordDataSubset | test | private ucar.ma2.Array readRecordDataSubset(ucar.nc2.Structure s, Section section) throws java.io.IOException {
Range recordRange = section.getRange(0);
int nrecords = recordRange.length();
// create the ArrayStructureMA
StructureMembers members = s.makeStructureMembers();
for (StructureMembers.Member m : members.getMembers()) {
Variable v2 = s.findVariable(m.getName());
N3header.Vinfo vinfo = (N3header.Vinfo) v2.getSPobject();
m.setDataParam((int) (vinfo.begin - header.recStart)); // offset from start of record
// construct the full shape
int rank = m.getShape().length;
int[] fullShape = new int[rank + 1];
fullShape[0] = nrecords; // the first dimension
System.arraycopy(m.getShape(), 0, fullShape, 1, rank); // the remaining dimensions
Array data = Array.factory(m.getDataType(), fullShape);
m.setDataArray( data);
m.setDataObject( data.getIndexIterator());
}
//LOOK this is all wrong - why using recsize ???
return null;
/* members.setStructureSize(recsize);
ArrayStructureMA structureArray = new ArrayStructureMA(members, new int[]{nrecords});
// note dependency on raf; should probably defer to subclass
// loop over records
byte[] record = new byte[ recsize];
ByteBuffer bb = ByteBuffer.wrap(record);
for (int recnum = recordRange.first(); recnum <= recordRange.last(); recnum += recordRange.stride()) {
if (debugRecord) System.out.println(" readRecordDataSubset recno= " + recnum);
// read one record
raf.seek(recStart + recnum * recsize); // where the record starts
if (recnum != numrecs - 1)
raf.readFully(record, 0, recsize);
else
raf.read(record, 0, recsize); // "wart" allows file to be one byte short. since its always padding, we allow
// transfer desired variable(s) to result array(s)
for (StructureMembers.Member m : members.getMembers()) {
IndexIterator dataIter = (IndexIterator) m.getDataObject();
IospHelper.copyFromByteBuffer(bb, m, dataIter);
}
}
return structureArray; */
} | java | {
"resource": ""
} |
q174343 | N3iosp.fillNonRecordVariables | test | protected void fillNonRecordVariables() throws IOException {
// run through each variable
for (Variable v : ncfile.getVariables()) {
if (v.isUnlimited()) continue;
try {
writeData(v, v.getShapeAsSection(), makeConstantArray(v));
} catch (InvalidRangeException e) {
e.printStackTrace(); // shouldnt happen
}
}
} | java | {
"resource": ""
} |
q174344 | GradsTimeDimension.makeTimeStruct | test | public GradsTimeStruct makeTimeStruct(int timeIndex) {
double tVal = getValues()[timeIndex];
Date d = DateUnit.getStandardDate(tVal + " " + getUnit());
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
calendar.setTime(d);
return makeTimeStruct(calendar);
} | java | {
"resource": ""
} |
q174345 | GradsTimeDimension.makeTimeStruct | test | private GradsTimeStruct makeTimeStruct(Calendar calendar) {
GradsTimeStruct ts = new GradsTimeStruct();
ts.year = calendar.get(Calendar.YEAR);
ts.month = calendar.get(Calendar.MONTH) + 1; // MONTH is zero based
ts.day = calendar.get(Calendar.DAY_OF_MONTH);
ts.hour = calendar.get(Calendar.HOUR_OF_DAY);
ts.minute = calendar.get(Calendar.MINUTE);
ts.jday = calendar.get(Calendar.DAY_OF_YEAR);
return ts;
} | java | {
"resource": ""
} |
q174346 | GradsTimeDimension.hasTimeTemplate | test | public static boolean hasTimeTemplate(String template) {
for (int i = 0; i < timeTemplates.length; i++) {
if (template.indexOf(timeTemplates[i]) >= 0) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q174347 | FunctionLibrary.add | test | public void add(ServerSideFunction function) {
if (function instanceof BoolFunction) {
boolFunctions.put(function.getName(), function);
}
if (function instanceof BTFunction) {
btFunctions.put(function.getName(), function);
}
} | java | {
"resource": ""
} |
q174348 | FunctionLibrary.getBoolFunction | test | public BoolFunction getBoolFunction(String name)
throws NoSuchFunctionException {
if (!boolFunctions.containsKey(name)) {
loadNewFunction(name);
}
return (BoolFunction) boolFunctions.get(name);
} | java | {
"resource": ""
} |
q174349 | FunctionLibrary.getBTFunction | test | public BTFunction getBTFunction(String name)
throws NoSuchFunctionException {
if (!btFunctions.containsKey(name)) {
loadNewFunction(name);
}
return (BTFunction) btFunctions.get(name);
} | java | {
"resource": ""
} |
q174350 | FunctionLibrary.loadNewFunction | test | protected void loadNewFunction(String name) {
try {
String fullName = prefix + name;
Class value = Class.forName(fullName);
if ((ServerSideFunction.class).isAssignableFrom(value)) {
add((ServerSideFunction) value.newInstance());
return;
}
} catch (ClassNotFoundException e) {
} catch (IllegalAccessException e) {
} catch (InstantiationException e) {
}
} | java | {
"resource": ""
} |
q174351 | McIDASLookup.getLevelName | test | public final String getLevelName(GridRecord gr) {
if (cust != null) {
String result = cust.getLevelNameShort( gr.getLevelType1());
if (result != null) return result;
}
String levelUnit = getLevelUnit(gr);
if (levelUnit != null) {
int level1 = (int) gr.getLevel1();
int level2 = (int) gr.getLevel2();
if (levelUnit.equalsIgnoreCase("hPa")) {
return "pressure";
} else if (level1 == 1013) {
return "mean sea level";
} else if (level1 == 0) {
return "tropopause";
} else if (level1 == 1001) {
return "surface";
} else if (level2 != 0) {
return "layer";
}
}
return "";
} | java | {
"resource": ""
} |
q174352 | McIDASLookup.getLevelDescription | test | public final String getLevelDescription(GridRecord gr) {
if (cust != null) {
String result = cust.getLevelDescription( gr.getLevelType1());
if (result != null) return result;
}
// TODO: flesh this out
return getLevelName(gr);
} | java | {
"resource": ""
} |
q174353 | McIDASLookup.getLevelUnit | test | public final String getLevelUnit(GridRecord gr) {
if (cust != null) {
String result = cust.getLevelUnits( gr.getLevelType1());
if (result != null) return result;
}
return visad.jmet.MetUnits.makeSymbol(((McIDASGridRecord) gr).getLevelUnitName());
} | java | {
"resource": ""
} |
q174354 | McIDASLookup.getProjectionType | test | public final int getProjectionType(GridDefRecord gds) {
String name = getProjectionName(gds).trim();
switch (name) {
case "MERC":
return Mercator;
case "CONF":
return LambertConformal;
case "PS":
return PolarStereographic;
default:
return -1;
}
} | java | {
"resource": ""
} |
q174355 | McIDASLookup.isVerticalCoordinate | test | public final boolean isVerticalCoordinate(GridRecord gr) {
if (cust != null) {
return cust.isVerticalCoordinate(gr.getLevelType1());
}
int type = gr.getLevelType1();
if (((McIDASGridRecord) gr).hasGribInfo()) {
if (type == 20) {
return true;
}
if (type == 100) {
return true;
}
if (type == 101) {
return true;
}
if ((type >= 103) && (type <= 128)) {
return true;
}
if (type == 141) {
return true;
}
if (type == 160) {
return true;
}
} else if (getLevelUnit(gr).equals("hPa")) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q174356 | McIDASLookup.isLayer | test | public boolean isLayer(GridRecord gr) {
if (cust != null) {
return cust.isLayer( gr.getLevelType1());
}
if (gr.getLevel2() == 0) {
return false;
}
return true;
} | java | {
"resource": ""
} |
q174357 | CoordTransBuilder.makeCoordinateTransform | test | static public CoordinateTransform makeCoordinateTransform (NetcdfDataset ds, AttributeContainer ctv, Formatter parseInfo, Formatter errInfo) {
// standard name
String transform_name = ctv.findAttValueIgnoreCase("transform_name", null);
if (null == transform_name)
transform_name = ctv.findAttValueIgnoreCase("Projection_Name", null);
// these names are from CF - dont want to have to duplicate
if (null == transform_name)
transform_name = ctv.findAttValueIgnoreCase(CF.GRID_MAPPING_NAME, null);
if (null == transform_name)
transform_name = ctv.findAttValueIgnoreCase(CF.STANDARD_NAME, null);
if (null == transform_name) {
parseInfo.format("**Failed to find Coordinate Transform name from Variable= %s%n", ctv);
return null;
}
transform_name = transform_name.trim();
// do we have a transform registered for this ?
Class builderClass = null;
for (Transform transform : transformList) {
if (transform.transName.equals(transform_name)) {
builderClass = transform.transClass;
break;
}
}
if (null == builderClass) {
parseInfo.format("**Failed to find CoordTransBuilder name= %s from Variable= %s%n", transform_name, ctv);
return null;
}
// get an instance of that class
Object builderObject;
try {
builderObject = builderClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
log.error("Cant create new instance "+builderClass.getName(), e);
return null;
}
if (null == builderObject) { // cant happen - because this was tested in registerTransform()
parseInfo.format("**Failed to build CoordTransBuilder object from class= %s for Variable= %s%n", builderClass.getName(), ctv);
return null;
}
CoordinateTransform ct;
if (builderObject instanceof VertTransformBuilderIF){
VertTransformBuilderIF vertBuilder = (VertTransformBuilderIF) builderObject;
vertBuilder.setErrorBuffer(errInfo);
ct = vertBuilder.makeCoordinateTransform(ds, ctv);
} else if (builderObject instanceof HorizTransformBuilderIF){
HorizTransformBuilderIF horizBuilder = (HorizTransformBuilderIF) builderObject;
horizBuilder.setErrorBuffer(errInfo);
String units = AbstractTransformBuilder.getGeoCoordinateUnits(ds, ctv); // barfola
ct = horizBuilder.makeCoordinateTransform(ctv, units);
} else {
log.error("Illegals class "+builderClass.getName());
return null;
}
if (ct != null) {
parseInfo.format(" Made Coordinate transform %s from variable %s: %s%n", transform_name, ctv.getName(), builderObject.getClass().getName());
}
return ct;
} | java | {
"resource": ""
} |
q174358 | CoordTransBuilder.makeDummyTransformVariable | test | static public VariableDS makeDummyTransformVariable(NetcdfDataset ds, CoordinateTransform ct) {
VariableDS v = new VariableDS( ds, null, null, ct.getName(), DataType.CHAR, "", null, null);
List<Parameter> params = ct.getParameters();
for (Parameter p : params) {
if (p.isString())
v.addAttribute(new Attribute(p.getName(), p.getStringValue()));
else {
double[] data = p.getNumericValues();
Array dataA = Array.factory(DataType.DOUBLE, new int[]{data.length}, data);
v.addAttribute(new Attribute(p.getName(), dataA));
}
}
v.addAttribute( new Attribute(_Coordinate.TransformType, ct.getTransformType().toString()));
// fake data
Array data = Array.factory(DataType.CHAR, new int[] {}, new char[] {' '});
v.setCachedData(data, true);
return v;
} | java | {
"resource": ""
} |
q174359 | CoordTransBuilder.makeProjection | test | static public ProjectionImpl makeProjection(CoverageTransform gct, Formatter errInfo) {
// standard name
String transform_name = gct.findAttValueIgnoreCase(CF.GRID_MAPPING_NAME, null);
if (null == transform_name) {
errInfo.format("**Failed to find Coordinate Transform name from GridCoordTransform= %s%n", gct);
return null;
}
transform_name = transform_name.trim();
// do we have a transform registered for this ?
Class builderClass = null;
for (Transform transform : transformList) {
if (transform.transName.equals(transform_name)) {
builderClass = transform.transClass;
break;
}
}
if (null == builderClass) {
errInfo.format("**Failed to find CoordTransBuilder name= %s from GridCoordTransform= %s%n", transform_name, gct);
return null;
}
// get an instance of that class
HorizTransformBuilderIF builder;
try {
builder = (HorizTransformBuilderIF) builderClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
log.error("Cant create new instance "+builderClass.getName(), e);
return null;
}
if (null == builder) { // cant happen - because this was tested in registerTransform()
errInfo.format("**Failed to build CoordTransBuilder object from class= %s for GridCoordTransform= %s%n", builderClass.getName(), gct);
return null;
}
String units = gct.findAttValueIgnoreCase(CDM.UNITS, null);
builder.setErrorBuffer( errInfo);
ProjectionCT ct = builder.makeCoordinateTransform(gct, units);
assert ct != null;
return ct.getProjection();
} | java | {
"resource": ""
} |
q174360 | ThreddsDatasetChooser.main | test | public static void main(String args[]) {
boolean usePopup = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-usePopup"))
usePopup = true;
}
try {
store = XMLStore.createFromFile("ThreddsDatasetChooser", null);
p = store.getPreferences();
} catch (IOException e) {
System.out.println("XMLStore Creation failed " + e);
}
// put it together in a JFrame
final JFrame frame = new JFrame("Thredds Dataset Chooser");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
chooser.save();
Rectangle bounds = frame.getBounds();
p.putBeanObject(FRAME_SIZE, bounds);
try {
store.save();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.exit(0);
}
});
chooser = new ThreddsDatasetChooser(p, null, frame, true, usePopup, false);
chooser.setDoResolve(true);
//
frame.getContentPane().add(chooser);
Rectangle bounds = (Rectangle) p.getBean(FRAME_SIZE, new Rectangle(50, 50, 800, 450));
frame.setBounds(bounds);
frame.pack();
frame.setBounds(bounds);
frame.setVisible(true);
} | java | {
"resource": ""
} |
q174361 | FmrcCollectionTable.save | test | public void save() {
collectionNameTable.saveState(false);
dataTable.saveState(false);
prefs.putBeanObject("InfoWindowBounds", infoWindow.getBounds());
prefs.putInt("splitPos", split.getDividerLocation());
} | java | {
"resource": ""
} |
q174362 | FixedYearLengthChronology.withZone | test | @Override
public final Chronology withZone(DateTimeZone zone) {
if (zone.equals(DateTimeZone.UTC)) return this.withUTC();
throw new UnsupportedOperationException("Not supported yet.");
} | java | {
"resource": ""
} |
q174363 | SerialWriter.writeCount | test | public void
writeCount(long count)
throws IOException
{
countbuffer.clear();
countbuffer.putLong(count);
byte[] countbuf = countbuffer.array();
int len = countbuffer.position();
writeBytes(countbuf, len);
if(DEBUG) {
System.err.printf("count: %d%n", count);
}
} | java | {
"resource": ""
} |
q174364 | SerialWriter.writeAtomicArray | test | public void
writeAtomicArray(DapType daptype, Object values)
throws IOException
{
assert values != null && values.getClass().isArray();
ByteBuffer buf = SerialWriter.encodeArray(daptype, values, this.order);
byte[] bytes = buf.array();
int len = buf.position();
writeBytes(bytes, len);
if(DEBUG) {
System.err.printf("%s: ", daptype.getShortName());
for(int i = 0; i < len; i++) {
int x = (int) (order == ByteOrder.BIG_ENDIAN ? bytes[i] : bytes[(len - 1) - i]);
System.err.printf("%02x", (int) (x & 0xff));
}
System.err.println();
}
} | java | {
"resource": ""
} |
q174365 | SerialWriter.writeBytes | test | public void
writeBytes(byte[] bytes, int len)
throws IOException
{
outputBytes(bytes, 0, len);
if(this.checksummode.enabled(ChecksumMode.DAP)) {
this.checksum.update(bytes, 0, len);
if(DUMPCSUM) {
System.err.print("SSS ");
for(int i = 0; i < len; i++) {
System.err.printf("%02x", bytes[i]);
}
System.err.println();
}
}
} | java | {
"resource": ""
} |
q174366 | SerialWriter.outputBytes | test | public void
outputBytes(byte[] bytes, int start, int count)
throws IOException
{
if(DUMPDATA) {
System.err.printf("output %d/%d:", start, count);
for(int i = 0; i < count; i++) {
System.err.printf(" %02x", bytes[i]);
}
System.err.println("");
System.err.flush();
}
output.write(bytes, start, count);
} | java | {
"resource": ""
} |
q174367 | SimpleGeomController.finishInit | test | void finishInit() {
// some widgets from the GridUI
np = ui.panz;
vertPanel = ui.vertPanel;
dataValueLabel = ui.dataValueLabel;
posLabel = ui.positionLabel;
// get last saved Projection
project = (ProjectionImpl) store.getBean(LastProjectionName, null);
if (project != null)
setProjection( project);
// get last saved MapArea
ProjectionRect ma = (ProjectionRect) store.getBean(LastMapAreaName, null);
if (ma != null)
np.setMapArea( ma);
makeEventManagement();
// last thing
/* get last dataset filename and reopen it
String filename = (String) store.get(LastDatasetName);
if (filename != null)
setDataset(filename); */
} | java | {
"resource": ""
} |
q174368 | CalendarDateRange.of | test | static public CalendarDateRange of(DateRange dr) {
if (dr == null) return null;
return CalendarDateRange.of( dr.getStart().getDate(), dr.getEnd().getDate());
} | java | {
"resource": ""
} |
q174369 | Grib2Gds.factory | test | public static Grib2Gds factory(int template, byte[] data) {
Grib2Gds result;
switch (template) {
case 0:
result = new LatLon(data);
break;
case 1:
result = new RotatedLatLon(data);
break;
case 10:
result = new Mercator(data);
break;
case 20:
result = new PolarStereographic(data);
break;
case 30:
result = new LambertConformal(data, 30);
break;
case 31:
result = new AlbersEqualArea(data);
break;
case 40:
result = new GaussLatLon(data);
break;
case 50: // Spherical Harmonic Coefficients BOGUS
result = new GdsSpherical(data, template);
break;
case 90:
result = new SpaceViewPerspective(data);
break;
// LOOK NCEP specific
case 204:
result = new CurvilinearOrthogonal(data);
break;
case 32769:
result = new RotatedLatLon32769(data);
break;
default:
throw new UnsupportedOperationException("Unsupported GDS type = " + template);
}
result.finish(); // stuff that cant be done in the constructor
return result;
} | java | {
"resource": ""
} |
q174370 | Dap2Parse.ddsparse | test | public int
ddsparse(String text, DDS dds) throws ParseException
{
return dapparse(text, dds, null, null);
} | java | {
"resource": ""
} |
q174371 | Dap2Parse.dasparse | test | public int
dasparse(String text, DAS das)
throws ParseException
{
return dapparse(text, null, das, null);
} | java | {
"resource": ""
} |
q174372 | McIDASGridReader.swapGridHeader | test | private void swapGridHeader(int[] gh) {
McIDASUtil.flip(gh, 0, 5);
McIDASUtil.flip(gh, 7, 7);
McIDASUtil.flip(gh, 9, 10);
McIDASUtil.flip(gh, 12, 14);
McIDASUtil.flip(gh, 32, 51);
} | java | {
"resource": ""
} |
q174373 | McIDASGridReader.readGrid | test | public float[] readGrid(McIDASGridRecord gr) throws IOException {
float[] data;
//try {
int te = (gr.getOffsetToHeader() + 64) * 4;
int rows = gr.getRows();
int cols = gr.getColumns();
rf.seek(te);
float scale = (float) gr.getParamScale();
data = new float[rows * cols];
rf.order(needToSwap ? RandomAccessFile.LITTLE_ENDIAN : RandomAccessFile.BIG_ENDIAN);
// int n = 0;
// store such that 0,0 is in lower left corner...
for (int nc = 0; nc < cols; nc++) {
for (int nr = 0; nr < rows; nr++) {
int temp = rf.readInt(); // check for missing value
data[(rows - nr - 1) * cols + nc] = (temp
== McIDASUtil.MCMISSING)
? Float.NaN
: ((float) temp) / scale;
}
}
rf.order(RandomAccessFile.BIG_ENDIAN);
//} catch (Exception esc) {
// System.out.println(esc);
//}
return data;
} | java | {
"resource": ""
} |
q174374 | McIDASGridReader.main | test | public static void main(String[] args) throws IOException {
String file = "GRID2001";
if (args.length > 0) {
file = args[0];
}
McIDASGridReader mg = new McIDASGridReader(file);
GridIndex gridIndex = mg.getGridIndex();
List grids = gridIndex.getGridRecords();
System.out.println("found " + grids.size() + " grids");
int num = Math.min(grids.size(), 10);
for (int i = 0; i < num; i++) {
System.out.println(grids.get(i));
}
} | java | {
"resource": ""
} |
q174375 | WFSGetCapabilitiesWriter.writeAConstraint | test | private void writeAConstraint(String name, boolean isImplemented) {
String defValue;
if(isImplemented) defValue = "TRUE"; else defValue = "FALSE";
fileOutput += "<ows:Constraint name=\"" + name + "\"> "
+ "<ows:NoValues/> "
+ "<ows:DefaultValue>" + defValue +"</ows:DefaultValue> "
+ "</ows:Constraint>";
} | java | {
"resource": ""
} |
q174376 | WFSGetCapabilitiesWriter.writeHeadersAndSS | test | private void writeHeadersAndSS() {
fileOutput += "<wfs:WFS_Capabilities xsi:schemaLocation="
+ WFSXMLHelper.encQuotes("http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd ")
+ " xmlns:xsi=" + WFSXMLHelper.encQuotes("http://www.w3.org/2001/XMLSchema-instance")
+ " xmlns:xlink=" + WFSXMLHelper.encQuotes("http://www.w3.org/1999/xlink")
+ " xmlns:gml=" + WFSXMLHelper.encQuotes("http://opengis.net/gml")
+ " xmlns:fes=" + WFSXMLHelper.encQuotes("http://www.opengis.net/fes/2.0")
+ " xmlns:ogc=" + WFSXMLHelper.encQuotes("http://www.opengis.net/ogc")
+ " xmlns:ows=" + WFSXMLHelper.encQuotes("http://www.opengis.net/ows/1.1\" xmlns:wfs=\"http://opengis.net/wfs/2.0")
+ " xmlns=" + WFSXMLHelper.encQuotes("http://www.opengis.net/wfs/2.0")
+ " version=\"2.0.0\">";
writeServiceInfo();
} | java | {
"resource": ""
} |
q174377 | WFSGetCapabilitiesWriter.writeOperations | test | public void writeOperations() {
fileOutput += "<ows:OperationsMetadata> ";
for(WFSRequestType rt : operationList) {
writeAOperation(rt);
}
// Write parameters
fileOutput += "<ows:Parameter name=\"AcceptVersions\"> "
+ "<ows:AllowedValues> "
+ "<ows:Value>2.0.0</ows:Value>"
+ "</ows:AllowedValues>"
+ "</ows:Parameter>";
fileOutput += "<ows:Parameter name=\"AcceptFormats\">"
+ "<ows:AllowedValues> "
+ "<ows:Value>text/xml</ows:Value>"
+ "</ows:AllowedValues>"
+ "</ows:Parameter>";
fileOutput += "<ows:Parameter name=\"Sections\"> "
+ "<ows:AllowedValues> "
+ "<ows:Value>ServiceIdentification</ows:Value> "
+ "<ows:Value>ServiceProvider</ows:Value> "
+ "<ows:Value>OperationsMetadata</ows:Value> "
+ "<ows:Value>FeatureTypeList</ows:Value> "
+ "</ows:AllowedValues>"
+ "</ows:Parameter>";
fileOutput += "<ows:Parameter name=\"version\"> "
+ "<ows:AllowedValues> "
+ "<ows:Value>2.0.0</ows:Value>"
+ "</ows:AllowedValues>"
+ "</ows:Parameter>";
// Write constraints
writeAConstraint("ImplementsBasicWFS", true);
writeAConstraint("ImplementsTransactionalWFS", false);
writeAConstraint("ImplementsLockingWFS", false);
writeAConstraint("KVPEncoding", false);
writeAConstraint("XMLEncoding", true);
writeAConstraint("SOAPEncoding", false);
writeAConstraint("ImplementsInheritance", false);
writeAConstraint("ImplementsRemoteResolve", false);
writeAConstraint("ImplementsResultPaging", false);
writeAConstraint("ImplementsStandardJoins", false);
writeAConstraint("ImplementsSpatialJoins", false);
writeAConstraint("ImplementsTemporalJoins", false);
writeAConstraint("ImplementsFeatureVersioning", false);
writeAConstraint("ManageStoredQueries", false);
writeAConstraint("PagingIsTransactionSafe", false);
writeAConstraint("QueryExpressions", false);
fileOutput += "</ows:OperationsMetadata>";
} | java | {
"resource": ""
} |
q174378 | LogReader.readAll | test | public void readAll(File dir, FileFilter ff, Closure closure, LogFilter logf, Stats stat) throws IOException {
File[] files = dir.listFiles();
if (files == null) {
System.out.printf("Dir has no files= %s%n", dir);
return;
}
List<File> list = Arrays.asList(files);
Collections.sort(list);
for (File f : list) {
if ((ff != null) && !ff.accept(f)) continue;
if (f.isDirectory())
readAll(f, ff, closure, logf, stat);
else
scanLogFile(f, closure, logf, stat);
}
} | java | {
"resource": ""
} |
q174379 | LogReader.scanLogFile | test | public void scanLogFile(File file, Closure closure, LogFilter logf, Stats stat) throws IOException {
try (InputStream ios = new FileInputStream(file)) {
System.out.printf("-----Reading %s %n", file.getPath());
BufferedReader dataIS = new BufferedReader(new InputStreamReader(ios,
CDM.utf8Charset), 40 * 1000);
int total = 0;
int count = 0;
while ((maxLines < 0) || (count < maxLines)) {
Log log = parser.nextLog(dataIS);
if (log == null) break;
total++;
if ((logf != null) && !logf.pass(log)) continue;
closure.process(log);
count++;
}
if (stat != null) {
stat.total += total;
stat.passed += count;
}
System.out.printf("----- %s total requests=%d passed=%d %n", file.getPath(), total, count);
}
} | java | {
"resource": ""
} |
q174380 | GempakGridReader.getGridPackingType | test | public int getGridPackingType(int gridNumber) throws IOException {
// See DM_RDTR
int irow = 1; // Always 1 for grids
if ((gridNumber < 1) || (gridNumber > dmLabel.kcol)) {
logWarning("bad grid number " + gridNumber);
return -9;
}
int iprt = getPartNumber("GRID");
if (iprt == 0) {
logWarning("couldn't find part: GRID");
return -10;
}
// gotta subtract 1 because parts are 1 but List is 0 based
DMPart part = parts.get(iprt - 1);
// check for valid data type
if (part.ktyprt != MDGRID) {
logWarning("Not a valid type: "
+ GempakUtil.getDataType(part.ktyprt));
return -21;
}
int ilenhd = part.klnhdr;
int ipoint = dmLabel.kpdata
+ (irow - 1) * dmLabel.kcol * dmLabel.kprt
+ (gridNumber - 1) * dmLabel.kprt + (iprt - 1);
// From DM_RPKG
int istart = DM_RINT(ipoint);
if (istart == 0) {
return -15;
}
int length = DM_RINT(istart);
int isword = istart + 1;
if (length <= ilenhd) {
logWarning("length (" + length + ") is less than header length ("
+ ilenhd + ")");
return -15;
} else if (Math.abs(length) > 10000000) {
logWarning("length is huge: " + length);
return -34;
}
int[] header = new int[ilenhd];
DM_RINT(isword, header);
// int nword = length - ilenhd;
isword += ilenhd;
// read the data packing type
return DM_RINT(isword);
} | java | {
"resource": ""
} |
q174381 | GempakGridReader.findGrid | test | public GempakGridRecord findGrid(String parm) {
List<GridRecord> gridList = gridIndex.getGridRecords();
if (gridList == null) {
return null;
}
for (GridRecord grid : gridList) {
GempakGridRecord gh = (GempakGridRecord) grid;
if (gh.param.trim().equals(parm)) {
return gh;
}
}
return null;
} | java | {
"resource": ""
} |
q174382 | GempakGridReader.DM_RPKG | test | public float[] DM_RPKG(int isword, int nword, int decimalScale)
throws IOException {
// from DM_RPKG
// read the data packing type
float[] data;
int ipktyp = DM_RINT(isword);
int iiword = isword + 1;
int lendat = nword - 1;
if (ipktyp == MDGNON) { // no packing
data = new float[lendat];
DM_RFLT(iiword, data);
return data;
}
int iiw;
int irw;
if (ipktyp == MDGDIF) {
iiw = 4;
irw = 3;
} else if (ipktyp == MDGRB2) {
iiw = 4;
irw = 1;
} else {
iiw = 3;
irw = 2;
}
int[] iarray = new int[iiw];
float[] rarray = new float[irw];
DM_RINT(iiword, iarray);
iiword = iiword + iiw;
lendat = lendat - iiw;
DM_RFLT(iiword, rarray);
iiword = iiword + irw;
lendat = lendat - irw;
if (ipktyp == MDGRB2) {
data = unpackGrib2Data(iiword, lendat, iarray, rarray);
return data;
}
int nbits = iarray[0];
int misflg = iarray[1];
boolean miss = misflg != 0;
int kxky = iarray[2];
// int mword = kxky;
int kx = 0;
if (iiw == 4) {
kx = iarray[3];
}
float ref = rarray[0];
float scale = rarray[1];
float difmin = 0;
if (irw == 3) {
difmin = rarray[2];
}
data = unpackData(iiword, lendat, ipktyp, kxky, nbits, ref, scale,
miss, difmin, kx, decimalScale);
return data;
} | java | {
"resource": ""
} |
q174383 | GempakGridReader.unpackData | test | private synchronized float[] unpackData(int iiword, int nword,
int ipktyp, int kxky, int nbits,
float ref, float scale,
boolean miss, float difmin,
int kx, int decimalScale)
throws IOException {
if (ipktyp == MDGGRB) {
if (!useDP) {
return unpackGrib1Data(iiword, nword, kxky, nbits, ref,
scale, miss, decimalScale);
} else {
if (nword * 32 < kxky * nbits) { // to account for badly written files
nword++;
}
int[] ksgrid = new int[nword];
DM_RINT(iiword, ksgrid);
return DP_UGRB(ksgrid, kxky, nbits, ref, scale, miss,
decimalScale);
}
} else if (ipktyp == MDGNMC) {
return null;
} else if (ipktyp == MDGDIF) {
return null;
}
return null;
} | java | {
"resource": ""
} |
q174384 | GempakGridReader.DP_UGRB | test | private synchronized float[] DP_UGRB(int[] idata, int kxky, int nbits,
float qmin, float scale,
boolean misflg, int decimalScale)
throws IOException {
float scaleFactor = (decimalScale == 0)
? 1.f
: (float) Math.pow(10.0, -decimalScale);
//
//Check for valid input.
//
float[] grid = new float[kxky];
if ((nbits <= 1) || (nbits > 31)) {
return grid;
}
if (scale == 0.) {
return grid;
}
//
//Compute missing data value.
//
int imax = (int) (Math.pow(2, nbits) - 1);
//
//Retrieve data points from buffer.
//
int iword = 0;
int ibit = 1; // 1 based bit position
for (int i = 0; i < kxky; i++) {
//
// Get the integer from the buffer.
//
int jshft = nbits + ibit - 33;
int idat = 0;
idat = (jshft < 0)
? idata[iword] >>> Math.abs(jshft)
: idata[iword] << jshft;
idat = idat & imax;
//
// Check to see if packed integer overflows into next word. LOOK fishy bit operations
//
if (jshft > 0) {
jshft -= 32;
int idat2 = 0;
idat2 = idata[iword + 1] >>> Math.abs(jshft);
idat = idat | idat2;
}
//
// Compute value of word.
//
if ((idat == imax) && misflg) {
grid[i] = RMISSD;
} else {
grid[i] = (qmin + idat * scale) * scaleFactor;
}
//
// Set location for next word.
//
ibit += nbits;
if (ibit > 32) {
ibit -= 32;
iword++;
}
/*
if (i < 25) {
System.out.println("grid["+i+"]: " + grid[i]);
}
*/
}
return grid;
} | java | {
"resource": ""
} |
q174385 | GempakGridReader.unpackGrib1Data | test | private float[] unpackGrib1Data(int iiword, int nword, int kxky,
int nbits, float ref, float scale,
boolean miss, int decimalScale)
throws IOException {
//System.out.println("decimal scale = " + decimalScale);
float[] values = new float[kxky];
bitPos = 0;
bitBuf = 0;
next = 0;
ch1 = 0;
ch2 = 0;
ch3 = 0;
ch4 = 0;
rf.seek(getOffset(iiword));
int idat;
// save a pow call if we can
float scaleFactor = (decimalScale == 0)
? 1.f
: (float) Math.pow(10.0, -decimalScale);
//float scaleFactor = (float) Math.pow(10.0, -decimalScale);
for (int i = 0; i < values.length; i++) {
idat = bits2UInt(nbits);
if (miss && (idat == IMISSD)) {
values[i] = IMISSD;
} else {
values[i] = (ref + scale * idat) * scaleFactor;
}
/*
if (i < 25) {
System.out.println("values[" + i + "] = " + values[i]);
}
*/
}
return values;
} | java | {
"resource": ""
} |
q174386 | GempakGridReader.unpackGrib2Data | test | private float[] unpackGrib2Data(int iiword, int lendat, int[] iarray, float[] rarray) throws IOException {
long start = getOffset(iiword);
rf.seek(start);
Grib2Record gr = makeGribRecord(rf, start);
float[] data = gr.readData(rf);
if (((iarray[3] >> 6) & 1) == 0) { // -y scanning - flip
data = gb2_ornt(iarray[1], iarray[2], iarray[3], data);
}
return data;
} | java | {
"resource": ""
} |
q174387 | GempakGridReader.printGrids | test | public void printGrids() {
List<GridRecord> gridList = gridIndex.getGridRecords();
if (gridList == null)
return;
System.out.println(" NUM TIME1 TIME2 LEVL1 LEVL2 VCORD PARM");
for (GridRecord aGridList : gridList) {
System.out.println(aGridList);
}
} | java | {
"resource": ""
} |
q174388 | GempakGridReader.getNextByte | test | private void getNextByte() throws IOException {
if (!needToSwap) {
// Get the next byte from the RandomAccessFile
bitBuf = rf.read();
} else {
if (next == 3) {
bitBuf = ch3;
} else if (next == 2) {
bitBuf = ch2;
} else if (next == 1) {
bitBuf = ch1;
} else {
ch1 = rf.read();
ch2 = rf.read();
ch3 = rf.read();
ch4 = rf.read();
bitBuf = ch4;
next = 4;
}
next--;
}
} | java | {
"resource": ""
} |
q174389 | CalendarDate.of | test | public static CalendarDate of(Calendar cal, int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute) {
Chronology base = Calendar.getChronology(cal);
/* if (base == null)
base = ISOChronology.getInstanceUTC(); // already in UTC
else
base = ZonedChronology.getInstance( base, DateTimeZone.UTC); // otherwise wrap it to be in UTC */
DateTime dt = new DateTime(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, base);
if (!Calendar.isDefaultChronology(cal)) dt = dt.withChronology(Calendar.getChronology(cal));
dt = dt.withZone(DateTimeZone.UTC);
return new CalendarDate(cal, dt);
} | java | {
"resource": ""
} |
q174390 | CalendarDate.of | test | public static CalendarDate of(java.util.Date date) {
DateTime dt = new DateTime(date, DateTimeZone.UTC) ;
return new CalendarDate(null, dt);
} | java | {
"resource": ""
} |
q174391 | CalendarDate.of | test | public static CalendarDate of(long msecs) {
// Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z using ISOChronology in the specified time zone.
DateTime dt = new DateTime(msecs, DateTimeZone.UTC) ;
return new CalendarDate(null, dt);
} | java | {
"resource": ""
} |
q174392 | CalendarDate.of | test | public static CalendarDate of(Calendar cal, long msecs) {
Chronology base = Calendar.getChronology(cal);
DateTime dt = new DateTime(msecs, base) ;
return new CalendarDate(cal, dt);
} | java | {
"resource": ""
} |
q174393 | CalendarDate.parseUdunits | test | public static CalendarDate parseUdunits(String calendarName, String udunits) {
int pos = udunits.indexOf(' ');
if (pos < 0) return null;
String valString = udunits.substring(0, pos).trim();
String unitString = udunits.substring(pos+1).trim();
CalendarDateUnit cdu = CalendarDateUnit.of(calendarName, unitString);
double val = Double.parseDouble(valString);
return cdu.makeCalendarDate(val);
} | java | {
"resource": ""
} |
q174394 | CalendarDate.getDifference | test | public long getDifference(CalendarDate o, CalendarPeriod.Field fld) {
switch (fld) {
case Millisec:
return getDifferenceInMsecs(o);
case Second:
return (long) (getDifferenceInMsecs(o) / MILLISECS_IN_SECOND);
case Minute:
return (long) (getDifferenceInMsecs(o) / MILLISECS_IN_MINUTE);
case Hour:
return (long) (getDifferenceInMsecs(o) / MILLISECS_IN_HOUR);
case Day:
return (long) (getDifferenceInMsecs(o) / MILLISECS_IN_DAY);
case Month:
int tmonth = getFieldValue(CalendarPeriod.Field.Month);
int omonth = o.getFieldValue(CalendarPeriod.Field.Month);
int years = (int) this.getDifference(o, CalendarPeriod.Field.Year);
return tmonth-omonth + 12 * years;
case Year:
int tyear = getFieldValue(CalendarPeriod.Field.Year);
int oyear = o.getFieldValue(CalendarPeriod.Field.Year);
return tyear - oyear;
}
return dateTime.getMillis() - o.dateTime.getMillis();
} | java | {
"resource": ""
} |
q174395 | DataToCDM.createAtomicVar | test | protected CDMArrayAtomic
createAtomicVar(DataCursor data)
throws DapException
{
CDMArrayAtomic array = new CDMArrayAtomic(data);
return array;
} | java | {
"resource": ""
} |
q174396 | DownloadController.setup | test | public void setup(HttpServletRequest req, HttpServletResponse resp)
throws SendError
{
this.req = req;
this.res = resp;
if(!once)
doonce(req);
// Parse any query parameters
try {
this.params = new DownloadParameters(req);
} catch (IOException ioe) {
throw new SendError(res.SC_BAD_REQUEST, ioe);
}
} | java | {
"resource": ""
} |
q174397 | DownloadController.escapeString | test | static protected String escapeString(String s)
{
StringBuilder buf = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
int c = s.charAt(i);
switch (c) {
case '"':
buf.append("\\\"");
break;
case '\\':
buf.append("\\\\");
break;
case '\n':
buf.append('\n');
break;
case '\r':
buf.append('\r');
break;
case '\t':
buf.append('\r');
break;
case '\f':
buf.append('\f');
break;
default:
if(c < ' ')
buf.append(String.format("\\x%02x", (c & 0xff)));
else
buf.append((char) c);
break;
}
}
return buf.toString();
} | java | {
"resource": ""
} |
q174398 | CDMUtil.createSlices | test | static public List<Slice>
createSlices(List<Range> rangelist)
throws dap4.core.util.DapException
{
List<Slice> slices = new ArrayList<Slice>(rangelist.size());
for(int i = 0; i < rangelist.size(); i++) {
Range r = rangelist.get(i);
// r does not store last
int stride = r.stride();
int first = r.first();
int n = r.length();
int stop = first + (n * stride);
Slice cer = new Slice(first, stop - 1, stride);
slices.add(cer);
}
return slices;
} | java | {
"resource": ""
} |
q174399 | CDMUtil.unwrapfile | test | static public NetcdfFile unwrapfile(NetcdfFile file)
{
for(; ; ) {
if(file instanceof NetcdfDataset) {
NetcdfDataset ds = (NetcdfDataset) file;
file = ds.getReferencedFile();
if(file == null) break;
} else break;
}
return file;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.