_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q163200 | CredentialListMapping.fetcher | train | public static CredentialListMappingFetcher fetcher(final String pathAccountSid,
final String pathDomainSid,
final String pathSid) {
return new CredentialListMappingFetcher(pathAccountSid, pathDomainSid, pathSid);
} | java | {
"resource": ""
} |
q163201 | CredentialListMapping.deleter | train | public static CredentialListMappingDeleter deleter(final String pathAccountSid,
final String pathDomainSid,
final String pathSid) {
return new CredentialListMappingDeleter(pathAccountSid, pathDomainSid, pathSid);
} | java | {
"resource": ""
} |
q163202 | Webhook.fetcher | train | public static WebhookFetcher fetcher(final String pathServiceSid,
final String pathChannelSid,
final String pathSid) {
return new WebhookFetcher(pathServiceSid, pathChannelSid, pathSid);
} | java | {
"resource": ""
} |
q163203 | Webhook.updater | train | public static WebhookUpdater updater(final String pathServiceSid,
final String pathChannelSid,
final String pathSid) {
return new WebhookUpdater(pathServiceSid, pathChannelSid, pathSid);
} | java | {
"resource": ""
} |
q163204 | Webhook.deleter | train | public static WebhookDeleter deleter(final String pathServiceSid,
final String pathChannelSid,
final String pathSid) {
return new WebhookDeleter(pathServiceSid, pathChannelSid, pathSid);
} | java | {
"resource": ""
} |
q163205 | VoiceGrant.setOutgoingApplication | train | public VoiceGrant setOutgoingApplication(
String outgoingApplicationSid,
Map<String, Object> outgoingApplicationParams
) {
this.outgoingApplicationSid = outgoingApplicationSid;
this.outgoingApplicationParams = outgoingApplicationParams;
return this;
} | java | {
"resource": ""
} |
q163206 | MessageUpdater.update | train | @Override
@SuppressWarnings("checkstyle:linelength")
public Message update(final TwilioRestClient client) {
Request request = new Request(
HttpMethod.POST,
Domains.IPMESSAGING.toString(),
"/v1/Services/" + this.pathServiceSid + "/Channels/" + this.pathChannelSid + "/Messages/" + this.pathSid + "",
client.getRegion()
);
addPostParams(request);
Response response = client.request(request);
if (response == null) {
throw new ApiConnectionException("Message update failed: Unable to connect to server");
} else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) {
RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
if (restException == null) {
throw new ApiException("Server Error, no content");
}
throw new ApiException(
restException.getMessage(),
restException.getCode(),
restException.getMoreInfo(),
restException.getStatus(),
null
);
}
return Message.fromJson(response.getStream(), client.getObjectMapper());
} | java | {
"resource": ""
} |
q163207 | TwiMLResponseExample.main | train | public static void main(final String[] args) throws TwiMLException, URISyntaxException {
// Say
Say say = new Say.Builder("Hello World!")
.voice(Say.Voice.MAN)
.loop(5)
.build();
VoiceResponse response = new VoiceResponse.Builder()
.say(say)
.build();
System.out.println(response.toXml());
// Gather, Redirect
Gather gather = new Gather.Builder()
.numDigits(10)
.say(new Say.Builder("Press 1").build())
.build();
Redirect redirect = new Redirect.Builder(new URI("https://example.com")).build();
response = new VoiceResponse.Builder()
.gather(gather)
.redirect(redirect)
.build();
System.out.println(response.toXml());
// Conference
Conference conference = new Conference.Builder("my room")
.beep(Conference.Beep.TRUE)
.build();
Dial dial = new Dial.Builder()
.callerId("+1 (555) 555-5555")
.action(new URI("https:///example.com"))
.hangupOnStar(true)
.conference(conference)
.build();
response = new VoiceResponse.Builder()
.dial(dial)
.build();
System.out.println(response.toXml());
} | java | {
"resource": ""
} |
q163208 | Notification.fetcher | train | public static NotificationFetcher fetcher(final String pathAccountSid,
final String pathCallSid,
final String pathSid) {
return new NotificationFetcher(pathAccountSid, pathCallSid, pathSid);
} | java | {
"resource": ""
} |
q163209 | Notification.deleter | train | public static NotificationDeleter deleter(final String pathAccountSid,
final String pathCallSid,
final String pathSid) {
return new NotificationDeleter(pathAccountSid, pathCallSid, pathSid);
} | java | {
"resource": ""
} |
q163210 | FieldValue.fetcher | train | public static FieldValueFetcher fetcher(final String pathAssistantSid,
final String pathFieldTypeSid,
final String pathSid) {
return new FieldValueFetcher(pathAssistantSid, pathFieldTypeSid, pathSid);
} | java | {
"resource": ""
} |
q163211 | FieldValue.creator | train | public static FieldValueCreator creator(final String pathAssistantSid,
final String pathFieldTypeSid,
final String language,
final String value) {
return new FieldValueCreator(pathAssistantSid, pathFieldTypeSid, language, value);
} | java | {
"resource": ""
} |
q163212 | FieldValue.deleter | train | public static FieldValueDeleter deleter(final String pathAssistantSid,
final String pathFieldTypeSid,
final String pathSid) {
return new FieldValueDeleter(pathAssistantSid, pathFieldTypeSid, pathSid);
} | java | {
"resource": ""
} |
q163213 | InstalledAddOnExtension.updater | train | public static InstalledAddOnExtensionUpdater updater(final String pathInstalledAddOnSid,
final String pathSid,
final Boolean enabled) {
return new InstalledAddOnExtensionUpdater(pathInstalledAddOnSid, pathSid, enabled);
} | java | {
"resource": ""
} |
q163214 | Asset.updater | train | public static AssetUpdater updater(final String pathServiceSid,
final String pathSid,
final String friendlyName) {
return new AssetUpdater(pathServiceSid, pathSid, friendlyName);
} | java | {
"resource": ""
} |
q163215 | IpAddress.creator | train | public static IpAddressCreator creator(final String pathAccountSid,
final String pathIpAccessControlListSid,
final String friendlyName,
final String ipAddress) {
return new IpAddressCreator(pathAccountSid, pathIpAccessControlListSid, friendlyName, ipAddress);
} | java | {
"resource": ""
} |
q163216 | IpAddress.fetcher | train | public static IpAddressFetcher fetcher(final String pathAccountSid,
final String pathIpAccessControlListSid,
final String pathSid) {
return new IpAddressFetcher(pathAccountSid, pathIpAccessControlListSid, pathSid);
} | java | {
"resource": ""
} |
q163217 | IpAddress.updater | train | public static IpAddressUpdater updater(final String pathAccountSid,
final String pathIpAccessControlListSid,
final String pathSid) {
return new IpAddressUpdater(pathAccountSid, pathIpAccessControlListSid, pathSid);
} | java | {
"resource": ""
} |
q163218 | IpAddress.deleter | train | public static IpAddressDeleter deleter(final String pathAccountSid,
final String pathIpAccessControlListSid,
final String pathSid) {
return new IpAddressDeleter(pathAccountSid, pathIpAccessControlListSid, pathSid);
} | java | {
"resource": ""
} |
q163219 | TaskChannel.creator | train | public static TaskChannelCreator creator(final String pathWorkspaceSid,
final String friendlyName,
final String uniqueName) {
return new TaskChannelCreator(pathWorkspaceSid, friendlyName, uniqueName);
} | java | {
"resource": ""
} |
q163220 | StepContext.fetcher | train | public static StepContextFetcher fetcher(final String pathFlowSid,
final String pathEngagementSid,
final String pathStepSid) {
return new StepContextFetcher(pathFlowSid, pathEngagementSid, pathStepSid);
} | java | {
"resource": ""
} |
q163221 | AssetVersion.fetcher | train | public static AssetVersionFetcher fetcher(final String pathServiceSid,
final String pathAssetSid,
final String pathSid) {
return new AssetVersionFetcher(pathServiceSid, pathAssetSid, pathSid);
} | java | {
"resource": ""
} |
q163222 | AssetVersion.creator | train | public static AssetVersionCreator creator(final String pathServiceSid,
final String pathAssetSid,
final String path,
final AssetVersion.Visibility visibility) {
return new AssetVersionCreator(pathServiceSid, pathAssetSid, path, visibility);
} | java | {
"resource": ""
} |
q163223 | Deployment.fetcher | train | public static DeploymentFetcher fetcher(final String pathServiceSid,
final String pathEnvironmentSid,
final String pathSid) {
return new DeploymentFetcher(pathServiceSid, pathEnvironmentSid, pathSid);
} | java | {
"resource": ""
} |
q163224 | Deployment.creator | train | public static DeploymentCreator creator(final String pathServiceSid,
final String pathEnvironmentSid,
final String buildSid) {
return new DeploymentCreator(pathServiceSid, pathEnvironmentSid, buildSid);
} | java | {
"resource": ""
} |
q163225 | FileLogger.setConfig | train | public void setConfig(LogFileConfiguration config) {
this.config = config == null ? null : config.readOnlyCopy();
if (config == null) {
Log.w(
DOMAIN,
"Database.log.getFile().getConfig() is now null, meaning file logging is disabled. "
+ "Log files required for product support are not being generated.");
}
updateConfig();
} | java | {
"resource": ""
} |
q163226 | CBLVersion.getSysInfo | train | public static String getSysInfo() {
String info = sysInfo.get();
if (info == null) {
final String version = Build.VERSION.RELEASE; // "1.0" or "3.4b5"
final String model = Build.MODEL;
info = String.format(
Locale.ENGLISH,
SYS_INFO,
(version.length() <= 0) ? "0.0" : version,
(model.length() <= 0) ? "unknown" : model);
sysInfo.compareAndSet(null, info);
}
return info;
} | java | {
"resource": ""
} |
q163227 | PrecisionContextRoundedOperator.of | train | public static PrecisionContextRoundedOperator of(MathContext mathContext) {
Objects.requireNonNull(mathContext);
if(RoundingMode.UNNECESSARY.equals(mathContext.getRoundingMode())) {
throw new IllegalArgumentException("To create the MathContextRoundedOperator you cannot use the RoundingMode.UNNECESSARY on MathContext");
}
if(mathContext.getPrecision() <= 0) {
throw new IllegalArgumentException("To create the MathContextRoundedOperator you cannot use the zero precision on MathContext");
}
return new PrecisionContextRoundedOperator(mathContext);
} | java | {
"resource": ""
} |
q163228 | FastMoney.checkNumber | train | protected void checkNumber(Number number) {
Objects.requireNonNull(number, "Number is required.");
// numeric check for overflow...
if (number.longValue() > MAX_BD.longValue()) {
throw new ArithmeticException("Value exceeds maximal value: " + MAX_BD);
}
BigDecimal bd = MoneyUtils.getBigDecimal(number);
if (bd.precision() > MAX_BD.precision()) {
throw new ArithmeticException("Precision exceeds maximal precision: " + MAX_BD.precision());
}
if (bd.scale() > SCALE) {
String val = MonetaryConfig.getConfig()
.get("org.javamoney.moneta.FastMoney.enforceScaleCompatibility");
if(val==null){
val = "false";
}
if (Boolean.parseBoolean(val)) {
throw new ArithmeticException("Scale of " + bd + " exceeds maximal scale: " + SCALE);
} else {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Scale exceeds maximal scale of FastMoney (" + SCALE +
"), implicit rounding will be applied to " + number);
}
}
}
} | java | {
"resource": ""
} |
q163229 | ECBRateReadingHandler.addRate | train | void addRate(CurrencyUnit term, LocalDate localDate, Number rate) {
RateType rateType = RateType.HISTORIC;
ExchangeRateBuilder builder;
if (Objects.nonNull(localDate)) {
// TODO check/test!
if (localDate.equals(LocalDate.now())) {
rateType = RateType.DEFERRED;
}
builder = new ExchangeRateBuilder(
ConversionContextBuilder.create(context, rateType).set(localDate).build());
} else {
builder = new ExchangeRateBuilder(ConversionContextBuilder.create(context, rateType).build());
}
builder.setBase(ECBHistoricRateProvider.BASE_CURRENCY);
builder.setTerm(term);
builder.setFactor(DefaultNumberValue.of(rate));
ExchangeRate exchangeRate = builder.build();
Map<String, ExchangeRate> rateMap = this.historicRates.get(localDate);
if (Objects.isNull(rateMap)) {
synchronized (this.historicRates) {
rateMap = Optional.ofNullable(this.historicRates.get(localDate)).orElse(new ConcurrentHashMap<>());
this.historicRates.putIfAbsent(localDate, rateMap);
}
}
rateMap.put(term.getCurrencyCode(), exchangeRate);
} | java | {
"resource": ""
} |
q163230 | DefaultMonetaryCurrenciesSingletonSpi.getProviderNames | train | @Override
public Set<String> getProviderNames() {
Set<String> result = new HashSet<>();
for (CurrencyProviderSpi spi : Bootstrap.getServices(CurrencyProviderSpi.class)) {
try {
result.add(spi.getProviderName());
} catch (Exception e) {
Logger.getLogger(DefaultMonetaryCurrenciesSingletonSpi.class.getName())
.log(Level.SEVERE, "Error loading currency provider names for " + spi.getClass().getName(),
e);
}
}
return result;
} | java | {
"resource": ""
} |
q163231 | LazyBoundCurrencyConversion.getExchangeRate | train | @Override
public ExchangeRate getExchangeRate(MonetaryAmount amount) {
return this.rateProvider.getExchangeRate(ConversionQueryBuilder
.of(conversionQuery).setBaseCurrency(amount.getCurrency())
.build());
// return this.rateProvider.getExchangeRate(amount.getCurrency(),
// getCurrency());
} | java | {
"resource": ""
} |
q163232 | Money.parse | train | public static Money parse(CharSequence text, MonetaryAmountFormat formatter) {
return from(formatter.parse(text));
} | java | {
"resource": ""
} |
q163233 | Money.isInfinityAndNotNaN | train | @Deprecated
public static boolean isInfinityAndNotNaN(Number number) {
if (Double.class == number.getClass() || Float.class == number.getClass()) {
double dValue = number.doubleValue();
if (!Double.isNaN(dValue) && Double.isInfinite(dValue)) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q163234 | LoadableResource.load | train | public boolean load() {
if ((lastLoaded + cacheTTLMillis) <= System.currentTimeMillis()) {
clearCache();
}
if (!readCache()) {
if (shouldReadDataFromFallback()) {
return loadFallback();
}
}
return true;
} | java | {
"resource": ""
} |
q163235 | LoadableResource.loadRemote | train | public boolean loadRemote() {
for (URI itemToLoad : remoteResources) {
try {
return load(itemToLoad, false);
} catch (Exception e) {
LOG.log(Level.INFO, "Failed to load resource: " + itemToLoad, e);
}
}
return false;
} | java | {
"resource": ""
} |
q163236 | LoadableResource.loadFallback | train | public boolean loadFallback() {
try {
if (fallbackLocation == null) {
Logger.getLogger(getClass().getName()).warning("No fallback resource for " + this +
", loadFallback not supported.");
return false;
}
load(fallbackLocation, true);
clearCache();
return true;
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to load fallback resource: " + fallbackLocation, e);
}
return false;
} | java | {
"resource": ""
} |
q163237 | IdentityRateProvider.isAvailable | train | @Override
public boolean isAvailable(ConversionQuery conversionQuery) {
return conversionQuery.getBaseCurrency().getCurrencyCode()
.equals(conversionQuery.getCurrency().getCurrencyCode());
} | java | {
"resource": ""
} |
q163238 | CurrencyUnitBuilder.of | train | public static CurrencyUnitBuilder of(String currencyCode, String providerName) {
return new CurrencyUnitBuilder(currencyCode, CurrencyContextBuilder.of(providerName).build());
} | java | {
"resource": ""
} |
q163239 | CurrencyUnitBuilder.setCurrencyCode | train | public CurrencyUnitBuilder setCurrencyCode(String currencyCode) {
Objects.requireNonNull(currencyCode, "currencyCode required");
this.currencyCode = currencyCode;
this.currencyContext = CurrencyContextBuilder.of(getClass().getSimpleName()).build();
return this;
} | java | {
"resource": ""
} |
q163240 | MoneyUtils.checkAmountParameter | train | public static void checkAmountParameter(MonetaryAmount amount, CurrencyUnit currencyUnit) {
requireNonNull(amount, "Amount must not be null.");
final CurrencyUnit amountCurrency = amount.getCurrency();
if (!currencyUnit.getCurrencyCode().equals(amountCurrency.getCurrencyCode())) {
throw new MonetaryException("Currency mismatch: " + currencyUnit + '/' + amountCurrency);
}
} | java | {
"resource": ""
} |
q163241 | MonetaryFunctions.groupByCurrencyUnit | train | public static Collector<MonetaryAmount,?,Map<CurrencyUnit,List<MonetaryAmount>>> groupByCurrencyUnit(){
return Collectors.groupingBy(MonetaryAmount::getCurrency);
} | java | {
"resource": ""
} |
q163242 | MonetaryFunctions.summarizingMonetary | train | public static Collector<MonetaryAmount, MonetarySummaryStatistics, MonetarySummaryStatistics> summarizingMonetary(
CurrencyUnit currencyUnit){
Supplier<MonetarySummaryStatistics> supplier = () -> new DefaultMonetarySummaryStatistics(currencyUnit);
return Collector.of(supplier, MonetarySummaryStatistics::accept, MonetarySummaryStatistics::combine);
} | java | {
"resource": ""
} |
q163243 | MonetaryFunctions.summarizingMonetary | train | @Deprecated
public static Collector<MonetaryAmount, MonetarySummaryStatistics, MonetarySummaryStatistics> summarizingMonetary(
CurrencyUnit currencyUnit, ExchangeRateProvider provider){
// TODO implement method here
return summarizingMonetary(currencyUnit);
} | java | {
"resource": ""
} |
q163244 | MonetaryFunctions.groupBySummarizingMonetary | train | public static Collector<MonetaryAmount,GroupMonetarySummaryStatistics,GroupMonetarySummaryStatistics>
groupBySummarizingMonetary(){
return Collector.of(GroupMonetarySummaryStatistics::new, GroupMonetarySummaryStatistics::accept,
GroupMonetarySummaryStatistics::combine);
} | java | {
"resource": ""
} |
q163245 | MonetaryFunctions.isBetween | train | public static Predicate<MonetaryAmount> isBetween(MonetaryAmount min, MonetaryAmount max){
return isLessThanOrEqualTo(max).and(isGreaterThanOrEqualTo(min));
} | java | {
"resource": ""
} |
q163246 | MonetaryFunctions.sum | train | public static MonetaryAmount sum(MonetaryAmount a, MonetaryAmount b){
MoneyUtils.checkAmountParameter(Objects.requireNonNull(a), Objects.requireNonNull(b.getCurrency()));
return a.add(b);
} | java | {
"resource": ""
} |
q163247 | MonetaryFunctions.sum | train | public static BinaryOperator<MonetaryAmount> sum(
ExchangeRateProvider provider, CurrencyUnit currency) {
CurrencyConversion currencyConversion = provider
.getCurrencyConversion(currency);
return (m1, m2) -> currencyConversion.apply(m1).add(
currencyConversion.apply(m2));
} | java | {
"resource": ""
} |
q163248 | MonetaryFunctions.min | train | public static BinaryOperator<MonetaryAmount> min(
ExchangeRateProvider provider) {
return (m1, m2) -> {
CurrencyConversion conversion = provider.getCurrencyConversion(m1
.getCurrency());
if (m1.isGreaterThan(conversion.apply(m2))) {
return m2;
}
return m1;
};
} | java | {
"resource": ""
} |
q163249 | ConversionOperators.summarizingMonetary | train | public static Collector<MonetaryAmount, MonetarySummaryStatistics, MonetarySummaryStatistics> summarizingMonetary(
CurrencyUnit currencyUnit, ExchangeRateProvider provider) {
Supplier<MonetarySummaryStatistics> supplier = () -> new ExchangeRateMonetarySummaryStatistics(
currencyUnit, provider);
return Collector.of(supplier, MonetarySummaryStatistics::accept,
MonetarySummaryStatistics::combine);
} | java | {
"resource": ""
} |
q163250 | Http11BlockLoader.getBlock | train | public byte[] getBlock(String url, long offset, int length)
throws IOException {
HttpMethod method = null;
try {
method = new GetMethod(url);
} catch(IllegalArgumentException e) {
LOGGER.warning("Bad URL for block fetch:" + url);
throw new IOException("Url:" + url + " does not look like an URL?");
}
StringBuilder sb = new StringBuilder(16);
sb.append(ZiplinedBlock.BYTES_HEADER).append(offset);
sb.append(ZiplinedBlock.BYTES_MINUS).append((offset + length)-1);
String rangeHeader = sb.toString();
method.addRequestHeader(ZiplinedBlock.RANGE_HEADER, rangeHeader);
//uc.setRequestProperty(RANGE_HEADER, sb.toString());
long start = System.currentTimeMillis();
try {
LOGGER.fine("Reading block:" + url + "("+rangeHeader+")");
int status = http.executeMethod(method);
if((status == 200) || (status == 206)) {
InputStream is = method.getResponseBodyAsStream();
byte[] block = new byte[length];
ByteStreams.readFully(is, block);
long elapsed = System.currentTimeMillis() - start;
PerformanceLogger.noteElapsed("CDXBlockLoad",elapsed,url);
return block;
} else {
throw new IOException("Bad status for " + url);
}
} finally {
method.releaseConnection();
}
} | java | {
"resource": ""
} |
q163251 | SpringReader.readSpringConfig | train | public static RequestMapper readSpringConfig(String configPath,
ServletContext servletContext) {
LOGGER.info("Loading from config file " + configPath);
currentContext = new FileSystemXmlApplicationContext("file:" + configPath);
Map<String,RequestHandler> beans =
currentContext.getBeansOfType(RequestHandler.class,false,false);
return new RequestMapper(beans.values(), servletContext);
} | java | {
"resource": ""
} |
q163252 | GraphRenderer.renderHTML | train | public static String renderHTML(Graph graph, String mapName, String imgUrl,
String targets[], String titles[]) {
StringBuilder sb = new StringBuilder();
sb.append("<map name=\"").append(mapName).append("\">");
RegionGraphElement rge[] = graph.getRegions();
int count = rge.length;
for(int i = 0; i < count; i++) {
if(targets[i] != null) {
Rectangle r = rge[i].getBoundingRectangle();
sb.append("<area href=\"").append(targets[i]).append("\"");
if(titles[i] != null) {
sb.append(" title=\"").append(titles[i]).append("\"");
}
sb.append(" shape=\"rect\" coords=\"");
sb.append(r.x).append(",");
sb.append(r.y).append(",");
sb.append(r.x+r.width).append(",");
sb.append(r.y+r.height).append("\" border=\"1\" />");
}
}
sb.append("</map>");
sb.append("<image src=\"").append(imgUrl).append("\"");
sb.append(" border=\"0\" width=\"").append(graph.width).append("\"");
sb.append(" height=\"").append(graph.height).append("\"");
sb.append(" usemap=\"#").append(mapName).append("\" />");
return sb.toString();
} | java | {
"resource": ""
} |
q163253 | GraphRenderer.render | train | public void render(OutputStream target, Graph graph) throws IOException {
BufferedImage bi =
new BufferedImage(graph.width, graph.height,
GraphConfiguration.imageType);
Graphics2D g2d = bi.createGraphics();
graph.draw(g2d);
ImageIO.write(bi, "png", target);
} | java | {
"resource": ""
} |
q163254 | DecodingResource.forEncoding | train | public static DecodingResource forEncoding(String contentEncoding, Resource source) throws IOException {
InputStream stream = decodingStream(contentEncoding, source);
if (stream == null) {
return null;
}
return new DecodingResource(source, stream);
} | java | {
"resource": ""
} |
q163255 | CompositeSearchResultSource.setCDXSources | train | public void setCDXSources(List<String> cdxs) {
sources = new ArrayList<SearchResultSource>();
for(int i = 0; i < cdxs.size(); i++) {
CDXIndex index = new CDXIndex();
index.setPath(cdxs.get(i));
addSource(index);
}
} | java | {
"resource": ""
} |
q163256 | GraphEncoder.decode | train | public static Graph decode(String encodedGraph, boolean noMonth)
throws GraphEncodingException {
GraphConfiguration config = new GraphConfiguration();
if(noMonth) {
config.valueHighlightColor = config.valueColor;
}
return decode(encodedGraph, config);
} | java | {
"resource": ""
} |
q163257 | GraphEncoder.decode | train | public static Graph decode(String encodedGraph, GraphConfiguration config)
throws GraphEncodingException {
// encoded = "800_35_REGIONDATA_REGIONDATA_REGIONDATA_REGIONDATA_..."
String parts[] = encodedGraph.split(DELIM);
int numRegions = parts.length - 2;
if(parts.length < 1) {
throw new GraphEncodingException("No regions defined!");
}
int width;
int height;
try {
width = Integer.parseInt(parts[0]);
} catch(NumberFormatException e) {
throw new GraphEncodingException("Bad integer width:" + parts[0]);
}
try {
height = Integer.parseInt(parts[1]);
} catch(NumberFormatException e) {
throw new GraphEncodingException("Bad integer width:" + parts[0]);
}
RegionData data[] = new RegionData[numRegions];
for(int i = 0; i < numRegions; i++) {
// REGIONDATA = "2001:-1:0ab3f70023f902f"
// LABEL:ACTIVE_IDX:HEXDATA
String regionParts[] = parts[i + 2].split(REGION_DELIM);
if(regionParts.length != 3) {
throw new GraphEncodingException("Wrong number of parts in " +
parts[i+2]);
}
int highlightedValue = Integer.parseInt(regionParts[1]);
int values[] = decodeHex(regionParts[2]);
data[i] = new RegionData(regionParts[0], highlightedValue, values);
}
return new Graph(width, height, data, config);
} | java | {
"resource": ""
} |
q163258 | GraphEncoder.encode | train | public static String encode(Graph g) {
RegionGraphElement rge[] = g.getRegions();
RegionData data[] = new RegionData[rge.length];
for(int i = 0; i < data.length; i++) {
data[i] = rge[i].getData();
}
return encode(g.width, g.height, data);
} | java | {
"resource": ""
} |
q163259 | GraphEncoder.encode | train | public static String encode(int width, int height, RegionData data[]) {
StringBuilder sb = new StringBuilder();
sb.append(width).append(DELIM);
sb.append(height);
boolean first = false;
for(RegionData datum : data) {
if(first) {
first = false;
} else {
sb.append(DELIM);
}
sb.append(datum.getLabel()).append(REGION_DELIM);
sb.append(datum.getHighlightedValue()).append(REGION_DELIM);
sb.append(encodeHex(datum.getValues()));
}
return sb.toString();
} | java | {
"resource": ""
} |
q163260 | UriMatchRule.processIfMatches | train | public String processIfMatches(final I input) {
String uriAsString = input.getUri();
String text = input.getTextToProcess();
Matcher m = patternImpl.matcher(uriAsString);
if (!m.find()) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Rule " + getClass().getSimpleName()
+ ": skipped " + uriAsString);
}
return text;
}
String result = new String(text);
for (PatternBasedTextProcessor proc : processors) {
result = proc.process(result);
}
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Rule " + getClass().getSimpleName()
+ ": processed " + uriAsString);
}
return result;
} | java | {
"resource": ""
} |
q163261 | ResultsPartitionsFactory.get | train | public static ArrayList<ResultsPartition> get(CaptureSearchResults results,
WaybackRequest wbRequest) {
return get(results, wbRequest, null);
} | java | {
"resource": ""
} |
q163262 | ValueGraphElements.getElement | train | public ValueGraphElement getElement(int i) {
if((i < 0) || (i >= values.length)) {
throw new NoSuchElementException();
}
int minHeight = config.valueMinHeight;
// normalize height to value between 0 and 1:
float value = ((float) values[i]) / ((float) maxValue);
float usableHeight = height - minHeight;
int valueHeight = (int) (usableHeight * value) + minHeight;
int elX = Graph.xlateX(width, values.length, i);
int elW = Graph.xlateX(width, values.length, i+1) - elX;
int elY = height - valueHeight;
boolean hot = i == highlightValue;
return new ValueGraphElement(x + elX, y + elY, elW, valueHeight, hot, config);
} | java | {
"resource": ""
} |
q163263 | RangeGroup.setMembers | train | public synchronized void setMembers(String[] urls) {
HashMap<String,RangeMember> newMembers =
new HashMap<String,RangeMember>();
for(int i=0; i < urls.length; i++) {
if(members.containsKey(urls[i])) {
newMembers.put(urls[i],members.get(urls[i]));
} else {
RangeMember newMember = new RangeMember();
newMember.setUrlBase(urls[i]);
newMembers.put(urls[i],newMember);
}
}
members = newMembers;
} | java | {
"resource": ""
} |
q163264 | PerfStats.getAllStats | train | public static String getAllStats(OutputFormat format) {
StringBuilder sb = new StringBuilder();
boolean first = true;
Collection<PerfStatEntry> stats = perfStats.get().values();
switch (format) {
case JSON:
sb.append('{');
for (PerfStatEntry entry : stats) {
if (entry.count > 0) {
if (first) {
first = false;
} else {
sb.append(',');
}
sb.append('"').append(entry.name).append("\":");
if (entry.isErr)
sb.append("null");
else
sb.append(entry.total);
}
}
sb.append('}');
break;
default:
sb.append("[");
for (PerfStatEntry entry : stats) {
if (entry.count > 0) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(entry.toString());
}
}
sb.append("]");
break;
}
return sb.toString();
} | java | {
"resource": ""
} |
q163265 | TextDocument.resolvePageUrls | train | public void resolvePageUrls() {
// TODO: get url from Resource instead of SearchResult?
String pageUrl = result.getOriginalUrl();
String captureDate = result.getCaptureTimestamp();
String existingBaseHref = TagMagix.getBaseHref(sb);
if (existingBaseHref == null) {
insertAtStartOfHead("<base href=\"" + pageUrl + "\" />");
} else {
pageUrl = existingBaseHref;
}
String markups[][] = {
{"FRAME","SRC"},
{"META","URL"},
{"LINK","HREF"},
{"SCRIPT","SRC"},
{TagMagix.ANY_TAGNAME,"background"}
};
// TODO: The classic WM added a js_ to the datespec, so NotInArchives
// can return an valid javascript doc, and not cause Javascript errors.
for(String tagAttr[] : markups) {
TagMagix.markupTagREURIC(sb, uriConverter, captureDate, pageUrl,
tagAttr[0], tagAttr[1]);
}
TagMagix.markupCSSImports(sb,uriConverter, captureDate, pageUrl);
TagMagix.markupStyleUrls(sb,uriConverter,captureDate,pageUrl);
} | java | {
"resource": ""
} |
q163266 | TextDocument.resolveAllPageUrls | train | public void resolveAllPageUrls() {
// TODO: get url from Resource instead of SearchResult?
String pageUrl = result.getOriginalUrl();
String captureDate = result.getCaptureTimestamp();
String existingBaseHref = TagMagix.getBaseHref(sb);
if (existingBaseHref != null) {
pageUrl = existingBaseHref;
}
ResultURIConverter ruc = new SpecialResultURIConverter(uriConverter);
// TODO: forms...?
String markups[][] = {
{"FRAME","SRC"},
{"META","URL"},
{"LINK","HREF"},
{"SCRIPT","SRC"},
{"IMG","SRC"},
{"A","HREF"},
{"AREA","HREF"},
{"OBJECT","CODEBASE"},
{"OBJECT","CDATA"},
{"APPLET","CODEBASE"},
{"APPLET","ARCHIVE"},
{"EMBED","SRC"},
{"IFRAME","SRC"},
{TagMagix.ANY_TAGNAME,"background"}
};
for(String tagAttr[] : markups) {
TagMagix.markupTagREURIC(sb, ruc, captureDate, pageUrl,
tagAttr[0], tagAttr[1]);
}
TagMagix.markupCSSImports(sb,uriConverter, captureDate, pageUrl);
TagMagix.markupStyleUrls(sb,uriConverter,captureDate,pageUrl);
} | java | {
"resource": ""
} |
q163267 | TextDocument.writeToOutputStream | train | public void writeToOutputStream(OutputStream os) throws IOException {
if(sb == null) {
throw new IllegalStateException("No interal StringBuffer");
}
byte[] b;
try {
b = getBytes();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
os.write(b);
} | java | {
"resource": ""
} |
q163268 | DirMaker.ensureDir | train | public static File ensureDir(String path, String name) throws IOException {
if((path == null) || (path.length() == 0)) {
throw new IOException("No configuration for (" + name + ")");
}
File dir = new File(path);
if(dir.exists()) {
if(!dir.isDirectory()) {
throw new IOException("Dir(" + name + ") at (" + path +
") exists but is not a directory!");
}
} else {
if(!dir.mkdirs()) {
throw new IOException("Unable to create dir(" + name +") at ("
+ path + ")");
}
}
return dir;
} | java | {
"resource": ""
} |
q163269 | GraphConfiguration.setRenderingHints | train | public void setRenderingHints(Graphics2D g2d) {
// g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
// RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
} | java | {
"resource": ""
} |
q163270 | StringFormatter.getLocalized | train | public String getLocalized(String key) {
if (bundle != null) {
try {
return bundle.getString(key);
// String localized = bundle.getString(key);
// if((localized != null) && (localized.length() > 0)) {
// return localized;
// }
} catch (Exception e) {
}
}
return key;
} | java | {
"resource": ""
} |
q163271 | LocalResourceIndexUpdater.init | train | public void init() throws ConfigurationException {
if(index == null) {
throw new ConfigurationException("No index target");
}
if(!index.isUpdatable()) {
throw new ConfigurationException("ResourceIndex is not updatable");
}
if(incoming == null) {
throw new ConfigurationException("No incoming");
}
if(runInterval > 0) {
thread = new UpdateThread(this,runInterval);
thread.start();
}
} | java | {
"resource": ""
} |
q163272 | ArcResource.parseHeaders | train | public void parseHeaders () throws IOException {
if(!parsedHeader) {
arcRecord.skipHttpHeader();
// copy all HTTP headers to metaData, prefixing with
// HTTP_HEADER_PREFIX
Header[] headers = arcRecord.getHttpHeaders();
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
String value = headers[i].getValue();
String name = headers[i].getName();
metaData.put(HTTP_HEADER_PREFIX + name,value);
if(name.toUpperCase().contains(
HttpHeaderOperation.HTTP_TRANSFER_ENC_HEADER)) {
if(value.toUpperCase().contains(
HttpHeaderOperation.HTTP_CHUNKED_ENCODING_HEADER)) {
setChunkedEncoding();
}
}
}
}
// copy all ARC record header fields to metaData, prefixing with
// ARC_META_PREFIX
Map<String,Object> headerMetaMap = arcRecord.getMetaData().getHeaderFields();
Set<String> keys = headerMetaMap.keySet();
Iterator<String> itr = keys.iterator();
while(itr.hasNext()) {
String metaKey = itr.next();
Object value = headerMetaMap.get(metaKey);
String metaValue = "";
if(value != null) {
metaValue = value.toString();
}
metaData.put(ARC_META_PREFIX + metaKey,metaValue);
}
parsedHeader = true;
}
} | java | {
"resource": ""
} |
q163273 | UIResults.resultToReplayUrl | train | public String resultToReplayUrl(CaptureSearchResult result) {
if(uriConverter == null) {
return null;
}
String url = result.getOriginalUrl();
String captureDate = result.getCaptureTimestamp();
return uriConverter.makeReplayURI(captureDate,url);
} | java | {
"resource": ""
} |
q163274 | UIResults.urlForPage | train | public String urlForPage(int pageNum) {
WaybackRequest wbRequest = getWbRequest();
return wbRequest.getAccessPoint().getQueryPrefix() + "query?" +
wbRequest.getQueryArguments(pageNum);
} | java | {
"resource": ""
} |
q163275 | UIResults.forward | train | public void forward(HttpServletRequest request,
HttpServletResponse response, final String target)
throws ServletException, IOException {
if (target.startsWith("/WEB-INF/classes")
|| target.startsWith("/WEB-INF/lib")
|| target.matches("^/WEB-INF/.+\\.xml")) {
throw new IOException("Not allowed");
}
this.contentJsp = target;
this.originalRequestURL = request.getRequestURL().toString();
request.setAttribute(FERRET_NAME, this);
RequestDispatcher dispatcher = request.getRequestDispatcher(target);
if(dispatcher == null) {
throw new IOException("No dispatcher for " + target);
}
dispatcher.forward(request, response);
} | java | {
"resource": ""
} |
q163276 | UIResults.extractException | train | public static UIResults extractException(HttpServletRequest httpRequest)
throws ServletException {
UIResults results = (UIResults) httpRequest.getAttribute(FERRET_NAME);
if (results == null) {
throw new ServletException("No attribute..");
}
if (results.exception == null) {
throw new ServletException("No WaybackException..");
}
if (results.wbRequest == null) {
throw new ServletException("No WaybackRequest..");
}
if (results.uriConverter == null) {
throw new ServletException("No ResultURIConverter..");
}
return results;
} | java | {
"resource": ""
} |
q163277 | UIResults.extractCaptureQuery | train | public static UIResults extractCaptureQuery(HttpServletRequest httpRequest)
throws ServletException {
UIResults results = (UIResults) httpRequest.getAttribute(FERRET_NAME);
if (results == null) {
throw new ServletException("No attribute..");
}
if (results.wbRequest == null) {
throw new ServletException("No WaybackRequest..");
}
if (results.uriConverter == null) {
throw new ServletException("No ResultURIConverter..");
}
if (results.captureResults == null) {
throw new ServletException("No CaptureSearchResults..");
}
return results;
} | java | {
"resource": ""
} |
q163278 | UIResults.extractUrlQuery | train | public static UIResults extractUrlQuery(HttpServletRequest httpRequest)
throws ServletException {
UIResults results = (UIResults) httpRequest.getAttribute(FERRET_NAME);
if (results == null) {
throw new ServletException("No attribute..");
}
if (results.wbRequest == null) {
throw new ServletException("No WaybackRequest..");
}
if (results.uriConverter == null) {
throw new ServletException("No ResultURIConverter..");
}
if (results.urlResults == null) {
throw new ServletException("No UrlSearchResults..");
}
return results;
} | java | {
"resource": ""
} |
q163279 | UIResults.extractReplay | train | public static UIResults extractReplay(HttpServletRequest httpRequest)
throws ServletException {
UIResults results = (UIResults) httpRequest.getAttribute(FERRET_NAME);
if (results == null) {
throw new ServletException("No attribute..");
}
if (results.wbRequest == null) {
throw new ServletException("No WaybackRequest..");
}
if (results.uriConverter == null) {
throw new ServletException("No ResultURIConverter..");
}
if (results.captureResults == null) {
throw new ServletException("No CaptureSearchResults..");
}
if (results.result == null) {
throw new ServletException("No CaptureSearchResult..");
}
if (results.resource == null) {
throw new ServletException("No Resource..");
}
return results;
} | java | {
"resource": ""
} |
q163280 | UIResults.getTargetSite | train | public String getTargetSite() {
try {
String urlstr = wbRequest.getRequestUrl();
if (urlstr == null) return null;
URL url = new URL(urlstr);
return url.getHost();
} catch (MalformedURLException ex) {
return null;
}
} | java | {
"resource": ""
} |
q163281 | DirectoryResourceFileSource.populateFileList | train | private void populateFileList(ResourceFileList list, File root, boolean recurse)
throws IOException {
if(root.isDirectory()) {
File[] files = root.listFiles();
if(files != null) {
for(File file : files) {
if(file.isFile() && filter.accept(root, file.getName())) {
ResourceFileLocation location = new ResourceFileLocation(
file.getName(),file.getAbsolutePath());
list.add(location);
} else if(recurse && file.isDirectory()){
populateFileList(list, file, recurse);
}
}
}
} else {
LOGGER.warning(root.getAbsolutePath() + " is not a directory.");
return;
}
} | java | {
"resource": ""
} |
q163282 | BDBRecordSet.shutdownDB | train | public synchronized void shutdownDB() throws DatabaseException {
if (db != null) {
db.close();
db = null;
}
if (env != null) {
env.close();
env = null;
}
} | java | {
"resource": ""
} |
q163283 | FileRegion.copyToOutputStream | train | public void copyToOutputStream(OutputStream o) throws IOException {
long left = end - start;
int BUFF_SIZE = 4096;
byte buf[] = new byte[BUFF_SIZE];
RandomAccessFile raf = new RandomAccessFile(file, "r");
try {
raf.seek(start);
while(left > 0) {
int amtToRead = (int) Math.min(left, BUFF_SIZE);
int amtRead = raf.read(buf, 0, amtToRead);
if(amtRead < 0) {
throw new IOException("Not enough to read! EOF before expected region end");
}
o.write(buf,0,amtRead);
left -= amtRead;
}
} finally {
raf.close();
}
} | java | {
"resource": ""
} |
q163284 | PreservingHttpHeaderProcessor.setPrefix | train | public void setPrefix(String prefix) {
this.prefix = prefix;
if (this.prefix != null && this.prefix.isEmpty())
this.prefix = null;
} | java | {
"resource": ""
} |
q163285 | BeanNameRegistrar.registerHandler | train | public static void registerHandler(RequestHandler handler,
RequestMapper mapper) {
String name = null;
int internalPort = 8080;
if (handler instanceof AbstractRequestHandler) {
name = ((AbstractRequestHandler)handler).getAccessPointPath();
internalPort = ((AbstractRequestHandler)handler).getInternalPort();
}
if (name == null) {
name = handler.getBeanName();
if (name != null) {
LOGGER.warning("Request handler with bean name " + name + " does not provide explict " +
"access point path. Will try to use the beanname to infer. This fallback " +
"is DEPRECATED and will be removed in the future. Please update configuration " +
"to explicitly set 'accessPointPath' property (and 'internalPort' if needed).");
}
}
if(name != null) {
if(name.equals(RequestMapper.GLOBAL_PRE_REQUEST_HANDLER)) {
LOGGER.info("Registering Global-pre request handler:" +
handler);
mapper.addGlobalPreRequestHandler(handler);
} else if(name.equals(RequestMapper.GLOBAL_POST_REQUEST_HANDLER)) {
LOGGER.info("Registering Global-post request handler:" +
handler);
mapper.addGlobalPostRequestHandler(handler);
} else {
try {
boolean registered =
registerPort(name, handler, mapper) ||
registerPortPath(name, handler, mapper) ||
registerHostPort(name, handler, mapper) ||
registerHostPortPath(name, handler, mapper) ||
registerURIPatternPath(name, internalPort, handler, mapper);
if(!registered) {
LOGGER.severe("Unable to register (" + name + ")");
}
} catch(NumberFormatException e) {
LOGGER.severe("FAILED parseInt(" + name + ")");
}
}
} else {
LOGGER.info("Unable to register RequestHandler - null beanName");
}
if(handler instanceof ShutdownListener) {
ShutdownListener s = (ShutdownListener) handler;
mapper.addShutdownListener(s);
}
} | java | {
"resource": ""
} |
q163286 | CDXFlexFormat.parseCDXLineFlex | train | public static CaptureSearchResult parseCDXLineFlex(String line) {
CaptureSearchResult result = new CaptureSearchResult();
return parseCDXLineFlex(line, result);
} | java | {
"resource": ""
} |
q163287 | CDXFlexFormat.parseCDXLineFlexFast | train | public static CaptureSearchResult parseCDXLineFlexFast(String line) {
CaptureSearchResult result = new FastCaptureSearchResult();
return parseCDXLineFlex(line, result);
} | java | {
"resource": ""
} |
q163288 | SURTTokenizer.nextSearch | train | public String nextSearch() {
if(!triedExact) {
triedExact = true;
return remainder + EXACT_SUFFIX;
}
if(!triedFull) {
triedFull = true;
if(remainder.endsWith(")/")) {
choppedPath = true;
}
return remainder;
}
if(!choppedArgs) {
choppedArgs = true;
int argStart = remainder.indexOf('?');
if(argStart != -1) {
remainder = remainder.substring(0,argStart);
return remainder;
}
}
// we have already returned remainder as-is, so we have slightly
// special handling here to make sure we continue to make progress:
// (com,foo,www,)/ => (com,foo,www,
// (com,foo,www,)/bar => (com,foo,www,)/
// (com,foo,www,)/bar/ => (com,foo,www,)/bar
// (com,foo,www,)/bar/foo => (com,foo,www,)/bar
// (com,foo,www,)/bar/foo/ => (com,foo,www,)/bar/foo
if(!choppedPath) {
int lastSlash = remainder.lastIndexOf('/');
if(lastSlash != -1) {
if(lastSlash == (remainder.length()-1)) {
if(remainder.endsWith(")/")) {
String tmp = remainder;
remainder = remainder.substring(0,lastSlash-1);
choppedPath = true;
return tmp;
} else {
remainder = remainder.substring(0,lastSlash);
return remainder;
}
}
if((lastSlash > 0) && remainder.charAt(lastSlash-1) == ')') {
String tmp = remainder.substring(0,lastSlash+1);
remainder = remainder.substring(0,lastSlash-1);
return tmp;
} else {
remainder = remainder.substring(0,lastSlash);
return remainder;
}
}
choppedPath = true;
}
if(!choppedLogin) {
choppedLogin = true;
int lastAt = remainder.lastIndexOf('@');
if(lastAt != -1) {
String tmp = remainder;
remainder = remainder.substring(0,lastAt);
return tmp;
}
}
if(!choppedPort) {
choppedPort = true;
int lastColon = remainder.lastIndexOf(':');
if(lastColon != -1) {
return remainder;
}
}
// now just remove ','s
int lastComma = remainder.lastIndexOf(',');
if(lastComma == -1) {
return null;
}
remainder = remainder.substring(0,lastComma);
return remainder;
} | java | {
"resource": ""
} |
q163289 | CDXServer.afterPropertiesSet | train | @Override
public void afterPropertiesSet() throws Exception {
if (cdxSource == null) {
cdxSource = zipnumSource;
}
cdxLineFactory = new StandardCDXLineFactory(cdxFormat);
// defaultCdxFormat = cdxLineFactory.getParseFormat();
// if (authChecker != null && authChecker.getPublicCdxFields() != null)
// {
// publicCdxFields = new
// FieldSplitFormat(authChecker.getPublicCdxFields());
// }
if (defaultParams == null) {
defaultParams = new ZipNumParams(maxPageSize, maxPageSize, 0, false);
}
super.afterPropertiesSet();
} | java | {
"resource": ""
} |
q163290 | Timestamp.setDate | train | public final void setDate(final Date date) {
this.date = (Date) date.clone();
dateStr = ArchiveUtils.get14DigitDate(date);
} | java | {
"resource": ""
} |
q163291 | Timestamp.dateStrToDate | train | public static Date dateStrToDate(final String dateStr) {
String paddedDateStr = padStartDateStr(dateStr);
try {
return ArchiveUtils.parse14DigitDate(paddedDateStr);
} catch (ParseException e) {
e.printStackTrace();
// TODO: This is certainly not the right thing, but padStartDateStr
// should ensure we *never* get here..
return new Date((long)SSE_YEAR_LOWER_LIMIT * 1000);
}
} | java | {
"resource": ""
} |
q163292 | Timestamp.padEndDateStr | train | public static String padEndDateStr(String timestamp) {
return boundTimestamp(padDigits(timestamp,LOWER_TIMESTAMP_LIMIT,
UPPER_TIMESTAMP_LIMIT,UPPER_TIMESTAMP_LIMIT));
} | java | {
"resource": ""
} |
q163293 | Timestamp.padStartDateStr | train | public static String padStartDateStr(String timestamp) {
return boundTimestamp(padDigits(timestamp,LOWER_TIMESTAMP_LIMIT,
UPPER_TIMESTAMP_LIMIT,LOWER_TIMESTAMP_LIMIT));
} | java | {
"resource": ""
} |
q163294 | RemoteResourceFileLocationDB.nameToUrls | train | public String[] nameToUrls(final String name) throws IOException {
NameValuePair[] args = {
new NameValuePair(
ResourceFileLocationDBServlet.OPERATION_ARGUMENT,
ResourceFileLocationDBServlet.LOOKUP_OPERATION),
new NameValuePair(
ResourceFileLocationDBServlet.NAME_ARGUMENT,
name)
};
String locations = doGetMethod(args);
if(locations != null) {
return locations.split("\n");
}
return null;
} | java | {
"resource": ""
} |
q163295 | RemoteResourceFileLocationDB.addNameUrl | train | public void addNameUrl(final String name, final String url)
throws IOException {
doPostMethod(ResourceFileLocationDBServlet.ADD_OPERATION, name, url);
} | java | {
"resource": ""
} |
q163296 | RemoteResourceFileLocationDB.removeNameUrl | train | public void removeNameUrl(final String name, final String url)
throws IOException {
doPostMethod(ResourceFileLocationDBServlet.REMOVE_OPERATION, name, url);
} | java | {
"resource": ""
} |
q163297 | RangeResource.parseRange | train | public void parseRange() throws RangeNotSatisfiableException, IOException {
if (requestedRanges.length > 1) {
throw new RangeNotSatisfiableException(origResource, requestedRanges,
"Multiple ranges are not supported yet");
}
final long[] firstRange = requestedRanges[0];
long start = firstRange[0];
long stop = firstRange[1];
long[] availRange = availableRange();
if (availRange == null) {
throw new RangeNotSatisfiableException(origResource, requestedRanges,
"available range cannot be determined");
}
if (start < 0) {
// tail range (-N) - translate to absolute positions
start = availRange[2] + start;
stop = availRange[2];
}
if (stop < 0) {
// M-
stop = availRange[2];
}
if (start < availRange[0] || stop > availRange[1]) {
// requested range is not satisfiable with content available
// in the resource.
// TODO: if availRange[1] == file length, stop > availRange[1]
// is okay. We just replay start..availRange[1]. Guessing it
// must be extremely rare to have such capture.
throw new RangeNotSatisfiableException(origResource, requestedRanges,
"requested range is not available in this capture");
}
if (start > availRange[0]) {
origResource.skip(start - availRange[0]);
}
outputLength = stop - start;
setInputStream(ByteStreams.limit(origResource, outputLength));
httpHeaders = new HashMap<String, String>();
httpHeaders.putAll(origResource.getHttpHeaders());
// TODO: Add Content-Range
String contentRange = String.format("bytes %d-%d/%d", start,
stop - 1, availRange[2]);
HttpHeaderOperation.replaceHeader(httpHeaders,
HttpHeaderOperation.HTTP_CONTENT_RANGE_HEADER, contentRange);
HttpHeaderOperation
.replaceHeader(httpHeaders, HttpHeaderOperation.HTTP_LENGTH_HEADER,
Long.toString(stop - start));
} | java | {
"resource": ""
} |
q163298 | RangeResource.availableRange | train | protected long[] availableRange() {
// for revisit capture, HTTP headers comes from revisiting resource.
// it should be okay to assume revisited resource has exactly the same
// Content-Range header field.
Map<String, String> respHeaders = origResource.getHttpHeaders();
long[] contentRange = HttpHeaderOperation
.getContentRange(respHeaders);
long availStart, availStop, contentLength;
if (contentRange == null) {
// regular 200 response (or Content-Range is invalid)
String clen = HttpHeaderOperation.getContentLength(respHeaders);
if (clen != null) {
try {
contentLength = Long.parseLong(clen);
} catch (NumberFormatException ex) {
return null;
}
} else {
// no Content-Length - probably chunked encoded -
// not supported yet (TODO: determine length by
// actually reading?)
return null;
}
availStart = 0;
availStop = contentLength;
} else {
// 206, or perhaps 416 response
if (contentRange[0] < 0) {
// 416 (both [0] and [1] are -1 for */instance-length)
return null;
}
availStart = contentRange[0];
availStop = contentRange[1];
contentLength = contentRange[2];
// TODO: need support for M-N/*?
if (contentLength < 0)
return null;
// sanity check
if (availStop <= availStart) return null;
if (contentLength < availStop) return null;
}
return new long[] { availStart, availStop, contentLength };
} | java | {
"resource": ""
} |
q163299 | WaybackRequest.createUrlQueryRequest | train | public static WaybackRequest createUrlQueryRequest(String url, String start, String end) {
WaybackRequest r = new WaybackRequest();
r.setUrlQueryRequest();
r.setRequestUrl(url);
r.setStartTimestamp(start);
r.setEndTimestamp(end);
return r;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.