_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q175000 | DatasetUrl.searchFragment | test | static private ServiceType searchFragment(String fragment) {
if (fragment.length() == 0)
return null;
Map<String, String> map = parseFragment(fragment);
if (map == null) return null;
String protocol = map.get("protocol");
if(protocol == null) {
for(String p: FRAGPROTOCOLS) {
if(map.get(p) != null) {protocol = p; break;}
}
}
if (protocol != null) {
if (protocol.equalsIgnoreCase("dap") || protocol.equalsIgnoreCase("dods"))
return ServiceType.OPENDAP;
if (protocol.equalsIgnoreCase("dap4"))
return ServiceType.DAP4;
if (protocol.equalsIgnoreCase("cdmremote"))
return ServiceType.CdmRemote;
if (protocol.equalsIgnoreCase("thredds"))
return ServiceType.THREDDS;
if (protocol.equalsIgnoreCase("ncml"))
return ServiceType.NCML;
}
return null;
} | java | {
"resource": ""
} |
q175001 | DatasetUrl.searchPath | test | static private ServiceType searchPath(String url) {
if(false) { // Disable for now
if(url == null || url.length() == 0)
return null;
url = url.toLowerCase(); // for matching purposes
for(int i=0; i<FRAGPROTOCOLS.length;i++) {
String p = FRAGPROTOCOLS[i];
if(url.indexOf("/thredds/"+p.toLowerCase()+"/")>= 0) {
return FRAGPROTOSVCTYPE[i];
}
}
}
return null;
} | java | {
"resource": ""
} |
q175002 | DatasetUrl.decodePathExtension | test | static private ServiceType decodePathExtension(String path) {
// Look at the path extensions
if (path.endsWith(".dds") || path.endsWith(".das") || path.endsWith(".dods"))
return ServiceType.OPENDAP;
if (path.endsWith(".dmr") || path.endsWith(".dap") || path.endsWith(".dsr"))
return ServiceType.DAP4;
if (path.endsWith(".xml") || path.endsWith(".ncml"))
return ServiceType.NCML;
return null;
} | java | {
"resource": ""
} |
q175003 | DatasetUrl.checkIfDods | test | static private ServiceType checkIfDods(String location) throws IOException {
int len = location.length();
// Strip off any trailing .dds, .das, or .dods
if (location.endsWith(".dds"))
location = location.substring(0, len - ".dds".length());
if (location.endsWith(".das"))
location = location.substring(0, len - ".das".length());
if (location.endsWith(".dods"))
location = location.substring(0, len - ".dods".length());
// Opendap assumes that the caller has properly escaped the url
try (
// For some reason, the head method is not using credentials
// method = session.newMethodHead(location + ".dds");
HTTPMethod method = HTTPFactory.Get(location + ".dds")) {
int status = method.execute();
if (status == 200) {
Header h = method.getResponseHeader("Content-Description");
if ((h != null) && (h.getValue() != null)) {
String v = h.getValue();
if (v.equalsIgnoreCase("dods-dds") || v.equalsIgnoreCase("dods_dds"))
return ServiceType.OPENDAP;
else
throw new IOException("OPeNDAP Server Error= " + method.getResponseAsString());
}
}
if (status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_FORBIDDEN)
throw new IOException("Unauthorized to open dataset " + location);
// not dods
return null;
}
} | java | {
"resource": ""
} |
q175004 | DatasetUrl.checkIfDap4 | test | static private ServiceType checkIfDap4(String location) throws IOException {
// Strip off any trailing DAP4 prefix
if (location.endsWith(".dap"))
location = location.substring(0, location.length() - ".dap".length());
else if (location.endsWith(".dmr"))
location = location.substring(0, location.length() - ".dmr".length());
else if (location.endsWith(".dmr.xml"))
location = location.substring(0, location.length() - ".dmr.xml".length());
else if (location.endsWith(".dsr"))
location = location.substring(0, location.length() - ".dsr".length());
try (HTTPMethod method = HTTPFactory.Get(location + ".dmr.xml")) {
int status = method.execute();
if (status == 200) {
Header h = method.getResponseHeader("Content-Type");
if ((h != null) && (h.getValue() != null)) {
String v = h.getValue();
if (v.startsWith("application/vnd.opendap.org"))
return ServiceType.DAP4;
}
}
if (status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_FORBIDDEN)
throw new IOException("Unauthorized to open dataset " + location);
// not dods
return null;
}
} | java | {
"resource": ""
} |
q175005 | NcStreamWriter.sendData2 | test | public long sendData2(Variable v, Section section, OutputStream out, NcStreamCompression compress) throws IOException, InvalidRangeException {
if (show) System.out.printf(" %s section=%s%n", v.getFullName(), section);
boolean isVlen = v.isVariableLength(); // && v.getRank() > 1;
if (isVlen)
v.read(section);
NcStreamDataCol encoder = new NcStreamDataCol();
NcStreamProto.DataCol dataProto = encoder.encodeData2(v.getFullName(), isVlen, section, v.read(section));
// LOOK trap error, write error message ??
// dataProto.writeDelimitedTo(out);
long size = 0;
size += writeBytes(out, NcStream.MAGIC_DATA2); // data version 3
byte[] datab = dataProto.toByteArray();
size += NcStream.writeVInt(out, datab.length); // dataProto len
size += writeBytes(out, datab); // dataProto
return size;
} | java | {
"resource": ""
} |
q175006 | DapUtil.fqnSuffix | test | static public String fqnSuffix(String fqn)
{
int structindex = fqn.lastIndexOf('.');
int groupindex = fqn.lastIndexOf('/');
if(structindex >= 0)
return fqn.substring(structindex + 1, fqn.length());
else
return fqn.substring(groupindex + 1, fqn.length());
} | java | {
"resource": ""
} |
q175007 | DapUtil.fqnPrefix | test | static public String fqnPrefix(String fqn)
{
int structindex = fqn.lastIndexOf('.');
int groupindex = fqn.lastIndexOf('/');
if(structindex >= 0)
return fqn.substring(0, structindex);
else
return fqn.substring(0, groupindex);
} | java | {
"resource": ""
} |
q175008 | DapUtil.locateFile | test | static public String
locateFile(String filename, String abspath, boolean wantdir)
{
Deque<String> q = new ArrayDeque<String>();
// clean up the path and filename
filename = filename.trim().replace('\\', '/');
abspath = abspath.trim().replace('\\', '/');
if(filename.charAt(0) == '/') filename = filename.substring(1);
if(filename.endsWith("/")) filename = filename.substring(0, filename.length() - 1);
if(abspath.endsWith("/")) abspath = abspath.substring(0, abspath.length() - 1);
q.addFirst(abspath); // prime the search queue
for(; ; ) { // breadth first search
String currentpath = q.poll();
if(currentpath == null) break; // done searching
File current = new File(currentpath);
File[] contents = current.listFiles();
if(contents != null) {
for(File subfile : contents) {
if(!subfile.getName().equals(filename)) continue;
if((wantdir && subfile.isDirectory())
|| (!wantdir && subfile.isFile())) {
// Assume this is it
return DapUtil.canonicalpath(subfile.getAbsolutePath());
}
}
for(File subfile : contents) {
if(subfile.isDirectory())
q.addFirst(currentpath + "/" + subfile.getName());
}
}
}
return null;
} | java | {
"resource": ""
} |
q175009 | DapUtil.locateRelative | test | static public String
locateRelative(String relpath, String abspath, boolean wantdir)
{
// clean up the path and filename
relpath = relpath.trim().replace('\\', '/');
if(relpath.charAt(0) == '/') relpath = relpath.substring(1);
if(relpath.endsWith("/")) relpath = relpath.substring(0, relpath.length() - 1);
String[] pieces = relpath.split("[/]");
String partial = abspath;
for(int i = 0; i < pieces.length - 1; i++) {
String nextdir = locateFile(pieces[i], abspath, true);
if(nextdir == null) return null;
partial = nextdir;
}
// See if the final file|dir exists in this dir
String finalpath = locateFile(pieces[pieces.length - 1], partial, wantdir);
return finalpath;
} | java | {
"resource": ""
} |
q175010 | DapUtil.extract | test | static public byte[] extract(ByteBuffer buf)
{
int len = buf.limit();
byte[] bytes = new byte[len];
buf.rewind();
buf.get(bytes);
return bytes;
} | java | {
"resource": ""
} |
q175011 | DapUtil.getStructurePath | test | static public List<DapVariable>
getStructurePath(DapVariable var)
{
List<DapNode> path = var.getPath();
List<DapVariable> structpath = new ArrayList<DapVariable>();
for(int i = 0; i < path.size(); i++) {
DapNode node = path.get(i);
switch (node.getSort()) {
case DATASET:
case GROUP:
break;
case VARIABLE:
structpath.add((DapVariable) node);
break;
default:
assert false : "Internal error";
}
}
return structpath;
} | java | {
"resource": ""
} |
q175012 | DapUtil.nullify | test | static public String
nullify(String path)
{
return (path != null && path.length() == 0 ? null : path);
} | java | {
"resource": ""
} |
q175013 | DapUtil.join | test | static public String
join(String[] array, String sep, int from, int upto)
{
if(sep == null) sep = "";
if(from < 0 || upto > array.length)
throw new IndexOutOfBoundsException();
if(upto <= from)
return "";
StringBuilder result = new StringBuilder();
boolean first = true;
for(int i = from; i < upto; i++, first = false) {
if(!first) result.append(sep);
result.append(array[i]);
}
return result.toString();
} | java | {
"resource": ""
} |
q175014 | DapUtil.hasDriveLetter | test | static public boolean
hasDriveLetter(String path)
{
boolean hasdr = false;
if(path != null && path.length() >= 2) {
hasdr = (DRIVELETTERS.indexOf(path.charAt(0)) >= 0 && path.charAt(1) == ':');
}
return hasdr;
} | java | {
"resource": ""
} |
q175015 | DapUtil.getProtocols | test | static public List<String>
getProtocols(String url, int[] breakpoint)
{
// break off any leading protocols;
// there may be more than one.
// Watch out for Windows paths starting with a drive letter.
// Each protocol has trailing ':' removed
List<String> allprotocols = new ArrayList<>(); // all leading protocols upto path or host
// Note, we cannot use split because of the context sensitivity
StringBuilder buf = new StringBuilder(url);
int protosize = 0;
for(; ; ) {
int index = buf.indexOf(":");
if(index < 0) break; // no more protocols
String protocol = buf.substring(0, index);
// Check for windows drive letter
if(index == 1 //=>|protocol| == 1 => windows drive letter
&& "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.indexOf(buf.charAt(0)) >= 0) break;
allprotocols.add(protocol);
buf.delete(0, index + 1); // remove the leading protocol
protosize += (index + 1);
if(buf.indexOf("/") == 0)
break; // anything after this is not a protocol
}
breakpoint[0] = protosize;
return allprotocols;
} | java | {
"resource": ""
} |
q175016 | DapUtil.indexToSlices | test | static public List<Slice>
indexToSlices(Index indices, DapVariable template)
throws dap4.core.util.DapException
{
List<DapDimension> dims = template.getDimensions();
List<Slice> slices = indexToSlices(indices, dims);
return slices;
} | java | {
"resource": ""
} |
q175017 | DapUtil.offsetToSlices | test | static public List<Slice>
offsetToSlices(long offset, DapVariable template)
throws DapException
{
List<DapDimension> dims = template.getDimensions();
long[] dimsizes = DapUtil.getDimSizes(dims);
return indexToSlices(offsetToIndex(offset, dimsizes), template);
} | java | {
"resource": ""
} |
q175018 | DapUtil.isContiguous | test | static public boolean
isContiguous(List<Slice> slices)
{
for(Slice sl : slices) {
if(sl.getStride() != 1) return false;
}
return true;
} | java | {
"resource": ""
} |
q175019 | DapUtil.isSinglePoint | test | static public boolean
isSinglePoint(List<Slice> slices)
{
for(Slice sl : slices) {
if(sl.getCount() != 1) return false;
}
return true;
} | java | {
"resource": ""
} |
q175020 | DapUtil.slicesToIndex | test | static public Index
slicesToIndex(List<Slice> slices)
throws DapException
{
long[] positions = new long[slices.size()];
long[] dimsizes = new long[slices.size()];
for(int i = 0; i < positions.length; i++) {
Slice s = slices.get(i);
if(s.getCount() != 1)
throw new DapException("Attempt to convert non-singleton sliceset to index");
positions[i] = s.getFirst();
dimsizes[i] = s.getMax();
}
return new Index(positions, dimsizes);
} | java | {
"resource": ""
} |
q175021 | NcStreamReader.readData | test | public DataResult readData(InputStream is, NetcdfFile ncfile, String location) throws IOException {
byte[] b = new byte[4];
int bytesRead = NcStream.readFully(is, b);
if (bytesRead < b.length)
throw new EOFException(location);
if (NcStream.test(b,NcStream.MAGIC_DATA)) return readData1(is, ncfile);
if (NcStream.test(b,NcStream.MAGIC_DATA2)) return readData2(is);
throw new IOException("Data transfer corrupted on " + location);
} | java | {
"resource": ""
} |
q175022 | RecordDatasetHelper.setStationInfo | test | public void setStationInfo(String stnIdVName, String stnDescVName, String stnIndexVName, StationHelper stationHelper) {
this.stnIdVName = stnIdVName;
this.stnDescVName = stnDescVName;
this.stnIndexVName = stnIndexVName;
this.stationHelper = stationHelper;
if (stnIdVName != null) {
Variable stationVar = ncfile.findVariable(stnIdVName);
stationIdType = stationVar.getDataType();
}
} | java | {
"resource": ""
} |
q175023 | RecordDatasetHelper.setShortNames | test | public void setShortNames(String latVName, String lonVName, String altVName, String obsTimeVName, String nomTimeVName) {
this.latVName = latVName;
this.lonVName = lonVName;
this.zcoordVName = altVName;
this.obsTimeVName = obsTimeVName;
this.nomTimeVName = nomTimeVName;
} | java | {
"resource": ""
} |
q175024 | FeatureCollectionConfigBuilder.readConfigFromCatalog | test | public FeatureCollectionConfig readConfigFromCatalog(String catalogAndPath) {
String catFilename;
String fcName = null;
int pos = catalogAndPath.indexOf("#");
if (pos > 0) {
catFilename = catalogAndPath.substring(0, pos);
fcName = catalogAndPath.substring(pos + 1);
} else {
catFilename = catalogAndPath;
}
File cat = new File(catFilename);
org.jdom2.Document doc;
try {
SAXBuilder builder = new SAXBuilder();
doc = builder.build(cat);
} catch (Exception e) {
e.printStackTrace();
return null;
}
try {
List<Element> fcElems = new ArrayList<>();
findFeatureCollection(doc.getRootElement(), fcName, fcElems);
if (fcElems.size() > 0)
return readConfig(fcElems.get(0));
} catch (IllegalStateException e) {
e.printStackTrace();
}
return null;
} | java | {
"resource": ""
} |
q175025 | DapGroup.addDecl | test | public void
addDecl(DapNode newdecl)
throws DapException
{
DapSort newsort = newdecl.getSort();
String newname = newdecl.getShortName();
boolean suppress = false;
// Look for name conflicts (ignore anonymous dimensions)
if(newsort != DapSort.DIMENSION || newname != null) {
for(DapNode decl : decls) {
if(newsort == decl.getSort()
&& newname.equals(decl.getShortName()))
throw new DapException("DapGroup: attempt to add duplicate decl: " + newname);
}
} else { // Anonymous
DapDimension anon = (DapDimension) newdecl;
assert (newsort == DapSort.DIMENSION && newname == null);
// Search for matching anonymous dimension
boolean found = false;
for(DapDimension dim : dimensions) {
if(!dim.isShared() && dim.getSize() == anon.getSize()) {
found = true;
break;
}
}
// Define the anondecl in root group
if(!found && !isTopLevel()) getDataset().addDecl(anon);
suppress = found || !isTopLevel();
}
if(!suppress) {
decls.add(newdecl);
newdecl.setParent(this); // Cross link
}
switch (newdecl.getSort()) {
case ATTRIBUTE:
case ATTRIBUTESET:
case OTHERXML:
super.addAttribute((DapAttribute) newdecl);
break;
case DIMENSION:
if(!suppress)
dimensions.add((DapDimension) newdecl);
break;
case ENUMERATION:
enums.add((DapEnumeration) newdecl);
break;
case ATOMICTYPE:
break; // do nothing
case STRUCTURE:
case SEQUENCE:
compounds.add((DapStructure)newdecl);
break;
case VARIABLE:
variables.add((DapVariable) newdecl);
break;
case GROUP:
case DATASET:
if(this != (DapGroup) newdecl)
groups.add((DapGroup) newdecl);
break;
default:
throw new ClassCastException(newdecl.getShortName());
}
} | java | {
"resource": ""
} |
q175026 | DapGroup.updateGroups | test | void
updateGroups(List<DapGroup> groups)
{
// Verify that the incoming groups are all and only in the list of groups.
assert (groups.size() == this.groups.size()) : "Update groups: not same size";
for(DapGroup g : groups) {
if(!this.groups.contains(g))
assert (false) : "Update groups: attempt to add new group";
}
} | java | {
"resource": ""
} |
q175027 | DapGroup.findVariable | test | public DapVariable
findVariable(String name)
{
DapNode var = findInGroup(name, DapSort.VARIABLE);
return (DapVariable) var;
} | java | {
"resource": ""
} |
q175028 | COARDSConvention.getAxisType | test | protected AxisType getAxisType( NetcdfDataset ncDataset, VariableEnhanced v) {
String unit = v.getUnitsString();
if (unit == null)
return null;
unit = unit.trim();
if( unit.equalsIgnoreCase("degrees_east") ||
unit.equalsIgnoreCase("degrees_E") ||
unit.equalsIgnoreCase("degreesE") ||
unit.equalsIgnoreCase("degree_east") ||
unit.equalsIgnoreCase("degree_E") ||
unit.equalsIgnoreCase("degreeE"))
return AxisType.Lon;
if ( unit.equalsIgnoreCase("degrees_north") ||
unit.equalsIgnoreCase("degrees_N") ||
unit.equalsIgnoreCase("degreesN") ||
unit.equalsIgnoreCase("degree_north") ||
unit.equalsIgnoreCase("degree_N") ||
unit.equalsIgnoreCase("degreeN"))
return AxisType.Lat;
if (SimpleUnit.isDateUnit(unit)) {
return AxisType.Time;
}
// look for other z coordinate
if (SimpleUnit.isCompatible("mbar", unit))
return AxisType.Pressure;
if (unit.equalsIgnoreCase("level") || unit.equalsIgnoreCase("layer") || unit.equalsIgnoreCase("sigma_level"))
return AxisType.GeoZ;
String positive = ncDataset.findAttValueIgnoreCase((Variable) v, CF.POSITIVE, null);
if (positive != null) {
if (SimpleUnit.isCompatible("m", unit))
return AxisType.Height;
else
return AxisType.GeoZ;
}
// a bad idea, but CDC SST relies on it :
// :Source = "NOAA/National Climatic Data Center";
// :Contact = "Dick Reynolds, email: Richard.W.Reynolds@noaa.gov & Chunying Liu, email: Chunying.liu@noaa.gov";
//:netcdf_Convention = "COARDS";
// if (checkForMeter && SimpleUnit.isCompatible("m", unit))
// return AxisType.Height;
return null;
} | java | {
"resource": ""
} |
q175029 | Grib1WmoTimeType.getStatType | test | @Nullable
public static GribStatType getStatType(int timeRangeIndicator) {
switch (timeRangeIndicator) {
case 3:
case 6:
case 7:
case 51:
case 113:
case 115:
case 117:
case 120:
case 123:
return GribStatType.Average;
case 4:
case 114:
case 116:
case 124:
return GribStatType.Accumulation;
case 5:
return GribStatType.DifferenceFromEnd;
case 118:
return GribStatType.Covariance;
case 119:
case 125:
return GribStatType.StandardDeviation;
default:
return null;
}
} | java | {
"resource": ""
} |
q175030 | HorizCoordSys.subsetLon | test | private Optional<CoverageCoordAxis> subsetLon(LatLonRect llbb, int stride) throws InvalidRangeException {
double wantMin = LatLonPointImpl.lonNormalFrom(llbb.getLonMin(), lonAxis.getStartValue());
double wantMax = LatLonPointImpl.lonNormalFrom(llbb.getLonMax(), lonAxis.getStartValue());
double start = lonAxis.getStartValue();
double end = lonAxis.getEndValue();
// use MAMath.MinMax as a container for two values, min and max
List<MAMath.MinMax> lonIntvs = subsetLonIntervals(wantMin, wantMax, start, end);
if (lonIntvs.size() == 0)
return Optional.empty(String.format(
"longitude want [%f,%f] does not intersect lon axis [%f,%f]", wantMin, wantMax, start, end));
if (lonIntvs.size() == 1) {
MAMath.MinMax lonIntv = lonIntvs.get(0);
return lonAxis.subset(lonIntv.min, lonIntv.max, stride);
}
// this is the seam crossing case
return lonAxis.subsetByIntervals(lonIntvs, stride);
} | java | {
"resource": ""
} |
q175031 | HorizCoordSys.getRanges | test | public List<RangeIterator> getRanges() {
List<RangeIterator> result = new ArrayList<>();
result.add(getYAxis().getRange());
RangeIterator lonRange = getXAxis().getRangeIterator();
if (lonRange == null) lonRange = getXAxis().getRange(); // clumsy
result.add(lonRange);
return result;
} | java | {
"resource": ""
} |
q175032 | HTTPSession.setDefaults | test | static synchronized protected void setDefaults(Map<Prop, Object> props)
{
if(false) {// turn off for now
props.put(Prop.HANDLE_AUTHENTICATION, Boolean.TRUE);
}
props.put(Prop.HANDLE_REDIRECTS, Boolean.TRUE);
props.put(Prop.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
props.put(Prop.MAX_REDIRECTS, (Integer) DFALTREDIRECTS);
props.put(Prop.SO_TIMEOUT, (Integer) DFALTSOTIMEOUT);
props.put(Prop.CONN_TIMEOUT, (Integer) DFALTCONNTIMEOUT);
props.put(Prop.CONN_REQ_TIMEOUT, (Integer) DFALTCONNREQTIMEOUT);
props.put(Prop.USER_AGENT, DFALTUSERAGENT);
} | java | {
"resource": ""
} |
q175033 | HTTPSession.getSessionID | test | public String getSessionID()
{
String sid = null;
String jsid = null;
List<Cookie> cookies = this.sessioncontext.getCookieStore().getCookies();
for(Cookie cookie : cookies) {
if(cookie.getName().equalsIgnoreCase("sessionid"))
sid = cookie.getValue();
if(cookie.getName().equalsIgnoreCase("jsessionid"))
jsid = cookie.getValue();
}
return (sid == null ? jsid : sid);
} | java | {
"resource": ""
} |
q175034 | HTTPSession.setMaxRedirects | test | public HTTPSession setMaxRedirects(int n)
{
if(n < 0) //validate
throw new IllegalArgumentException("setMaxRedirects");
localsettings.put(Prop.MAX_REDIRECTS, n);
this.cachevalid = false;
return this;
} | java | {
"resource": ""
} |
q175035 | HTTPSession.setUseSessions | test | public HTTPSession setUseSessions(boolean tf)
{
localsettings.put(Prop.USESESSIONS, (Boolean) tf);
this.cachevalid = false;
return this;
} | java | {
"resource": ""
} |
q175036 | HTTPSession.close | test | synchronized public void close()
{
if(this.closed)
return; // multiple calls ok
closed = true;
for(HTTPMethod m : this.methods) {
m.close(); // forcibly close; will invoke removemethod().
}
methods.clear();
} | java | {
"resource": ""
} |
q175037 | HTTPSession.setAuthenticationAndProxy | test | synchronized
protected void
setAuthenticationAndProxy(HttpClientBuilder cb)
throws HTTPException
{
// First, setup the ssl factory
cb.setSSLSocketFactory((SSLConnectionSocketFactory) authcontrols.get(AuthProp.SSLFACTORY));
// Second, Construct a CredentialsProvider that is
// the union of the Proxy credentials plus
// either the global or local credentials; local overrides global
// Unfortunately, we cannot either clone or extract the contents
// of the client supplied provider, so we are forced (for now)
// to modify the client supplied provider.
// Look in the local credentials first for for best scope match
AuthScope bestMatch = HTTPAuthUtil.bestmatch(scope, localcreds.keySet());
CredentialsProvider cp = null;
if(bestMatch != null) {
cp = localcreds.get(bestMatch);
} else {
bestMatch = HTTPAuthUtil.bestmatch(scope, globalcredfactories.keySet());
if(bestMatch != null) {
HTTPProviderFactory factory = globalcredfactories.get(bestMatch);
cp = factory.getProvider(bestMatch);
}
}
// Build the proxy credentials and AuthScope
Credentials proxycreds = null;
AuthScope proxyscope = null;
String user = (String) authcontrols.get(AuthProp.PROXYUSER);
String pwd = (String) authcontrols.get(AuthProp.PROXYPWD);
HttpHost httpproxy = (HttpHost) authcontrols.get(AuthProp.HTTPPROXY);
HttpHost httpsproxy = (HttpHost) authcontrols.get(AuthProp.HTTPSPROXY);
if(user != null && (httpproxy != null || httpsproxy != null)) {
if(httpproxy != null)
proxyscope = HTTPAuthUtil.hostToAuthScope(httpproxy);
else //httpsproxy != null
proxyscope = HTTPAuthUtil.hostToAuthScope(httpsproxy);
proxycreds = new UsernamePasswordCredentials(user, pwd);
}
if(cp == null && proxycreds != null && proxyscope != null) {
// If client provider is null and proxycreds are not,
// then use proxycreds alone
cp = new BasicCredentialsProvider();
cp.setCredentials(proxyscope, proxycreds);
} else if(cp != null && proxycreds != null && proxyscope != null) {
// If client provider is not null and proxycreds are not,
// then add proxycreds to the client provider
cp.setCredentials(proxyscope, proxycreds);
}
if(cp != null)
this.sessioncontext.setCredentialsProvider(cp);
} | java | {
"resource": ""
} |
q175038 | HTTPSession.track | test | static protected synchronized void track(HTTPSession session)
{
if(!TESTING) throw new UnsupportedOperationException();
if(sessionList == null)
sessionList = new ConcurrentSkipListSet<HTTPSession>();
sessionList.add(session);
} | java | {
"resource": ""
} |
q175039 | HTTPSession.setGlobalCredentialsProvider | test | @Deprecated
static public void
setGlobalCredentialsProvider(AuthScope scope, CredentialsProvider provider)
throws HTTPException
{
setGlobalCredentialsProvider(provider, scope);
} | java | {
"resource": ""
} |
q175040 | TextGetPutPane.validate | test | void validate(String urlString) {
if (urlString == null) return;
URI uri;
try {
uri = new URI(urlString);
}
catch (URISyntaxException e) {
javax.swing.JOptionPane.showMessageDialog(null, "URISyntaxException on URL (" +
urlString + ") " + e.getMessage() + "\n");
return;
}
String contents = getText();
//boolean isCatalog = contents.indexOf("queryCapability") < 0;
ByteArrayInputStream is = new ByteArrayInputStream(contents.getBytes(CDM.utf8Charset));
try {
CatalogBuilder catFactory = new CatalogBuilder();
Catalog cat = catFactory.buildFromLocation(urlString, null);
boolean isValid = !catFactory.hasFatalError();
javax.swing.JOptionPane.showMessageDialog(this,
"Catalog Validation = " + isValid + "\n" + catFactory.getErrorMessage());
} catch (IOException e) {
e.printStackTrace();
}
} | java | {
"resource": ""
} |
q175041 | Index.factory | test | static public Index factory(int[] shape) {
int rank = shape.length;
switch (rank) {
case 0:
return new Index0D();
case 1:
return new Index1D(shape);
case 2:
return new Index2D(shape);
case 3:
return new Index3D(shape);
case 4:
return new Index4D(shape);
case 5:
return new Index5D(shape);
case 6:
return new Index6D(shape);
case 7:
return new Index7D(shape);
default:
return new Index(shape);
}
} | java | {
"resource": ""
} |
q175042 | Index.computeStrides | test | static private long computeStrides(int[] shape, int[] stride) {
long product = 1;
for (int ii = shape.length - 1; ii >= 0; ii--) {
final int thisDim = shape[ii];
if (thisDim < 0)
continue; // ignore vlen
stride[ii] = (int) product;
product *= thisDim;
}
return product;
} | java | {
"resource": ""
} |
q175043 | Index.section | test | Index section(List<Range> ranges) throws InvalidRangeException {
// check ranges are valid
if (ranges.size() != rank)
throw new InvalidRangeException("Bad ranges [] length");
for (int ii = 0; ii < rank; ii++) {
Range r = ranges.get(ii);
if (r == null)
continue;
if (r == Range.VLEN)
continue;
if ((r.first() < 0) || (r.first() >= shape[ii]))
throw new InvalidRangeException("Bad range starting value at index " + ii + " == " + r.first());
if ((r.last() < 0) || (r.last() >= shape[ii]))
throw new InvalidRangeException("Bad range ending value at index " + ii + " == " + r.last());
}
int reducedRank = rank;
for (Range r : ranges) {
if ((r != null) && (r.length() == 1))
reducedRank--;
}
Index newindex = Index.factory(reducedRank);
newindex.offset = offset;
// calc shape, size, and index transformations
// calc strides into original (backing) store
int newDim = 0;
for (int ii = 0; ii < rank; ii++) {
Range r = ranges.get(ii);
if (r == null) { // null range means use the whole original dimension
newindex.shape[newDim] = shape[ii];
newindex.stride[newDim] = stride[ii];
//if (name != null) newindex.name[newDim] = name[ii];
newDim++;
} else if (r.length() != 1) {
newindex.shape[newDim] = r.length();
newindex.stride[newDim] = stride[ii] * r.stride();
newindex.offset += stride[ii] * r.first();
//if (name != null) newindex.name[newDim] = name[ii];
newDim++;
} else {
newindex.offset += stride[ii] * r.first(); // constant due to rank reduction
}
}
newindex.size = computeSize(newindex.shape);
newindex.fastIterator = fastIterator && (newindex.size == size); // if equal, then its not a real subset, so can still use fastIterator
newindex.precalc(); // any subclass-specific optimizations
return newindex;
} | java | {
"resource": ""
} |
q175044 | Index.reduce | test | Index reduce() {
Index c = this;
for (int ii = 0; ii < rank; ii++)
if (shape[ii] == 1) { // do this on the first one you find
Index newc = c.reduce(ii);
return newc.reduce(); // any more to do?
}
return c;
} | java | {
"resource": ""
} |
q175045 | Index.reduce | test | Index reduce(int dim) {
if ((dim < 0) || (dim >= rank))
throw new IllegalArgumentException("illegal reduce dim " + dim);
if (shape[dim] != 1)
throw new IllegalArgumentException("illegal reduce dim " + dim + " : length != 1");
Index newindex = Index.factory(rank - 1);
newindex.offset = offset;
int count = 0;
for (int ii = 0; ii < rank; ii++) {
if (ii != dim) {
newindex.shape[count] = shape[ii];
newindex.stride[count] = stride[ii];
//if (name != null) newindex.name[count] = name[ii];
count++;
}
}
newindex.size = computeSize(newindex.shape);
newindex.fastIterator = fastIterator;
newindex.precalc(); // any subclass-specific optimizations
return newindex;
} | java | {
"resource": ""
} |
q175046 | Index.transpose | test | Index transpose(int index1, int index2) {
if ((index1 < 0) || (index1 >= rank))
throw new IllegalArgumentException();
if ((index2 < 0) || (index2 >= rank))
throw new IllegalArgumentException();
Index newIndex = (Index) this.clone();
newIndex.stride[index1] = stride[index2];
newIndex.stride[index2] = stride[index1];
newIndex.shape[index1] = shape[index2];
newIndex.shape[index2] = shape[index1];
/* if (name != null) {
newIndex.name[index1] = name[index2];
newIndex.name[index2] = name[index1];
} */
newIndex.fastIterator = false;
newIndex.precalc(); // any subclass-specific optimizations
return newIndex;
} | java | {
"resource": ""
} |
q175047 | Index.permute | test | Index permute(int[] dims) {
if (dims.length != shape.length)
throw new IllegalArgumentException();
for (int dim : dims)
if ((dim < 0) || (dim >= rank))
throw new IllegalArgumentException();
boolean isPermuted = false;
Index newIndex = (Index) this.clone();
for (int i = 0; i < dims.length; i++) {
newIndex.stride[i] = stride[dims[i]];
newIndex.shape[i] = shape[dims[i]];
//if (name != null) newIndex.name[i] = name[dims[i]];
if (i != dims[i]) isPermuted = true;
}
newIndex.fastIterator = fastIterator && !isPermuted; // useful optimization
newIndex.precalc(); // any subclass-specific optimizations
return newIndex;
} | java | {
"resource": ""
} |
q175048 | Index.getIndexIterator | test | IndexIterator getIndexIterator(Array maa) {
if (fastIterator)
return new IteratorFast(size, maa);
else
return new IteratorImpl(maa);
} | java | {
"resource": ""
} |
q175049 | Index.currentElement | test | public int currentElement() {
int value = offset; // NB: dont have to check each index again
for (int ii = 0; ii < rank; ii++) { // general rank
if (shape[ii] < 0) break;//vlen
value += current[ii] * stride[ii];
}
return value;
} | java | {
"resource": ""
} |
q175050 | Index.set | test | public Index set(int[] index) {
if (index.length != rank)
throw new ArrayIndexOutOfBoundsException();
if (rank == 0) return this;
int prefixrank = (hasvlen ? rank : rank - 1);
System.arraycopy(index, 0, current, 0, prefixrank);
if (hasvlen) current[prefixrank] = -1;
return this;
} | java | {
"resource": ""
} |
q175051 | Index.setDim | test | public void setDim(int dim, int value) {
if (value < 0 || value >= shape[dim]) // check index here
throw new ArrayIndexOutOfBoundsException();
if (shape[dim] >= 0) //!vlen
current[dim] = value;
} | java | {
"resource": ""
} |
q175052 | Index.set | test | public Index set(int v0, int v1, int v2) {
setDim(0, v0);
setDim(1, v1);
setDim(2, v2);
return this;
} | java | {
"resource": ""
} |
q175053 | CoordinateTimeIntv.getTimeIntervalName | test | public String getTimeIntervalName() {
// are they the same length ?
int firstValue = -1;
for (TimeCoordIntvValue tinv : timeIntervals) {
int value = (tinv.getBounds2() - tinv.getBounds1());
if (firstValue < 0) firstValue = value;
else if (value != firstValue) return MIXED_INTERVALS;
}
firstValue = (firstValue * timeUnit.getValue());
return firstValue + "_" + timeUnit.getField().toString();
} | java | {
"resource": ""
} |
q175054 | CoordinateTimeIntv.makeCalendarDateRange | test | @Override
public CalendarDateRange makeCalendarDateRange(ucar.nc2.time.Calendar cal) {
CalendarDateUnit cdu = CalendarDateUnit.of(cal, timeUnit.getField(), refDate);
CalendarDate start = cdu.makeCalendarDate( timeUnit.getValue() * timeIntervals.get(0).getBounds2());
CalendarDate end = cdu.makeCalendarDate(timeUnit.getValue() * timeIntervals.get(getSize()-1).getBounds2());
return CalendarDateRange.of(start, end);
} | java | {
"resource": ""
} |
q175055 | AbstractGempakStationFileReader.makeDateList | test | protected List<String> makeDateList(boolean unique) {
Key date = dateTimeKeys.get(0);
Key time = dateTimeKeys.get(1);
List<int[]> toCheck;
if (date.type.equals(ROW)) {
toCheck = headers.rowHeaders;
} else {
toCheck = headers.colHeaders;
}
List<String> fileDates = new ArrayList<>();
for (int[] header : toCheck) {
if (header[0] != IMISSD) {
// convert to GEMPAK date/time
int idate = header[date.loc + 1];
int itime = header[time.loc + 1];
// TODO: Add in the century
String dateTime = GempakUtil.TI_CDTM(idate, itime);
fileDates.add(dateTime);
}
}
if (unique && !fileDates.isEmpty()) {
SortedSet<String> uniqueTimes =
Collections.synchronizedSortedSet(new TreeSet<String>());
uniqueTimes.addAll(fileDates);
fileDates.clear();
fileDates.addAll(uniqueTimes);
}
return fileDates;
} | java | {
"resource": ""
} |
q175056 | AbstractGempakStationFileReader.makeParams | test | private List<GempakParameter> makeParams(DMPart part) {
List<GempakParameter> gemparms = new ArrayList<>(part.kparms);
for (DMParam param : part.params) {
String name = param.kprmnm;
GempakParameter parm = GempakParameters.getParameter(name);
if (parm == null) {
//System.out.println("couldn't find " + name
// + " in params table");
parm = new GempakParameter(1, name, name, "", 0);
}
gemparms.add(parm);
}
return gemparms;
} | java | {
"resource": ""
} |
q175057 | AbstractGempakStationFileReader.getStationList | test | private List<GempakStation> getStationList() {
Key slat = findKey(GempakStation.SLAT);
if (slat == null) {
return null;
}
List<int[]> toCheck;
if (slat.type.equals(ROW)) {
toCheck = headers.rowHeaders;
} else {
toCheck = headers.colHeaders;
}
List<GempakStation> fileStations = new ArrayList<>();
int i = 0;
for (int[] header : toCheck) {
if (header[0] != IMISSD) {
GempakStation station = makeStation(header);
if (station != null) {
station.setIndex(i + 1);
fileStations.add(station);
}
}
i++;
}
return fileStations;
} | java | {
"resource": ""
} |
q175058 | AbstractGempakStationFileReader.makeStation | test | private GempakStation makeStation(int[] header) {
if ((stationKeys == null) || stationKeys.isEmpty()) {
return null;
}
GempakStation newStation = new GempakStation();
for (Key key : stationKeys) {
int loc = key.loc + 1;
switch (key.name) {
case GempakStation.STID:
newStation.setSTID(GempakUtil.ST_ITOC(header[loc]).trim());
break;
case GempakStation.STNM:
newStation.setSTNM(header[loc]);
break;
case GempakStation.SLAT:
newStation.setSLAT(header[loc]);
break;
case GempakStation.SLON:
newStation.setSLON(header[loc]);
break;
case GempakStation.SELV:
newStation.setSELV(header[loc]);
break;
case GempakStation.SPRI:
newStation.setSPRI(header[loc]);
break;
case GempakStation.STAT:
newStation.setSTAT(GempakUtil.ST_ITOC(header[loc]).trim());
break;
case GempakStation.COUN:
newStation.setCOUN(GempakUtil.ST_ITOC(header[loc]).trim());
break;
case GempakStation.SWFO:
newStation.setSWFO(GempakUtil.ST_ITOC(header[loc]).trim());
break;
case GempakStation.WFO2:
newStation.setWFO2(GempakUtil.ST_ITOC(header[loc]).trim());
break;
case GempakStation.STD2:
newStation.setSTD2(GempakUtil.ST_ITOC(header[loc]).trim());
break;
}
}
return newStation;
} | java | {
"resource": ""
} |
q175059 | AbstractGempakStationFileReader.getStationKeyNames | test | public List<String> getStationKeyNames() {
List<String> keys = new ArrayList<>();
if ((stationKeys != null) && !stationKeys.isEmpty()) {
for (Key key : stationKeys) {
keys.add(key.name);
}
}
return keys;
} | java | {
"resource": ""
} |
q175060 | AbstractGempakStationFileReader.getDates | test | public List<Date> getDates() {
if ((dates == null || dates.isEmpty()) && !dateList.isEmpty()) {
dates = new ArrayList<>(dateList.size());
dateFmt.setTimeZone(TimeZone.getTimeZone("GMT"));
for (String dateString : dateList) {
Date d = dateFmt.parse(dateString, new ParsePosition(0));
//DateFromString.getDateUsingSimpleDateFormat(dateString,
// DATE_FORMAT);
dates.add(d);
}
}
return dates;
} | java | {
"resource": ""
} |
q175061 | AbstractGempakStationFileReader.findStationIndex | test | public int findStationIndex(String id) {
for (GempakStation station : getStations()) {
if (station.getSTID().equals(id)) {
return station.getIndex();
}
}
return -1;
} | java | {
"resource": ""
} |
q175062 | AbstractGempakStationFileReader.getFileType | test | public String getFileType() {
String type = "Unknown";
switch (dmLabel.kftype) {
case MFSN:
type = "Sounding";
break;
case MFSF:
type = "Surface";
break;
default:
}
if (!subType.equals("")) {
type = type + " (" + subType + ")";
}
return type;
} | java | {
"resource": ""
} |
q175063 | IndentWriter.indent | test | public void indent(int n)
{
depth += n;
if(depth < 0)
depth = 0;
else if(depth > MAXDEPTH)
depth = MAXDEPTH;
} | java | {
"resource": ""
} |
q175064 | IndentWriter.setIndent | test | public void setIndent(int n)
{
depth = n;
if(depth < 0)
depth = 0;
else if(depth > MAXDEPTH)
depth = MAXDEPTH;
} | java | {
"resource": ""
} |
q175065 | GribIndex.readOrCreateIndexFromSingleFile | test | public static GribIndex readOrCreateIndexFromSingleFile(boolean isGrib1, MFile mfile, CollectionUpdateType force, org.slf4j.Logger logger) throws IOException {
GribIndex index = isGrib1 ? new Grib1Index() : new Grib2Index();
if (!index.readIndex(mfile.getPath(), mfile.getLastModified(), force)) { // heres where the index date is checked against the data file
index.makeIndex(mfile.getPath(), null);
logger.debug(" Index written: {} == {} records", mfile.getName() + GBX9_IDX, index.getNRecords());
} else if (debug) {
logger.debug(" Index read: {} == {} records", mfile.getName() + GBX9_IDX, index.getNRecords());
}
return index;
} | java | {
"resource": ""
} |
q175066 | MFileCollectionManager.addDirectoryScan | test | public void addDirectoryScan(String dirName, String suffix, String regexpPatternString, String subdirsS, String olderS, Object auxInfo) {
CompositeMFileFilter filters = new CompositeMFileFilter();
if (null != regexpPatternString)
filters.addIncludeFilter(new RegExpMatchOnName(regexpPatternString));
else if (suffix != null)
filters.addIncludeFilter(new WildcardMatchOnPath("*" + suffix + "$"));
if (olderS != null) {
try {
TimeDuration tu = new TimeDuration(olderS);
filters.addAndFilter(new LastModifiedLimit((long) (1000 * tu.getValueInSeconds())));
} catch (Exception e) {
logger.error(collectionName + ": Invalid time unit for olderThan = {}", olderS);
}
}
boolean wantSubdirs = true;
if ((subdirsS != null) && subdirsS.equalsIgnoreCase("false"))
wantSubdirs = false;
CollectionConfig mc = new CollectionConfig(dirName, dirName, wantSubdirs, filters, auxInfo);
// create name
StringBuilder sb = new StringBuilder(dirName);
if (wantSubdirs)
sb.append("**/");
if (null != regexpPatternString)
sb.append(regexpPatternString);
else if (suffix != null)
sb.append(suffix);
else
sb.append("noFilter");
collectionName = sb.toString();
scanList.add(mc);
} | java | {
"resource": ""
} |
q175067 | MFileCollectionManager.isScanNeeded | test | @Override
public boolean isScanNeeded() {
// see if we need to recheck
if (recheck == null) {
logger.debug("{}: scan not needed, recheck null", collectionName);
return false;
}
if (!hasScans()) {
logger.debug("{}: scan not needed, no scanners", collectionName);
return false;
}
synchronized (this) {
if (map == null && !isStatic()) {
logger.debug("{}: scan needed, never scanned", collectionName);
return true;
}
}
Date now = new Date();
Date lastCheckedDate = new Date(getLastScanned());
Date need = recheck.add(lastCheckedDate);
if (now.before(need)) {
logger.debug("{}: scan not needed, last scanned={}, now={}", collectionName, lastCheckedDate, now);
return false;
}
return true;
} | java | {
"resource": ""
} |
q175068 | MFileCollectionManager.scanFirstTime | test | private boolean scanFirstTime() throws IOException {
Map<String, MFile> newMap = new HashMap<>();
if (!hasScans()) {
map = newMap;
return false;
}
reallyScan(newMap);
// deleteOld(newMap); // ?? hmmmmm LOOK this seems wrong; maintainence in background ?? generally collection doesnt exist
// implement olderThan
if (olderThanInMsecs > 0) {
long olderThan = System.currentTimeMillis() - olderThanInMsecs; // new files must be older than this.
Iterator<MFile> iter = newMap.values().iterator(); // need iterator so we can remove()
while (iter.hasNext()) {
MFile newFile = iter.next();
String path = newFile.getPath();
if (newFile.getLastModified() > olderThan) { // the file is too new
iter.remove();
logger.debug("{}: scan found new Dataset but its too recently modified = {}", collectionName, path);
}
}
}
map = newMap;
this.lastScanned = System.currentTimeMillis();
this.lastChanged.set(this.lastScanned);
logger.debug("{} : initial scan found n datasets = {} ", collectionName, map.keySet().size());
return map.keySet().size() > 0;
} | java | {
"resource": ""
} |
q175069 | FileWriter2.setDebugFlags | test | public static void setDebugFlags(ucar.nc2.util.DebugFlags debugFlags) {
debug = debugFlags.isSet("ncfileWriter2/debug");
debugWrite = debugFlags.isSet("ncfileWriter2/debugWrite");
debugChunk = debugFlags.isSet("ncfileWriter2/debugChunk");
} | java | {
"resource": ""
} |
q175070 | FileWriter2.addVariable | test | public Variable addVariable(Variable oldVar) {
List<Dimension> newDims = getNewDimensions(oldVar);
Variable newVar;
if ((oldVar.getDataType().equals(DataType.STRING)) && (!version.isExtendedModel())) {
newVar = writer.addStringVariable(null, oldVar, newDims);
} else {
newVar = writer.addVariable(null, oldVar.getShortName(), oldVar.getDataType(), newDims);
}
varMap.put(oldVar, newVar);
varList.add(oldVar);
for (Attribute orgAtt : oldVar.getAttributes())
writer.addVariableAttribute(newVar, convertAttribute(orgAtt));
return newVar;
} | java | {
"resource": ""
} |
q175071 | FileWriter2.write | test | public NetcdfFile write(CancelTask cancel) throws IOException {
try {
if (version.isExtendedModel())
addGroupExtended(null, fileIn.getRootGroup());
else
addGroupClassic();
if (cancel != null && cancel.isCancel()) return null;
// create the file
writer.create();
if (cancel != null && cancel.isCancel()) return null;
double total = copyVarData(varList, null, cancel);
if (cancel != null && cancel.isCancel()) return null;
writer.flush();
if (debug) System.out.println("FileWriter done total bytes = " + total);
} catch (IOException ioe) {
ioe.printStackTrace();
writer.abort(); // clean up
throw ioe;
}
return writer.getNetcdfFile();
} | java | {
"resource": ""
} |
q175072 | MarshallingUtil.validate | test | public static void validate(XmlObject doc, boolean strict) throws XmlException {
// Create an XmlOptions instance and set the error listener.
Set<XmlError> validationErrors = new HashSet<>();
XmlOptions validationOptions = new XmlOptions();
validationOptions.setErrorListener(validationErrors);
// Validate the XML document
final boolean isValid = doc.validate(validationOptions);
// Create Exception with error message if the xml document is invalid
if (!isValid && !strict) {
// check if we have special validation cases which could let the message pass anyhow
validationErrors = filterToOnlySerious(validationErrors);
}
if (!validationErrors.isEmpty()) {
throw new XmlException(createErrorMessage(validationErrors));
}
} | java | {
"resource": ""
} |
q175073 | MultiSlice.toConstraintString | test | @Override
public String toConstraintString()
throws DapException
{
assert this.first != UNDEFINED && this.stride != UNDEFINED && this.stop != UNDEFINED;
StringBuilder buf = new StringBuilder();
buf.append("[");
boolean first = true;
for(Slice sub: this.subslices) {
if(!first) buf.append(",");
first = false;
if((sub.stop - sub.first) == 0) {
buf.append("0");
} else if(sub.stride == 1) {
if((sub.stop - sub.first) == 1)
buf.append(sub.first);
else
buf.append(String.format("%d:%d", sub.first, sub.stop - 1));
} else
buf.append(String.format("%d:%d:%d", sub.first, sub.stride, sub.stop - 1));
}
buf.append("]");
return buf.toString();
} | java | {
"resource": ""
} |
q175074 | StructureDS.setOriginalVariable | test | public void setOriginalVariable(ucar.nc2.Variable orgVar) {
if (!(orgVar instanceof Structure))
throw new IllegalArgumentException("StructureDS must wrap a Structure; name=" + orgVar.getFullName());
this.orgVar = (Structure) orgVar;
} | java | {
"resource": ""
} |
q175075 | StructureDS.reallyRead | test | @Override
public Array reallyRead(Variable client, CancelTask cancelTask) throws IOException {
Array result;
if (hasCachedData())
result = super.reallyRead(client, cancelTask);
else if (orgVar != null)
result = orgVar.read();
else {
throw new IllegalStateException("StructureDS has no way to get data");
//Object data = smProxy.getFillValue(getDataType());
//return Array.factoryConstant(dataType.getPrimitiveClassType(), getShape(), data);
}
return convert(result, null);
} | java | {
"resource": ""
} |
q175076 | StructureDS.reallyRead | test | @Override
public Array reallyRead(Variable client, Section section, CancelTask cancelTask) throws IOException, InvalidRangeException {
if (section.computeSize() == getSize())
return _read();
Array result;
if (hasCachedData())
result = super.reallyRead(client, section, cancelTask);
else if (orgVar != null)
result = orgVar.read(section);
else {
throw new IllegalStateException("StructureDS has no way to get data");
//Object data = smProxy.getFillValue(getDataType());
//return Array.factoryConstant(dataType.getPrimitiveClassType(), section.getShape(), data);
}
// do any needed conversions (enum/scale/offset/missing/unsigned, etc)
return convert(result, section);
} | java | {
"resource": ""
} |
q175077 | StructureDS.convertNeeded | test | private boolean convertNeeded(StructureMembers smData) {
for (Variable v : getVariables()) {
if (v instanceof VariableDS) {
VariableDS vds = (VariableDS) v;
if (vds.needConvert())
return true;
} else if (v instanceof StructureDS) {
StructureDS nested = (StructureDS) v;
if (nested.convertNeeded(null))
return true;
}
// a variable with no data in the underlying smData
if ((smData != null) && !varHasData(v, smData))
return true;
}
return false;
} | java | {
"resource": ""
} |
q175078 | StructureDS.convert | test | protected ArrayStructure convert(Array data, Section section) throws IOException {
ArrayStructure orgAS = (ArrayStructure) data;
if (!convertNeeded(orgAS.getStructureMembers())) {
// name, info change only
convertMemberInfo(orgAS.getStructureMembers());
return orgAS;
}
// LOOK! converting to ArrayStructureMA
// do any enum/scale/offset/missing/unsigned conversions
ArrayStructure newAS = ArrayStructureMA.factoryMA(orgAS);
for (StructureMembers.Member m : newAS.getMembers()) {
VariableEnhanced v2 = (VariableEnhanced) findVariable(m.getName());
if ((v2 == null) && (orgVar != null)) // these are from orgVar - may have been renamed
v2 = findVariableFromOrgName(m.getName());
if (v2 == null) continue;
if (v2 instanceof VariableDS) {
VariableDS vds = (VariableDS) v2;
if (vds.needConvert()) {
Array mdata = newAS.extractMemberArray(m);
// mdata has not yet been enhanced, but vds would *think* that it has been if we used the 1-arg version of
// VariableDS.convert(). So, we use the 2-arg version to explicitly request enhancement.
mdata = vds.convert(mdata, vds.getEnhanceMode());
newAS.setMemberArray(m, mdata);
}
} else if (v2 instanceof StructureDS) {
StructureDS innerStruct = (StructureDS) v2;
if (innerStruct.convertNeeded(null)) {
if (innerStruct.getDataType() == DataType.SEQUENCE) {
ArrayObject.D1 seqArray = (ArrayObject.D1) newAS.extractMemberArray(m);
ArrayObject.D1 newSeq = (ArrayObject.D1) Array.factory(DataType.SEQUENCE, new int[] {(int) seqArray.getSize()});
m.setDataArray(newSeq); // put back into member array
// wrap each Sequence
for (int i = 0; i < seqArray.getSize(); i++) {
ArraySequence innerSeq = (ArraySequence) seqArray.get(i); // get old ArraySequence
newSeq.set(i, new SequenceConverter(innerStruct, innerSeq)); // wrap in converter
}
// non-Sequence Structures
} else {
Array mdata = newAS.extractMemberArray(m);
mdata = innerStruct.convert(mdata, null);
newAS.setMemberArray(m, mdata);
}
}
// always convert the inner StructureMembers
innerStruct.convertMemberInfo(m.getStructureMembers());
}
}
StructureMembers sm = newAS.getStructureMembers();
convertMemberInfo(sm);
// check for variables that have been added by NcML
for (Variable v : getVariables()) {
if (!varHasData(v, sm)) {
try {
Variable completeVar = getParentGroup().findVariable(v.getShortName()); // LOOK BAD
Array mdata = completeVar.read(section);
StructureMembers.Member m = sm.addMember(v.getShortName(), v.getDescription(), v.getUnitsString(), v.getDataType(), v.getShape());
newAS.setMemberArray(m, mdata);
} catch (InvalidRangeException e) {
throw new IOException(e.getMessage());
}
}
}
return newAS;
} | java | {
"resource": ""
} |
q175079 | StructureDS.convertMemberInfo | test | private void convertMemberInfo(StructureMembers wrapperSm) {
for (StructureMembers.Member m : wrapperSm.getMembers()) {
Variable v = findVariable(m.getName());
if ((v == null) && (orgVar != null)) // may have been renamed
v = (Variable) findVariableFromOrgName(m.getName());
if (v != null) { // a section will have missing variables LOOK wrapperSm probably wrong in that case
// log.error("Cant find " + m.getName());
//else
m.setVariableInfo(v.getShortName(), v.getDescription(), v.getUnitsString(), v.getDataType());
}
// nested structures
if (v instanceof StructureDS) {
StructureDS innerStruct = (StructureDS) v;
innerStruct.convertMemberInfo(m.getStructureMembers());
}
}
} | java | {
"resource": ""
} |
q175080 | StructureDS.findVariableFromOrgName | test | private VariableEnhanced findVariableFromOrgName(String orgName) {
for (Variable vTop : getVariables()) {
Variable v = vTop;
while (v instanceof VariableEnhanced) {
VariableEnhanced ve = (VariableEnhanced) v;
if ((ve.getOriginalName() != null) && (ve.getOriginalName().equals(orgName)))
return (VariableEnhanced) vTop;
v = ve.getOriginalVariable();
}
}
return null;
} | java | {
"resource": ""
} |
q175081 | StructureDS.varHasData | test | private boolean varHasData(Variable v, StructureMembers sm) {
if (sm.findMember(v.getShortName()) != null) return true;
while (v instanceof VariableEnhanced) {
VariableEnhanced ve = (VariableEnhanced) v;
if (sm.findMember(ve.getOriginalName()) != null) return true;
v = ve.getOriginalVariable();
}
return false;
} | java | {
"resource": ""
} |
q175082 | StructureDS.enhance | test | public void enhance(Set<NetcdfDataset.Enhance> mode) {
for (Variable v : getVariables()) {
VariableEnhanced ve = (VariableEnhanced) v;
ve.enhance(mode);
}
} | java | {
"resource": ""
} |
q175083 | DatasetManager.resourceControlOk | test | public boolean resourceControlOk(HttpServletRequest req, HttpServletResponse res, String reqPath) {
if (null == reqPath)
reqPath = TdsPathUtils.extractPath(req, null);
// see if its under resource control
String rc = null;
DataRootManager.DataRootMatch match = dataRootManager.findDataRootMatch(reqPath);
if (match != null) {
rc = match.dataRoot.getRestrict(); // datasetScan, featCollection are restricted at the dataRoot
}
if (rc == null) {
rc = datasetTracker.findResourceControl(reqPath); // regular datasets tracked here
}
return resourceAuthorized(req, res, rc);
} | java | {
"resource": ""
} |
q175084 | GempakSoundingIOSP.makeEmptySequence | test | private ArraySequence makeEmptySequence(Sequence seq) {
StructureMembers members = seq.makeStructureMembers();
return new ArraySequence(members, new EmptyStructureDataIterator(), -1);
} | java | {
"resource": ""
} |
q175085 | GempakSoundingIOSP.makeArraySequence | test | private ArraySequence makeArraySequence(Sequence seq, List<GempakParameter> params, float[] values) {
if (values == null) {
return makeEmptySequence(seq);
}
int numLevels = values.length / params.size();
StructureMembers members = seq.makeStructureMembers();
int offset = ArrayStructureBB.setOffsets(members);
int size = offset * numLevels;
byte[] bytes = new byte[size];
ByteBuffer buf = ByteBuffer.wrap(bytes);
ArrayStructureBB abb = new ArrayStructureBB(members, new int[]{numLevels}, buf, 0);
int var = 0;
for (int i = 0; i < numLevels; i++) {
for (GempakParameter param : params) {
if (members.findMember(param.getName()) != null) {
buf.putFloat(values[var]);
}
var++;
}
}
return new ArraySequence(members, new SequenceIterator(numLevels, abb), numLevels);
} | java | {
"resource": ""
} |
q175086 | GempakSoundingIOSP.makeSequence | test | protected Sequence makeSequence(Structure parent, String partName, boolean includeMissing) {
List<GempakParameter> params = gemreader.getParameters(partName);
if (params == null) {
return null;
}
Sequence sVar = new Sequence(ncfile, null, parent, partName);
sVar.setDimensions("");
for (GempakParameter param : params) {
Variable v = makeParamVariable(param, null);
addVerticalCoordAttribute(v);
sVar.addMemberVariable(v);
}
if (includeMissing) {
sVar.addMemberVariable(makeMissingVariable());
}
return sVar;
} | java | {
"resource": ""
} |
q175087 | GempakSoundingIOSP.addVerticalCoordAttribute | test | private void addVerticalCoordAttribute(Variable v) {
GempakSoundingFileReader gsfr = (GempakSoundingFileReader) gemreader;
int vertType = gsfr.getVerticalCoordinate();
String pName = v.getFullName();
if (gemreader.getFileSubType().equals(GempakSoundingFileReader.MERGED)) {
if ((vertType == GempakSoundingFileReader.PRES_COORD) && pName.equals("PRES")) {
v.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Pressure.name()));
} else if ((vertType == GempakSoundingFileReader.HGHT_COORD) && (pName.equals("HGHT") || pName.equals("MHGT") || pName.equals("DHGT"))) {
v.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Height.name()));
}
} else if (pName.equals("PRES")) {
v.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Pressure.name()));
}
} | java | {
"resource": ""
} |
q175088 | InvCatalogFactory.readXMLasynch | test | public void readXMLasynch(String uriString, CatalogSetCallback callback) {
InvCatalogImpl cat = readXML(uriString);
callback.setCatalog(cat);
} | java | {
"resource": ""
} |
q175089 | InvCatalogFactory.readXML | test | public InvCatalogImpl readXML( String catAsString, URI baseUri )
{
return readXML( new StringReader( catAsString ), baseUri );
} | java | {
"resource": ""
} |
q175090 | InvCatalogFactory.readXML | test | public InvCatalogImpl readXML( StringReader catAsStringReader, URI baseUri )
{
XMLEntityResolver resolver = new XMLEntityResolver( false );
SAXBuilder builder = resolver.getSAXBuilder();
Document inDoc;
try
{
inDoc = builder.build( catAsStringReader );
}
catch ( Exception e )
{
InvCatalogImpl cat = new InvCatalogImpl( baseUri.toString(), null, null );
cat.appendErrorMessage( "**Fatal: InvCatalogFactory.readXML(String catAsString, URI url) failed:"
+ "\n Exception= " + e.getClass().getName() + " " + e.getMessage()
+ "\n fatalMessages= " + fatalMessages.toString()
+ "\n errMessages= " + errMessages.toString()
+ "\n warnMessages= " + warnMessages.toString() + "\n", true );
return cat;
}
return readXML( inDoc, baseUri );
} | java | {
"resource": ""
} |
q175091 | InvCatalogFactory.writeXML | test | public void writeXML(InvCatalogImpl catalog, OutputStream os, boolean raw) throws IOException {
InvCatalogConvertIF converter = this.getCatalogConverter(XMLEntityResolver.CATALOG_NAMESPACE_10);
converter.writeXML(catalog, os, raw);
} | java | {
"resource": ""
} |
q175092 | InvCatalogFactory.getMetadataConverter | test | public MetadataConverterIF getMetadataConverter(String key) {
if (key == null) return null;
return metadataConverters.get(key);
} | java | {
"resource": ""
} |
q175093 | DerivedUnitImpl.dimensionlessID | test | private static UnitName dimensionlessID() {
UnitName id;
try {
id = UnitName.newUnitName("1", "1", "1");
}
catch (final NameException e) {
id = null;
}
return id;
} | java | {
"resource": ""
} |
q175094 | DerivedUnitImpl.myMultiplyBy | test | @Override
protected Unit myMultiplyBy(final Unit that) throws MultiplyException {
Unit result;
if (dimension.getRank() == 0) {
result = that;
}
else {
if (!(that instanceof DerivedUnit)) {
result = that.multiplyBy(this);
}
else {
final UnitDimension thatDimension = ((DerivedUnit) that)
.getDimension();
result = thatDimension.getRank() == 0
? this
: new DerivedUnitImpl(dimension
.multiplyBy(thatDimension));
}
}
return result;
} | java | {
"resource": ""
} |
q175095 | DerivedUnitImpl.myDivideBy | test | @Override
protected Unit myDivideBy(final Unit that) throws OperationException {
Unit result;
if (dimension.getRank() == 0) {
result = that.raiseTo(-1);
}
else {
if (!(that instanceof DerivedUnit)) {
result = that.divideInto(this);
}
else {
final UnitDimension thatDimension = ((DerivedUnit) that)
.getDimension();
result = thatDimension.getRank() == 0
? this
: new DerivedUnitImpl(dimension.divideBy(thatDimension));
}
}
return result;
} | java | {
"resource": ""
} |
q175096 | DerivedUnitImpl.toDerivedUnit | test | public final float[] toDerivedUnit(final float[] input, final float[] output) {
if (input != output) {
System.arraycopy(input, 0, output, 0, input.length);
}
return output;
} | java | {
"resource": ""
} |
q175097 | DerivedUnitImpl.isCompatible | test | @Override
public final boolean isCompatible(final Unit that) {
final DerivedUnit unit = that.getDerivedUnit();
return equals(unit) || isReciprocalOf(unit);
} | java | {
"resource": ""
} |
q175098 | GMLFeatureWriter.writeFeature | test | public String writeFeature(SimpleGeometry geom) {
if (geom instanceof Point) return writePoint((Point)geom);
else if (geom instanceof Line) return writeLine((Line)geom);
else if (geom instanceof Polygon) return writePolygon((Polygon)geom);
else return null;
} | java | {
"resource": ""
} |
q175099 | GMLFeatureWriter.writePoint | test | private String writePoint(Point point) {
String xml = "";
xml += "<gml:Point srsName=\"http://www.opengis.net/gml/srs/epsg.xml@900913\" srsDimension=\"2\">"
+ "<gml:pos>" + point.getX() + " " + point.getY() +"</gml:pos>"
+ "</gml:Point>";
return xml;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.