_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q174800 | D4Cursor.readAs | test | protected Object
readAs(DapVariable atomvar, DapType basetype, List<Slice> slices)
throws DapException
{
if(basetype.getTypeSort() == TypeSort.Enum) {// short circuit this case
basetype = ((DapEnumeration) basetype).getBaseType();
return readAs(atomvar, basetype, slices);
}
long count = DapUtil.sliceProduct(slices);
Object result = LibTypeFcns.newVector(basetype, count);
Odometer odom = Odometer.factory(slices);
if(DapUtil.isContiguous(slices) && basetype.isFixedSize())
readContig(slices, basetype, count, odom, result);
else
readOdom(slices, basetype, odom, result);
return result;
} | java | {
"resource": ""
} |
q174801 | GempakLookup.isPositiveUp | test | public final boolean isPositiveUp(GridRecord gr) {
int type = gr.getLevelType1();
if ((type == 1) || (type == 5)) {
return false;
}
return true;
} | java | {
"resource": ""
} |
q174802 | UnitImpl.isCompatible | test | public boolean isCompatible(final Unit that) {
// jeffm: for some reason just calling getDerivedUnit().equals(...)
// with jikes 1.1.7 as the compiler causes the jvm to crash.
// The Unit u1=... does not crash.
final Unit u1 = getDerivedUnit();
return u1.equals(that.getDerivedUnit());
// return getDerivedUnit().equals(that.getDerivedUnit());
} | java | {
"resource": ""
} |
q174803 | UnitImpl.makeLabel | test | public String makeLabel(final String quantityID) {
final StringBuilder buf = new StringBuilder(quantityID);
if (quantityID.contains(" ")) {
buf.insert(0, '(').append(')');
}
buf.append('/');
final int start = buf.length();
buf.append(toString());
if (buf.substring(start).indexOf(' ') != -1) {
buf.insert(start, '(').append(')');
}
return buf.toString();
} | java | {
"resource": ""
} |
q174804 | BitReader.setBitOffset | test | public void setBitOffset(int bitOffset) throws IOException {
if (bitOffset % 8 == 0) {
raf.seek(startPos + bitOffset / 8);
bitPos = 0;
bitBuf = 0;
} else {
raf.seek(startPos + bitOffset / 8);
bitPos = 8 - (bitOffset % 8);
bitBuf = (byte) raf.read();
bitBuf &= 0xff >> (8 - bitPos); // mask off consumed bits
}
} | java | {
"resource": ""
} |
q174805 | BitReader.bits2UInt | test | public long bits2UInt(int nb) throws IOException {
assert nb <= 64;
assert nb >= 0;
long result = 0;
int bitsLeft = nb;
while (bitsLeft > 0) {
// we ran out of bits - fetch the next byte...
if (bitPos == 0) {
bitBuf = nextByte();
bitPos = BIT_LENGTH;
}
// -- retrieve bit from current byte ----------
// how many bits to read from the current byte
int size = Math.min(bitsLeft, bitPos);
// move my part to start
int myBits = bitBuf >> (bitPos - size);
// mask-off sign-extending
myBits &= BYTE_BITMASK;
// mask-off bits of next value
myBits &= ~(BYTE_BITMASK << size);
// -- put bit to result ----------------------
// where to place myBits inside of result
int shift = bitsLeft - size;
assert shift >= 0;
// put it there
result |= myBits << shift;
// -- put bit to result ----------------------
// update information on what we consumed
bitsLeft -= size;
bitPos -= size;
}
return result;
} | java | {
"resource": ""
} |
q174806 | BitReader.bits2SInt | test | public long bits2SInt(int nb) throws IOException {
long result = bits2UInt(nb);
// check if we're negative
if (getBit(result, nb)) {
// it's negative! reset leading bit
result = setBit(result, nb, false);
// build 2's-complement
result = ~result & LONG_BITMASK;
result = result + 1;
}
return result;
} | java | {
"resource": ""
} |
q174807 | DConnect2.openConnection | test | private void openConnection(String urlString, Command command) throws IOException, DAP2Exception
{
InputStream is = null;
try {
try (HTTPMethod method = HTTPFactory.Get(_session, urlString)) {
if(acceptCompress)
method.setCompression("deflate,gzip");
// enable sessions
if(allowSessions)
method.setUseSessions(true);
int statusCode;
for(; ; ) {
statusCode = method.execute();
if(statusCode != HttpStatus.SC_SERVICE_UNAVAILABLE)
break;
Thread.sleep(5000);
System.err.println("Service Unavailable");
}
// debug
// if (debugHeaders) ucar.httpservices.HttpClientManager.showHttpRequestInfo(f, method);
if(statusCode == HttpStatus.SC_NOT_FOUND) {
throw new DAP2Exception(DAP2Exception.NO_SUCH_FILE, method.getStatusText() + ": " + urlString);
}
if(statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
throw new InvalidCredentialsException(method.getStatusText());
}
if(statusCode != HttpStatus.SC_OK) {
throw new DAP2Exception("Method failed:" + method.getStatusText() + " on URL= " + urlString);
}
// Get the response body.
is = method.getResponseAsStream();
// check if its an error
Header header = method.getResponseHeader("Content-Description");
if(header != null && (header.getValue().equals("dods-error")
|| header.getValue().equals("dods_error"))) {
// create server exception object
DAP2Exception ds = new DAP2Exception();
// parse the Error object from stream and throw it
ds.parse(is);
throw ds;
}
ver = new ServerVersion(method);
checkHeaders(method);
// check for deflator
Header h = method.getResponseHeader("content-encoding");
String encoding = (h == null) ? null : h.getValue();
//if (encoding != null) LogStream.out.println("encoding= " + encoding);
if(encoding != null && encoding.equals("deflate")) {
is = new BufferedInputStream(new InflaterInputStream(is), 1000);
if(showCompress) System.out.printf("deflate %s%n", urlString);
} else if(encoding != null && encoding.equals("gzip")) {
is = new BufferedInputStream(new GZIPInputStream(is), 1000);
if(showCompress) System.out.printf("gzip %s%n", urlString);
} else {
if(showCompress) System.out.printf("none %s%n", urlString);
}
command.process(is);
}
} catch (IOException | DAP2Exception e) {
throw e;
} catch (Exception e) {
Util.check(e);
//e.printStackTrace();
throw new DAP2Exception(e);
}
} | java | {
"resource": ""
} |
q174808 | DConnect2.getDAS | test | public DAS getDAS() throws IOException, DAP2Exception
{
DASCommand command = new DASCommand();
if(filePath != null) { // url was file:
File daspath = new File(filePath + ".das");
// See if the das file exists
if(daspath.canRead()) {
try (FileInputStream is = new FileInputStream(daspath)) {
command.process(is);
}
}
} else if(stream != null) {
command.process(stream);
} else { // assume url is remote
try {
openConnection(urlString + ".das" + getCompleteCE(projString,selString), command);
} catch (DAP2Exception de) {
//if(de.getErrorCode() != DAP2Exception.NO_SUCH_FILE)
//throw de; // rethrow
}
}
return command.das;
} | java | {
"resource": ""
} |
q174809 | DConnect2.getDDS | test | public DDS getDDS(String CE) throws IOException, ParseException, DAP2Exception
{
DDSCommand command = new DDSCommand();
command.setURL(CE == null || CE.length() == 0 ? urlString : urlString + "?" + CE);
if(filePath != null) {
try (FileInputStream is = new FileInputStream(filePath + ".dds")) {
command.process(is);
}
} else if(stream != null) {
command.process(stream);
} else { // must be a remote url
openConnection(urlString + ".dds" + (getCompleteCE(CE)), command);
}
return command.dds;
} | java | {
"resource": ""
} |
q174810 | DConnect2.getCompleteCE | test | private String getCompleteCE(String CE)
{
String localProjString = null;
String localSelString = null;
if(CE == null)
return "";
//remove any leading '?'
if(CE.startsWith("?")) CE = CE.substring(1);
int selIndex = CE.indexOf('&');
if(selIndex == 0) {
localProjString = "";
localSelString = CE;
} else if(selIndex > 0) {
localSelString = CE.substring(selIndex);
localProjString = CE.substring(0, selIndex);
} else {// selIndex < 0
localProjString = CE;
localSelString = "";
}
String ce = projString;
if(!localProjString.equals("")) {
if(!ce.equals("") && localProjString.indexOf(',') != 0)
ce += ",";
ce += localProjString;
}
if(!selString.equals("")) {
if(selString.indexOf('&') != 0)
ce += "&";
ce += selString;
}
if(!localSelString.equals("")) {
if(localSelString.indexOf('&') != 0)
ce += "&";
ce += localSelString;
}
if(ce.length() > 0) ce = "?" + ce;
if(false) {
DAPNode.log.debug("projString: '" + projString + "'");
DAPNode.log.debug("localProjString: '" + localProjString + "'");
DAPNode.log.debug("selString: '" + selString + "'");
DAPNode.log.debug("localSelString: '" + localSelString + "'");
DAPNode.log.debug("Complete CE: " + ce);
}
return ce; // escaping will happen elsewhere
} | java | {
"resource": ""
} |
q174811 | Sinusoidal.projToLatLon | test | @Override
public LatLonPoint projToLatLon(ProjectionPoint world, LatLonPointImpl result) {
double fromX = world.getX() - falseEasting;
double fromY = world.getY() - falseNorthing;
double toLat_r = fromY / earthRadius;
double toLon_r;
if (Misc.nearlyEquals(Math.abs(toLat_r), PI_OVER_2, 1e-10)) {
toLat_r = toLat_r < 0 ? -PI_OVER_2 : +PI_OVER_2;
toLon_r = Math.toRadians(centMeridian); // if lat == +- pi/2, set lon = centMeridian (Snyder 248)
} else if (Math.abs(toLat_r) < PI_OVER_2) {
toLon_r = Math.toRadians(centMeridian) + fromX / (earthRadius * Math.cos(toLat_r));
} else {
return INVALID; // Projection point is off the map.
}
if (Misc.nearlyEquals(Math.abs(toLon_r), PI, 1e-10)) {
toLon_r = toLon_r < 0 ? -PI : +PI;
} else if (Math.abs(toLon_r) > PI) {
return INVALID; // Projection point is off the map.
}
result.setLatitude(Math.toDegrees(toLat_r));
result.setLongitude(Math.toDegrees(toLon_r));
return result;
} | java | {
"resource": ""
} |
q174812 | RadarServerController.idvDatasetCatalog | test | private String idvDatasetCatalog(String xml)
{
String ret = xml.replace("variables", "Variables");
ret = ret.replace("timeCoverage", "TimeSpan");
StringBuilder sub = new StringBuilder(ret.substring(0,
ret.indexOf("<geospatialCoverage>")));
sub.append("<LatLonBox>\n\t<north>90.0</north>\n\t<south>-90.0</south>");
sub.append("\n\t<east>180.0</east>\n\t<west>-180.0</west></LatLonBox>");
String endCoverage = "</geospatialCoverage>";
sub.append(ret.substring(ret.indexOf(endCoverage) + endCoverage.length()));
return sub.toString();
} | java | {
"resource": ""
} |
q174813 | RadarServerController.idvCompatibleRange | test | private DateRange idvCompatibleRange(DateRange range)
{
CalendarDate start = range.getStart().getCalendarDate();
CalendarDate end = range.getEnd().getCalendarDate();
return new DateRange(start.toDate(), end.toDate());
} | java | {
"resource": ""
} |
q174814 | DMSPHeader.isValidFile | test | boolean isValidFile( ucar.unidata.io.RandomAccessFile raFile )
{
// @todo This method should not be called if read() has or will be called on this instance.
this.raFile = raFile;
try
{
this.actualSize = raFile.length();
}
catch ( IOException e )
{
return( false );
}
try
{
this.readHeaderFromFile( raFile );
this.handleFileInformation();
this.handleProcessingInformation();
this.handleSatelliteInformation();
this.handleSensorInformation();
}
catch ( IOException e )
{
return( false );
}
return( true );
} | java | {
"resource": ""
} |
q174815 | DMSPHeader.handleSatelliteInformation | test | private void handleSatelliteInformation()
{
spacecraftIdAtt = new Attribute(
this.spacecraftIdAttName,
headerInfo.get(HeaderInfoTitle.SPACECRAFT_ID.toString()));
noradIdAtt = new Attribute(
this.noradIdAttName,
headerInfo.get(HeaderInfoTitle.NORAD_ID.toString()));
} | java | {
"resource": ""
} |
q174816 | DMSPHeader.handleSensorInformation | test | private void handleSensorInformation()
{
numSamplesPerBand = Integer.parseInt( headerInfo.get( HeaderInfoTitle.SAMPLES_PER_BAND.toString()) );
numSamplesPerBandDim = new Dimension(
this.numSamplesPerBandDimName,
numSamplesPerBand);
// Read nominal resolution information
nominalResolutionAtt = new Attribute( nominalResolutionAttName, headerInfo.get(HeaderInfoTitle.NOMINAL_RESOLUTION.toString()));
// Read bands per scanlin information.
bandsPerScanlineAtt = new Attribute( bandsPerScanlineAttName, Integer.valueOf(headerInfo.get(HeaderInfoTitle.BANDS_PER_SCANLINE.toString())));
// Read bytes per smaple information
bytesPerSampleAtt = new Attribute( bytesPerSampleAttName, Integer.valueOf(headerInfo.get(HeaderInfoTitle.BYTES_PER_SAMPLE.toString())));
// Read byte offset for band 1 information.
byteOffsetBand1Att = new Attribute( byteOffsetBand1AttName, Integer.valueOf(headerInfo.get(HeaderInfoTitle.BYTE_OFFSET_BAND_1.toString())));
// Read byte offset for band 2 information.
byteOffsetBand2Att = new Attribute( byteOffsetBand2AttName, Integer.valueOf(headerInfo.get(HeaderInfoTitle.BYTE_OFFSET_BAND_2.toString())));
// Band 1 description
band1Att = new Attribute( band1AttName, headerInfo.get( HeaderInfoTitle.BAND_1.toString()));
// Band 2 description
band2Att = new Attribute( band2AttName, headerInfo.get( HeaderInfoTitle.BAND_2.toString()));
// Band organization
bandOrganizationAtt = new Attribute( bandOrganizationAttName, headerInfo.get(HeaderInfoTitle.ORGANIZATION.toString()));
// thermal offset
thermalOffsetAtt = new Attribute( thermalOffsetAttName, headerInfo.get(HeaderInfoTitle.THERMAL_OFFSET.toString()));
// thermal scale
thermalScaleAtt = new Attribute( thermalScaleAttName, headerInfo.get(HeaderInfoTitle.THERMAL_SCALE.toString()));
// percent daylight
percentDaylightAtt = new Attribute( percentDaylightAttName, Double.valueOf(headerInfo.get(HeaderInfoTitle.PERCENT_DAYLIGHT.toString())));
// percent full moon
percentFullMoonAtt = new Attribute( percentFullMoonAttName, Double.valueOf(headerInfo.get(HeaderInfoTitle.PERCENT_FULL_MOON.toString())));
// percent terminator evident
percentTerminatorEvidentAtt = new Attribute( percentTerminatorEvidentAttName, Double.valueOf(headerInfo.get(HeaderInfoTitle.PERCENT_TERMINATOR_EVIDENT.toString())));
} | java | {
"resource": ""
} |
q174817 | Parse.readRootElement | test | static public Element readRootElement(String location) throws IOException {
org.jdom2.Document doc;
try {
SAXBuilder builder = new SAXBuilder();
doc = builder.build(location);
} catch (JDOMException e) {
throw new IOException(e.getMessage());
}
return doc.getRootElement();
} | java | {
"resource": ""
} |
q174818 | Parse.cleanCharacterData | test | static public String cleanCharacterData(String text) {
if (text == null) return null;
boolean bad = false;
for (int i = 0, len = text.length(); i < len; i++) {
int ch = text.charAt(i);
if (!org.jdom2.Verifier.isXMLCharacter(ch)) {
bad = true;
break;
}
}
if (!bad) return text;
StringBuilder sbuff = new StringBuilder(text.length());
for (int i = 0, len = text.length(); i < len; i++) {
int ch = text.charAt(i);
if (org.jdom2.Verifier.isXMLCharacter(ch))
sbuff.append((char) ch);
}
return sbuff.toString();
} | java | {
"resource": ""
} |
q174819 | Escape.xunescapeString | test | private static String xunescapeString(String in, char escape, boolean spaceplus)
{
try {
if(in == null) return null;
byte[] utf8 = in.getBytes(utf8Charset);
byte escape8 = (byte) escape;
byte[] out = new byte[utf8.length]; // Should be max we need
int index8 = 0;
for(int i = 0; i < utf8.length; ) {
byte b = utf8[i++];
if(b == plus && spaceplus) {
out[index8++] = blank;
} else if(b == escape8) {
// check to see if there are enough characters left
if(i + 2 <= utf8.length) {
b = (byte) (fromHex(utf8[i]) << 4 | fromHex(utf8[i + 1]));
i += 2;
}
}
out[index8++] = b;
}
return new String(out, 0, index8, utf8Charset);
} catch (Exception e) {
return in;
}
} | java | {
"resource": ""
} |
q174820 | Escape.escapeURLQuery | test | public static String escapeURLQuery(String ce)
{
try {
ce = escapeString(ce, _allowableInUrlQuery);
} catch (Exception e) {
ce = null;
}
return ce;
} | java | {
"resource": ""
} |
q174821 | Escape.unescapeURLQuery | test | public static String unescapeURLQuery(String ce)
{
try {
ce = unescapeString(ce);
} catch (Exception e) {
ce = null;
}
return ce;
} | java | {
"resource": ""
} |
q174822 | Escape.backslashDecode | test | public static String backslashDecode(String s)
{
StringBuilder buf = new StringBuilder(s);
int i = 0;
while(i < buf.length()) {
if(buf.charAt(i) == '\\') {
buf.deleteCharAt(i);
}
i++;
}
return buf.toString();
} | java | {
"resource": ""
} |
q174823 | Escape.backslashEncode | test | public static String backslashEncode(String s)
{
StringBuilder buf = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
int c = buf.charAt(i);
if(_MustBackslashEscape.indexOf(c) >= 0)
buf.append(_BACKSLASHEscape);
buf.append((char) c);
}
return buf.toString();
} | java | {
"resource": ""
} |
q174824 | AbstractLightningIOSP.addLightningGlobalAttributes | test | protected void addLightningGlobalAttributes(NetcdfFile ncfile) {
ncfile.addAttribute(null, new Attribute(CF.FEATURE_TYPE, CF.FeatureType.point.toString()));
ncfile.addAttribute( null, new Attribute(CDM.HISTORY, "Read directly by Netcdf Java IOSP"));
} | java | {
"resource": ""
} |
q174825 | Swap.swapShort | test | static public short swapShort(byte[] b, int offset) {
// 2 bytes
int low = b[offset] & 0xff;
int high = b[offset + 1] & 0xff;
return (short) (high << 8 | low);
} | java | {
"resource": ""
} |
q174826 | Swap.swapInt | test | static public int swapInt(byte[] b, int offset) {
// 4 bytes
int accum = 0;
for (int shiftBy = 0, i = offset; shiftBy < 32; shiftBy += 8, i++) {
accum |= (b[i] & 0xff) << shiftBy;
}
return accum;
} | java | {
"resource": ""
} |
q174827 | Swap.swapDouble | test | static public double swapDouble(byte[] b, int offset) {
long accum = 0;
long shiftedval;
for (int shiftBy = 0, i = offset; shiftBy < 64; shiftBy += 8, i++) {
shiftedval = ((long) (b[i] & 0xff)) << shiftBy;
accum |= shiftedval;
}
return Double.longBitsToDouble(accum);
} | java | {
"resource": ""
} |
q174828 | Swap.swapFloat | test | static public float swapFloat(float v) {
int l = swapInt(Float.floatToIntBits(v));
return (Float.intBitsToFloat(l));
} | java | {
"resource": ""
} |
q174829 | Swap.swapDouble | test | static public double swapDouble(double v) {
long l = swapLong(Double.doubleToLongBits(v));
return (Double.longBitsToDouble(l));
} | java | {
"resource": ""
} |
q174830 | Swap.shortToBytes | test | static public byte[] shortToBytes(short v) {
byte[] b = new byte[2];
int allbits = 255;
for (int i = 0; i < 2; i++) {
b[1 - i] = (byte) ((v & (allbits << i * 8)) >> i * 8);
}
return b;
} | java | {
"resource": ""
} |
q174831 | Swap.intToBytes | test | static public byte[] intToBytes(int v) {
byte[] b = new byte[4];
int allbits = 255;
for (int i = 0; i < 4; i++) {
b[3 - i] = (byte) ((v & (allbits << i * 8)) >> i * 8);
}
return b;
} | java | {
"resource": ""
} |
q174832 | Swap.longToBytes | test | static public byte[] longToBytes(long v) {
byte[] b = new byte[8];
long allbits = 255;
for (int i = 0; i < 8; i++) {
b[7 - i] = (byte) ((v & (allbits << i * 8)) >> i * 8);
}
return b;
} | java | {
"resource": ""
} |
q174833 | VerticalTransformImpl.subset | test | public VerticalTransform subset(Range t_range, Range z_range,
Range y_range, Range x_range)
throws ucar.ma2.InvalidRangeException {
return new VerticalTransformSubset(this, t_range, z_range, y_range, x_range);
} | java | {
"resource": ""
} |
q174834 | GridDatasetInv.writeXML | test | public String writeXML(Date lastModified) {
XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
return fmt.outputString(writeDocument(lastModified));
} | java | {
"resource": ""
} |
q174835 | OceanS.makeC | test | private Array makeC(Array s, double a, double b) {
int nz = (int) s.getSize();
Index sIndex = s.getIndex();
if (a == 0) return s; // per R. Signell, USGS
ArrayDouble.D1 c = new ArrayDouble.D1(nz);
double fac1 = 1.0 - b;
double denom1 = 1.0 / Math.sinh(a);
double denom2 = 1.0 / (2.0 * Math.tanh(0.5 * a));
for (int i = 0; i < nz; i++) {
double sz = s.getDouble(sIndex.set(i));
double term1 = fac1 * Math.sinh(a * sz) * denom1;
double term2 = b * (Math.tanh(a * (sz + 0.5))
* denom2 - 0.5);
c.set(i, term1 + term2);
}
return c;
} | java | {
"resource": ""
} |
q174836 | WFSDescribeFeatureTypeWriter.startXML | test | public void startXML() {
fileOutput += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
fileOutput += "<schema " + "xmlns:" + WFSController.TDSNAMESPACE + "=" + WFSXMLHelper.encQuotes(namespace) + " " +
"xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns=\"http://www.w3.org/2001/XMLSchema\" xmlns:gml=\"http://www.opengis.net/gml\" " +
"targetNamespace=\"" + server + "\" elementFormDefault=\"qualified\" " +
"version=\"0.1\">";
fileOutput += "<xsd:import namespace=\"http://www.opengis.net/gml\" " +
"schemaLocation=\"http://schemas.opengis.net/gml/2.1.2/feature.xsd\"/>";
} | java | {
"resource": ""
} |
q174837 | WFSDescribeFeatureTypeWriter.writeFeatures | test | public void writeFeatures() {
for (WFSFeature feat : featureList) {
fileOutput += "<xsd:complexType name=\"" + feat.getTitle() + "\">";
fileOutput += "<xsd:complexContent>";
fileOutput += "<xsd:extension base=\"gml:" + feat.getType() + "\">";
fileOutput += "<xsd:sequence>";
for (WFSFeatureAttribute attribute : feat.getAttributes()) {
fileOutput += "<xsd:element name =\"" + attribute.getName() + "\" type=\"" + attribute.getType() + "\"/>";
}
fileOutput += "</xsd:sequence>";
fileOutput += "</xsd:extension>";
fileOutput += "</xsd:complexContent>";
fileOutput += "</xsd:complexType>";
fileOutput += "<xsd:element name =\"" + feat.getName() + "\" type=\"tds:" + feat.getTitle() + "\"/>";
}
} | java | {
"resource": ""
} |
q174838 | GridCoordSys.addLevels | test | void addLevels(List<GridRecord> records) {
for (GridRecord record : records) {
Double d = new Double(record.getLevel1());
if (!levels.contains(d)) {
levels.add(d);
}
if (dontUseVertical && (levels.size() > 1)) {
if (GridServiceProvider.debugVert) {
System.out.println(
"GribCoordSys: unused level coordinate has > 1 levels = "
+ verticalName + " " + record.getLevelType1() + " "
+ levels.size());
}
}
}
Collections.sort(levels);
if (positive.equals("down")) {
Collections.reverse(levels);
// TODO: delete
/* for( int i = 0; i < (levels.size()/2); i++ ){
Double tmp = (Double) levels.get( i );
levels.set( i, levels.get(levels.size() -i -1));
levels.set(levels.size() -i -1, tmp );
} */
}
} | java | {
"resource": ""
} |
q174839 | GridCoordSys.addDimensionsToNetcdfFile | test | void addDimensionsToNetcdfFile(NetcdfFile ncfile, Group g) {
if (dontUseVertical) {
return;
}
int nlevs = levels.size();
ncfile.addDimension(g, new Dimension(verticalName, nlevs, true));
} | java | {
"resource": ""
} |
q174840 | GridCoordSys.addToNetcdfFile | test | void addToNetcdfFile(NetcdfFile ncfile, Group g) {
if (dontUseVertical) {
return;
}
if (g == null) {
g = ncfile.getRootGroup();
}
String dims = "time";
if (!dontUseVertical) {
dims = dims + " " + verticalName;
}
if (hcs.isLatLon()) {
dims = dims + " lat lon";
} else {
dims = dims + " y x";
}
//Collections.sort( levels);
int nlevs = levels.size();
// ncfile.addDimension(g, new Dimension(verticalName, nlevs, true));
// coordinate axis and coordinate system Variable
Variable v = new Variable(ncfile, g, null, verticalName);
v.setDataType(DataType.DOUBLE);
v.addAttribute(new Attribute("long_name",
lookup.getLevelDescription(record)));
v.addAttribute(new Attribute("units", lookup.getLevelUnit(record)));
// positive attribute needed for CF-1 Height and Pressure
if (positive != null) {
v.addAttribute(new Attribute("positive", positive));
}
if (units != null) {
AxisType axisType;
if (SimpleUnit.isCompatible("millibar", units)) {
axisType = AxisType.Pressure;
} else if (SimpleUnit.isCompatible("m", units)) {
axisType = AxisType.Height;
} else {
axisType = AxisType.GeoZ;
}
v.addAttribute(
new Attribute(
"grid_level_type",
Integer.toString(record.getLevelType1())));
v.addAttribute(new Attribute(_Coordinate.AxisType,
axisType.toString()));
v.addAttribute(new Attribute(_Coordinate.Axes, dims));
if (!hcs.isLatLon()) {
v.addAttribute(new Attribute(_Coordinate.Transforms,
hcs.getGridName()));
}
}
double[] data = new double[nlevs];
for (int i = 0; i < levels.size(); i++) {
Double d = (Double) levels.get(i);
data[i] = d.doubleValue();
}
Array dataArray = Array.factory(DataType.DOUBLE, new int[]{nlevs}, data);
v.setDimensions(verticalName);
v.setCachedData(dataArray, false);
ncfile.addVariable(g, v);
// look for vertical transforms
if (record.getLevelType1() == 109) {
findCoordinateTransform(g, "Pressure", record.getLevelType1());
}
} | java | {
"resource": ""
} |
q174841 | GridCoordSys.findCoordinateTransform | test | void findCoordinateTransform(Group g, String nameStartsWith, int levelType) {
// look for variable that uses this coordinate
List<Variable> vars = g.getVariables();
for (Variable v : vars) {
if (v.getShortName().equals(nameStartsWith)) {
Attribute att = v.findAttribute("grid_level_type");
if ((att == null) || (att.getNumericValue().intValue() != levelType)) {
continue;
}
v.addAttribute(new Attribute(_Coordinate.TransformType, "Vertical"));
v.addAttribute(new Attribute("transform_name", "Existing3DField"));
}
}
} | java | {
"resource": ""
} |
q174842 | GridCoordSys.getIndex | test | int getIndex(GridRecord record) {
Double d = new Double(record.getLevel1());
return levels.indexOf(d);
} | java | {
"resource": ""
} |
q174843 | DiskCache2.exit | test | static public void exit() {
if (timer != null) {
timer.cancel();
System.out.printf("DiskCache2.exit()%n");
}
timer = null;
} | java | {
"resource": ""
} |
q174844 | DiskCache2.getFile | test | public File getFile(String fileLocation) {
if (!alwaysUseCache) {
File f = new File(fileLocation);
if (f.exists()) return f;
if (canWrite(f)) return f;
}
if (neverUseCache) {
throw new IllegalStateException("neverUseCache=true, but file does not exist and directory is not writeable ="+fileLocation);
}
File f = new File(makeCachePath(fileLocation));
if (cachePathPolicy == CachePathPolicy.NestedDirectory) {
File dir = f.getParentFile();
if (!dir.exists() && !dir.mkdirs())
cacheLog.warn("Cant create directories for file "+dir.getPath());
}
return f;
} | java | {
"resource": ""
} |
q174845 | DiskCache2.getExistingFileOrCache | test | public File getExistingFileOrCache(String fileLocation) {
File f = new File(fileLocation);
if (f.exists()) return f;
if (neverUseCache) return null;
File fc = new File(makeCachePath(fileLocation));
if (fc.exists()) return fc;
return null;
} | java | {
"resource": ""
} |
q174846 | DiskCache2.showCache | test | public void showCache(PrintStream pw) {
pw.println("Cache files");
pw.println("Size LastModified Filename");
File dir = new File(root);
File[] files = dir.listFiles();
if (files != null)
for (File file : files) {
String org = null;
try {
org = URLDecoder.decode(file.getName(), "UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
pw.println(" " + file.length() + " " + new Date(file.lastModified()) + " " + org);
}
} | java | {
"resource": ""
} |
q174847 | DiskCache2.cleanCache | test | public void cleanCache(File dir, Formatter sbuff, boolean isRoot) {
long now = System.currentTimeMillis();
File[] files = dir.listFiles();
if (files == null) {
throw new IllegalStateException( "DiskCache2: not a directory or I/O error on dir="+dir.getAbsolutePath());
}
// check for empty directory
if (!isRoot && (files.length == 0)) {
long duration = now - dir.lastModified();
duration /= 1000 * 60; // minutes
if (duration > persistMinutes) {
boolean ok = dir.delete();
if (!ok)
cacheLog.error("Unable to delete file " + dir.getAbsolutePath());
if (sbuff != null)
sbuff.format(" deleted %s %s lastModified= %s%n", ok, dir.getPath(), CalendarDate.of(dir.lastModified()));
}
return;
}
// check for expired files
for (File file : files) {
if (file.isDirectory()) {
cleanCache(file, sbuff, false);
} else {
long duration = now - file.lastModified();
duration /= 1000 * 60; // minutes
if (duration > persistMinutes) {
boolean ok = file.delete();
if (!ok)
cacheLog.error("Unable to delete file " + file.getAbsolutePath());
if (sbuff != null)
sbuff.format(" deleted %s %s lastModified= %s%n", ok, file.getPath(), CalendarDate.of(file.lastModified()));
}
}
}
} | java | {
"resource": ""
} |
q174848 | Bearing.calculateBearing | test | public static Bearing calculateBearing(Earth e, LatLonPoint pt1,
LatLonPoint pt2, Bearing result) {
return calculateBearing(e, pt1.getLatitude(), pt1.getLongitude(),
pt2.getLatitude(), pt2.getLongitude(),
result);
} | java | {
"resource": ""
} |
q174849 | Bearing.calculateBearing | test | public static Bearing calculateBearing(LatLonPoint pt1, LatLonPoint pt2,
Bearing result) {
return calculateBearing(defaultEarth, pt1.getLatitude(),
pt1.getLongitude(), pt2.getLatitude(),
pt2.getLongitude(), result);
} | java | {
"resource": ""
} |
q174850 | Bearing.main | test | public static void main(String[] args) {
//Bearing workBearing = new Bearing();
LatLonPointImpl pt1 = new LatLonPointImpl(40, -105);
LatLonPointImpl pt2 = new LatLonPointImpl(37.4, -118.4);
Bearing b = calculateBearing(pt1, pt2, null);
System.out.println("Bearing from " + pt1 + " to " + pt2 + " = \n\t"
+ b);
LatLonPointImpl pt3 = new LatLonPointImpl();
pt3 = findPoint(pt1, b.getAngle(), b.getDistance(), pt3);
System.out.println(
"using first point, angle and distance, found second point at "
+ pt3);
pt3 = findPoint(pt2, b.getBackAzimuth(), b.getDistance(), pt3);
System.out.println(
"using second point, backazimuth and distance, found first point at "
+ pt3);
/* uncomment for timing tests
for(int j=0;j<10;j++) {
long t1 = System.currentTimeMillis();
for(int i=0;i<30000;i++) {
workBearing = Bearing.calculateBearing(42.5,-93.0,
48.9,-117.09,workBearing);
}
long t2 = System.currentTimeMillis();
System.err.println ("time:" + (t2-t1));
}
*/
} | java | {
"resource": ""
} |
q174851 | Bearing.findPoint | test | public static LatLonPointImpl findPoint(Earth e, LatLonPoint pt1,
double az, double dist,
LatLonPointImpl result) {
return findPoint(e, pt1.getLatitude(), pt1.getLongitude(), az, dist,
result);
} | java | {
"resource": ""
} |
q174852 | Bearing.findPoint | test | public static LatLonPointImpl findPoint(LatLonPoint pt1, double az,
double dist,
LatLonPointImpl result) {
return findPoint(defaultEarth, pt1.getLatitude(), pt1.getLongitude(),
az, dist, result);
} | java | {
"resource": ""
} |
q174853 | Bearing.findPoint | test | public static LatLonPointImpl findPoint(double lat1, double lon1,
double az, double dist,
LatLonPointImpl result) {
return findPoint(defaultEarth, lat1, lon1, az, dist, result);
} | java | {
"resource": ""
} |
q174854 | SourcePicture.loadPictureInThread | test | public void loadPictureInThread( URL imageUrl, int priority, double rotation ) {
if ( pictureStatusCode == LOADING ) {
stopLoadingExcept( imageUrl );
}
this.imageUrl = imageUrl;
this.rotation = rotation;
LoadThread t = new LoadThread( this );
t.setPriority( priority );
t.start();
} | java | {
"resource": ""
} |
q174855 | SourcePicture.loadPicture | test | public void loadPicture( URL imageUrl, double rotation ) {
if ( pictureStatusCode == LOADING ) {
stopLoadingExcept( imageUrl );
}
this.imageUrl = imageUrl;
this.rotation = rotation;
loadPicture();
} | java | {
"resource": ""
} |
q174856 | SourcePicture.loadPicture | test | public void loadPicture() {
Tools.log("SourcePicture.loadPicture: " + imageUrl.toString() + " loaded into SourcePicture object: " + Integer.toString(this.hashCode()) );
//Tools.freeMem();
setStatus( LOADING, "Loading: " + imageUrl.toString() );
abortFlag = false;
try {
// Java 1.4 way with a Listener
ImageInputStream iis = ImageIO.createImageInputStream( imageUrl.openStream() );
Iterator i = ImageIO.getImageReaders( iis );
if ( ! i.hasNext() ) { throw new IOException ("No Readers Available!"); }
reader = (ImageReader) i.next(); // grab the first one
reader.addIIOReadProgressListener( imageProgressListener );
reader.setInput( iis );
sourcePictureBufferedImage = null;
// try {
sourcePictureBufferedImage = reader.read( 0 ); // just get the first image
/* } catch ( OutOfMemoryError e ) {
Tools.log("SourcePicture caught an OutOfMemoryError while loading an image." );
iis.close();
reader.removeIIOReadProgressListener( imageProgressListener );
reader.dispose();
setStatus(ERROR, "Out of Memory Error while reading " + imageUrl.toString());
sourcePictureBufferedImage = null;
// PictureCache.clear();
JOptionPane.showMessageDialog( null, //deliberately null or it swaps the window
"outOfMemoryError",
"genericError",
JOptionPane.ERROR_MESSAGE);
System.gc();
System.runFinalization();
Tools.log("JPO has now run a garbage collection and finalization.");
return;
} */
iis.close();
reader.removeIIOReadProgressListener( imageProgressListener );
//Tools.log("!!dispose being called!!");
reader.dispose();
if ( ! abortFlag ) {
if ( rotation != 0 ) {
setStatus( ROTATING, "Rotating: " + imageUrl.toString() );
int xRot = sourcePictureBufferedImage.getWidth() / 2;
int yRot = sourcePictureBufferedImage.getHeight() / 2;
AffineTransform rotateAf = AffineTransform.getRotateInstance( Math.toRadians( rotation ), xRot, yRot );
AffineTransformOp op = new AffineTransformOp( rotateAf, AffineTransformOp.TYPE_BILINEAR );
Rectangle2D newBounds = op.getBounds2D( sourcePictureBufferedImage );
// a simple AffineTransform would give negative top left coordinates -->
// do another transform to get 0,0 as top coordinates again.
double minX = newBounds.getMinX();
double minY = newBounds.getMinY();
AffineTransform translateAf = AffineTransform.getTranslateInstance( minX * (-1), minY * (-1) );
rotateAf.preConcatenate( translateAf );
op = new AffineTransformOp( rotateAf, AffineTransformOp.TYPE_BILINEAR );
newBounds = op.getBounds2D( sourcePictureBufferedImage );
// this piece of code is so essential!!! Otherwise the internal image format
// is totally altered and either the AffineTransformOp decides it doesn't
// want to rotate the image or web browsers can't read the resulting image.
BufferedImage targetImage = new BufferedImage(
(int) newBounds.getWidth(),
(int) newBounds.getHeight(),
BufferedImage.TYPE_3BYTE_BGR );
sourcePictureBufferedImage = op.filter( sourcePictureBufferedImage, targetImage );
}
setStatus( READY, "Loaded: " + imageUrl.toString() );
PictureCache.add( imageUrl, (SourcePicture) this.clone() );
} else {
setStatus( ERROR, "Aborted: " + imageUrl.toString() );
sourcePictureBufferedImage = null;
}
} catch ( IOException e ) {
setStatus(ERROR, "Error while reading " + imageUrl.toString());
sourcePictureBufferedImage = null;
}
} | java | {
"resource": ""
} |
q174857 | SourcePicture.stopLoading | test | public void stopLoading() {
if ( imageUrl == null )
return; // SourcePicture has never been used yet
Tools.log("SourcePicture.stopLoading: called on " + imageUrl );
if ( pictureStatusCode == LOADING ) {
reader.abort();
abortFlag = true;
//reader.dispose();
//setStatus( ERROR, "Cache Loading was stopped " + imageUrl.toString() );
//sourcePictureBufferedImage = null;
// actually the thread reading the image continues
}
} | java | {
"resource": ""
} |
q174858 | SourcePicture.stopLoadingExcept | test | public boolean stopLoadingExcept( URL exemptionURL ) {
if ( imageUrl == null )
return false; // has never been used yet
if ( pictureStatusCode != LOADING ) {
Tools.log( "SourcePicture.stopLoadingExcept: called but pointless since image is not LOADING: " + imageUrl.toString());
return false;
}
if ( ! exemptionURL.toString().equals( imageUrl.toString() ) ) {
Tools.log ("SourcePicture.stopLoadingExcept: called with Url " + exemptionURL.toString() + " --> stopping loading of " + imageUrl.toString() );
stopLoading();
return true;
} else
return false;
} | java | {
"resource": ""
} |
q174859 | SourcePicture.getSize | test | public Dimension getSize() {
if ( sourcePictureBufferedImage != null )
return new Dimension( sourcePictureBufferedImage.getWidth(), sourcePictureBufferedImage.getHeight());
else
return new Dimension(0,0);
} | java | {
"resource": ""
} |
q174860 | SourcePicture.setSourceBufferedImage | test | public void setSourceBufferedImage( BufferedImage img, String statusMessage ) {
sourcePictureBufferedImage = img;
setStatus( READY, statusMessage );
} | java | {
"resource": ""
} |
q174861 | Access.getStandardUri | test | public URI getStandardUri() {
try {
Catalog cat = dataset.getParentCatalog();
if (cat == null)
return new URI(getUnresolvedUrlName());
return cat.resolveUri(getUnresolvedUrlName());
} catch (java.net.URISyntaxException e) {
throw new RuntimeException("Error parsing URL= " + getUnresolvedUrlName());
}
} | java | {
"resource": ""
} |
q174862 | DataDescriptor.makeAssociatedField | test | DataDescriptor makeAssociatedField(int bitWidth) {
DataDescriptor assDD = new DataDescriptor();
assDD.name = name + "_associated_field";
assDD.units = "";
assDD.refVal = 0;
assDD.scale = 0;
assDD.bitWidth = bitWidth;
assDD.type = 0;
assDD.f = 0;
assDD.x = 31;
assDD.y = 22;
assDD.fxy = (short) ((f << 14) + (x << 8) + (y));
return assDD;
} | java | {
"resource": ""
} |
q174863 | DataDescriptor.transferInfo | test | static public void transferInfo(List<DataDescriptor> fromList, List<DataDescriptor> toList) { // get info from proto message
if (fromList.size() != toList.size())
throw new IllegalArgumentException("list sizes dont match "+fromList.size()+" != "+toList.size());
for (int i=0; i<fromList.size(); i++) {
DataDescriptor from = fromList.get(i);
DataDescriptor to = toList.get(i);
to.refersTo = from.refersTo;
to.name = from.name;
if (from.getSubKeys() != null)
transferInfo(from.getSubKeys(), to.getSubKeys());
}
} | java | {
"resource": ""
} |
q174864 | DataDescriptor.countBits | test | int countBits() {
int total_nbits = 0;
total_nbytesCDM = 0;
for (DataDescriptor dd : subKeys) {
if (dd.subKeys != null) {
total_nbits += dd.countBits();
total_nbytesCDM += dd.total_nbytesCDM;
} else if (dd.f == 0) {
total_nbits += dd.bitWidth;
total_nbytesCDM += dd.getByteWidthCDM();
}
}
// replication
if (replication > 1) {
total_nbits *= replication;
total_nbytesCDM *= replication;
}
return total_nbits;
} | java | {
"resource": ""
} |
q174865 | DataDescriptor.equals2 | test | public boolean equals2(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DataDescriptor that = (DataDescriptor) o;
if (fxy != that.fxy) return false;
if (replication != that.replication) return false;
if (type != that.type) return false;
if (subKeys != null ? !subKeys.equals(that.subKeys) : that.subKeys != null) return false;
return true;
} | java | {
"resource": ""
} |
q174866 | DbaseFile.loadHeader | test | private int loadHeader() {
if (headerLoaded) return 0;
InputStream s = stream;
if (s == null) return -1;
try {
BufferedInputStream bs = new BufferedInputStream(s);
ds = new DataInputStream(bs);
/* read the header as one block of bytes*/
Header = new byte[32];
ds.readFully(Header);
//System.out.println("dbase header is " + Header);
if (Header[0] == '<') { //looks like html coming back to us!
close(ds);
return -1;
}
filetype = Header[0];
/* 4 bytes for number of records is in little endian */
nrecords = Swap.swapInt(Header, 4);
nbytesheader = Swap.swapShort(Header, 8);
/* read in the Field Descriptors */
/* have to figure how many there are from
* the header size. Should be nbytesheader/32 -1
*/
nfields = (nbytesheader / 32) - 1;
if (nfields < 1) {
System.out.println("nfields = " + nfields);
System.out.println("nbytesheader = " +
nbytesheader);
return -1;
}
FieldDesc = new DbaseFieldDesc[nfields];
data = new DbaseData[nfields];
for (int i = 0; i < nfields; i++) {
FieldDesc[i] = new DbaseFieldDesc(ds, filetype);
data[i] = new DbaseData(FieldDesc[i],
nrecords);
}
/* read the last byte of the header (0x0d) */
ds.readByte();
headerLoaded = true;
} catch (java.io.IOException e) {
close(s);
return -1;
}
return 0;
} | java | {
"resource": ""
} |
q174867 | DbaseFile.loadData | test | private int loadData() {
if (!headerLoaded) return -1;
if (dataLoaded) return 0;
InputStream s = stream;
if (s == null) return -1;
try {
/* read in the data */
for (int i = 0; i < nrecords; i++) {
/* read the data record indicator */
byte recbyte = ds.readByte();
if (recbyte == 0x20) {
for (int j = 0; j < nfields; j++) {
data[j].readRowN(ds, i);
}
} else {
/* a deleted record */
nrecords--;
i--;
}
}
dataLoaded = true;
} catch (java.io.IOException e) {
close(s);
return -1;
} finally {
close(s);
}
return 0;
} | java | {
"resource": ""
} |
q174868 | DbaseFile.getField | test | public DbaseData getField(String Name) {
for (int i = 0; i < nfields; i++) {
if (FieldDesc[i].Name.equals(Name)) return data[i];
}
return null;
} | java | {
"resource": ""
} |
q174869 | DbaseFile.getDoublesByName | test | public double[] getDoublesByName(String Name) {
DbaseData d;
if ((d = getField(Name)) == null) return null;
if (d.getType() == DbaseData.TYPE_CHAR) {
String[] s = d.getStrings();
double[] dd = new double[s.length];
for (int i = 0; i < s.length; i++) {
dd[i] = Double.valueOf(s[i]);
}
return dd;
}
if (d.getType() == DbaseData.TYPE_BOOLEAN) {
boolean[] b = d.getBooleans();
double[] dd = new double[b.length];
for (int i = 0; i < b.length; i++) {
if (b[i]) {
dd[i] = 1;
} else {
dd[i] = 0;
}
}
return dd;
}
return d.getDoubles();
} | java | {
"resource": ""
} |
q174870 | DbaseFile.getStringsByName | test | public String[] getStringsByName(String Name) {
DbaseData d;
if ((d = getField(Name)) == null) return null;
if (d.getType() != DbaseData.TYPE_CHAR) return null;
return d.getStrings();
} | java | {
"resource": ""
} |
q174871 | DbaseFile.getBooleansByName | test | public boolean[] getBooleansByName(String Name) {
DbaseData d;
if ((d = getField(Name)) == null) return null;
if (d.getType() != DbaseData.TYPE_BOOLEAN) return null;
return d.getBooleans();
} | java | {
"resource": ""
} |
q174872 | DbaseFile.getFieldName | test | public String getFieldName(int i) {
if (i >= nfields || i < 0) {
return null;
}
return (FieldDesc[i].Name);
} | java | {
"resource": ""
} |
q174873 | DbaseFile.getFieldNames | test | public String[] getFieldNames() {
String[] s = new String[nfields];
for (int i = 0; i < nfields; i++) {
s[i] = getFieldName(i);
}
return s;
} | java | {
"resource": ""
} |
q174874 | DbaseFile.main | test | public static void main(String[] args) {
if (args.length < 1) {
System.out.println("filename or URL required");
System.exit(-1);
}
for (String s : args) {
System.out.println("*** Dump of Dbase " + s + ":");
try {
DbaseFile dbf = new DbaseFile(s);
// load() method reads all data at once
if (dbf.loadHeader() != 0) {
System.out.println("Error loading header" + s);
System.exit(-1);
}
// output schema as [type0 field0, type1 field1, ...]
String[] fieldNames = dbf.getFieldNames();
System.out.print("[");
int nf = dbf.getNumFields();
DbaseData[] dbd = new DbaseData[nf];
for (int field = 0; field < nf; field++) {
dbd[field] = dbf.getField(field);
switch (dbd[field].getType()) {
case DbaseData.TYPE_BOOLEAN:
System.out.print("boolean ");
break;
case DbaseData.TYPE_CHAR:
System.out.print("String ");
break;
case DbaseData.TYPE_NUMERIC:
System.out.print("double ");
break;
}
System.out.print(fieldNames[field]);
if (field < nf - 1)
System.out.print(", ");
}
System.out.println("]");
if (dbf.loadData() != 0) {
System.out.println("Error loading data" + s);
System.exit(-1);
}
// output data
for (int rec = 0; rec < dbf.getNumRecords(); rec++) {
for (int field = 0; field < nf; field++) {
System.out.print(dbd[field].getData(rec));
if (field < nf - 1)
System.out.print(", ");
else
System.out.println();
}
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
} | java | {
"resource": ""
} |
q174875 | DapNode.getAttributes | test | public Map<String, DapAttribute> getAttributes()
{
if(attributes == null) attributes = new HashMap<String, DapAttribute>();
return attributes;
} | java | {
"resource": ""
} |
q174876 | DapNode.setAttribute | test | synchronized public DapAttribute setAttribute(DapAttribute attr)
throws DapException
{
if(attributes == null)
attributes = new HashMap<String, DapAttribute>();
DapAttribute old = attributes.get(attr.getShortName());
attributes.put(attr.getShortName(), attr);
attr.setParent(this);
return old;
} | java | {
"resource": ""
} |
q174877 | DapNode.removeAttribute | test | public synchronized void removeAttribute(DapAttribute attr)
throws DapException
{
if(this.attributes == null)
return;
String name = attr.getShortName();
if(this.attributes.containsKey(name))
this.attributes.remove(name);
} | java | {
"resource": ""
} |
q174878 | DapNode.getGroup | test | public DapGroup getGroup()
{
if(this.sort == DapSort.DATASET)
return null;
// Walk the parent node until we find a group
DapNode group = parent;
while(group != null) {
switch (group.getSort()) {
case DATASET:
case GROUP:
return (DapGroup) group;
default:
group = group.getParent();
break;
}
}
return (DapGroup) group;
} | java | {
"resource": ""
} |
q174879 | DapNode.getContainer | test | public DapNode getContainer()
{
DapNode parent = this.parent;
switch (getSort()) {
default:
break;
case ENUMCONST:
parent = ((DapEnumConst) this).getParent().getContainer();
break;
case ATTRIBUTE:
case ATTRIBUTESET:
case OTHERXML:
parent = ((DapAttribute) this).getParent();
if(parent instanceof DapVariable)
parent = parent.getContainer();
break;
case MAP:
parent = ((DapMap) this).getVariable().getContainer();
break;
}
return parent;
} | java | {
"resource": ""
} |
q174880 | DapNode.getEscapedShortName | test | public String getEscapedShortName()
{
if(this.escapedname == null)
this.escapedname = Escape.backslashEscape(getShortName(), null);
return this.escapedname;
} | java | {
"resource": ""
} |
q174881 | DapNode.getContainerPath | test | public List<DapNode> getContainerPath()
{
List<DapNode> path = new ArrayList<DapNode>();
DapNode current = this.getContainer();
for(; ; ) {
path.add(0, current);
if(current.getContainer() == null)
break;
current = current.getContainer();
}
return path;
} | java | {
"resource": ""
} |
q174882 | DapNode.getGroupPath | test | public List<DapGroup> getGroupPath()
{
List<DapGroup> path = new ArrayList<DapGroup>();
DapNode current = this;
for(; ; ) {
if(current.getSort() == DapSort.GROUP
|| current.getSort() == DapSort.DATASET)
path.add(0, (DapGroup) current);
if(current.getContainer() == null)
break;
current = current.getContainer();
}
return path;
} | java | {
"resource": ""
} |
q174883 | DapNode.computefqn | test | public String
computefqn()
{
List<DapNode> path = getPath(); // excludes root/wrt
StringBuilder fqn = new StringBuilder();
DapNode parent = path.get(0);
for(int i = 1; i < path.size(); i++) { // start at 1 to skip root
DapNode current = path.get(i);
// Depending on what parent is, use different delimiters
switch (parent.getSort()) {
case DATASET:
case GROUP:
case ENUMERATION:
fqn.append('/');
fqn.append(Escape.backslashEscape(current.getShortName(),"/."));
break;
// These use '.'
case STRUCTURE:
case SEQUENCE:
case ENUMCONST:
case VARIABLE:
fqn.append('.');
fqn.append(current.getEscapedShortName());
break;
default: // Others should never happen
throw new IllegalArgumentException("Illegal FQN parent");
}
parent = current;
}
return fqn.toString();
} | java | {
"resource": ""
} |
q174884 | DapNode.isTopLevel | test | public boolean isTopLevel()
{
return parent == null
|| parent.getSort() == DapSort.DATASET
|| parent.getSort() == DapSort.GROUP;
} | java | {
"resource": ""
} |
q174885 | D4DSP.build | test | protected void
build(DapDataset dmr, byte[] serialdata, ByteOrder order)
throws DapException
{
setDMR(dmr);
// "Compile" the databuffer section of the server response
this.databuffer = ByteBuffer.wrap(serialdata).order(order);
D4DataCompiler compiler = new D4DataCompiler(this, getChecksumMode(), getOrder(), this.databuffer);
compiler.compile();
} | java | {
"resource": ""
} |
q174886 | PreferencesExt.putBeanCollection | test | public void putBeanCollection(String key, Collection newValue) {
// if matches a stored Default, dont store
Object oldValue = getBean(key, null);
if ((oldValue == null) || !oldValue.equals( newValue))
keyValues.put( key, new Bean.Collection(newValue));
} | java | {
"resource": ""
} |
q174887 | PreferencesExt.getList | test | public List getList(String key, List def) {
try {
Object bean = getBean(key, def);
return (List) bean;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} | java | {
"resource": ""
} |
q174888 | PreferencesExt._getObject | test | private Object _getObject(String keyName) {
Object result = null;
try {
result = keyValues.get( keyName);
if (result == null) {
// if failed, check the stored Defaults
PreferencesExt sd = getStoredDefaults();
if (sd != null)
result = sd.getObjectFromNode( absolutePath(), keyName);
}
} catch (Exception e) {
// Ignoring exception causes default to be returned
}
return result;
} | java | {
"resource": ""
} |
q174889 | Grib2Record.readData | test | public float[] readData(RandomAccessFile raf, long drsPos) throws IOException {
raf.seek(drsPos);
Grib2SectionDataRepresentation drs = new Grib2SectionDataRepresentation(raf);
Grib2SectionBitMap bms = new Grib2SectionBitMap(raf);
Grib2SectionData dataSection = new Grib2SectionData(raf);
Grib2Gds gds = getGDS();
Grib2DataReader reader = new Grib2DataReader(drs.getDataTemplate(), gdss.getNumberPoints(), drs.getDataPoints(),
getScanMode(), gds.getNxRaw(), dataSection.getStartingPosition(), dataSection.getMsgLength());
Grib2Drs gdrs = drs.getDrs(raf);
float[] data = reader.getData(raf, bms, gdrs);
if (gds.isThin())
data = QuasiRegular.convertQuasiGrid(data, gds.getNptsInLine(), gds.getNxRaw(), gds.getNyRaw(), GribData.getInterpolationMethod());
lastRecordRead = this;
return data;
} | java | {
"resource": ""
} |
q174890 | DSPPrinter.print | test | public DSPPrinter
print()
throws DapException
{
DapDataset dmr = this.dsp.getDMR();
if(this.ce == null)
this.ce = CEConstraint.getUniversal(dmr);
this.printer.setIndent(0);
List<DapVariable> topvars = dmr.getTopVariables();
for(int i = 0; i < topvars.size(); i++) {
DapVariable top = topvars.get(i);
List<Slice> slices = this.ce.getConstrainedSlices(top);
if(this.ce.references(top)) {
DataCursor data = dsp.getVariableData(top);
printVariable(data,slices);
}
}
printer.eol();
return this;
} | java | {
"resource": ""
} |
q174891 | DSPPrinter.printCompoundInstance | test | protected void
printCompoundInstance(DataCursor datav)
throws DapException
{
//Index index = datav.getIndex();
DapStructure dstruct = (DapStructure) ((DapVariable) datav.getTemplate()).getBaseType();
switch (datav.getScheme()) {
case STRUCTURE:
case RECORD:
List<DapVariable> dfields = dstruct.getFields();
for(int f = 0; f < dfields.size(); f++) {
DapVariable field = dfields.get(f);
List<Slice> fieldslices = this.ce.getConstrainedSlices(field);
DataCursor fdata = datav.readField(f);
printVariable(fdata,fieldslices);
}
break;
case SEQUENCE:
DapSequence dseq = (DapSequence)dstruct;
long count = datav.getRecordCount();
for(long r = 0; r < count; r++) {
DataCursor dr = datav.readRecord(r);
printer.marginPrint("[");
printer.eol();
printer.indent();
printCompoundInstance(dr);
printer.outdent();
printer.marginPrint("]");
}
break;
default:
throw new DapException("Unexpected data cursor scheme:" + datav.getScheme());
}
} | java | {
"resource": ""
} |
q174892 | NcMLWriter.writeToString | test | public String writeToString(Element elem) {
try (StringWriter writer = new StringWriter()) {
writeToWriter(elem, writer);
return writer.toString();
} catch (IOException e) {
throw new AssertionError("CAN'T HAPPEN: StringWriter.close() is a no-op.", e);
}
} | java | {
"resource": ""
} |
q174893 | NcMLWriter.writeToFile | test | public void writeToFile(Element elem, File outFile) throws IOException {
try (OutputStream outStream = new BufferedOutputStream(new FileOutputStream(outFile, false))) {
writeToStream(elem, outStream);
}
} | java | {
"resource": ""
} |
q174894 | NcMLWriter.writeToStream | test | public void writeToStream(Element elem, OutputStream outStream) throws IOException {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new BufferedOutputStream(outStream), xmlFormat.getEncoding()))) {
writeToWriter(elem, writer);
}
} | java | {
"resource": ""
} |
q174895 | NcMLWriter.writeToWriter | test | public void writeToWriter(Element elem, Writer writer) throws IOException {
xmlOutputter.setFormat(xmlFormat);
elem.detach(); // In case this element had previously been added to a Document.
xmlOutputter.output(new Document(elem), writer);
} | java | {
"resource": ""
} |
q174896 | NcMLWriter.makeDimensionElement | test | public Element makeDimensionElement(Dimension dim) throws IllegalArgumentException {
if (!dim.isShared()) {
throw new IllegalArgumentException("Cannot create private dimension: " +
"in NcML, <dimension> elements are always shared.");
}
Element dimElem = new Element("dimension", namespace);
dimElem.setAttribute("name", dim.getShortName());
dimElem.setAttribute("length", Integer.toString(dim.getLength()));
if (dim.isUnlimited())
dimElem.setAttribute("isUnlimited", "true");
return dimElem;
} | java | {
"resource": ""
} |
q174897 | McIDASAreaTransformBuilder.makeCoordinateTransform | test | public ProjectionCT makeCoordinateTransform(AttributeContainer ctv, String units) {
int[] area = getIntArray(ctv, McIDASAreaProjection.ATTR_AREADIR);
int[] nav = getIntArray(ctv, McIDASAreaProjection.ATTR_NAVBLOCK);
int[] aux = null;
if (ctv.findAttributeIgnoreCase(McIDASAreaProjection.ATTR_AUXBLOCK) != null) {
aux = getIntArray(ctv, McIDASAreaProjection.ATTR_AUXBLOCK);
}
// not clear if its ok if aux is null, coverity is complaining
McIDASAreaProjection proj = new McIDASAreaProjection(area, nav, aux);
return new ProjectionCT(ctv.getName(), "FGDC", proj);
} | java | {
"resource": ""
} |
q174898 | McIDASAreaTransformBuilder.getIntArray | test | private int[] getIntArray(AttributeContainer ctv, String attName) {
Attribute att = ctv.findAttribute(attName);
if (att == null) {
throw new IllegalArgumentException("McIDASArea coordTransformVariable " + ctv.getName() + " must have " + attName + " attribute");
}
Array arr = att.getValues();
return (int[]) arr.get1DJavaArray(int.class);
} | java | {
"resource": ""
} |
q174899 | SI.bu | test | private static BaseUnit bu(final String name, final String symbol,
final BaseQuantity quantity) throws NameException,
UnitExistsException {
return BaseUnit.getOrCreate(UnitName.newUnitName(name, null, symbol),
quantity);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.