_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q169500 | MediaTypes.toHeader | validation | public static String toHeader(final MediaType mediaType) {
requireNonNull(mediaType,REFERENCE_MEDIA_TYPE_CANNOT_BE_NULL);
final StringBuilder builder=
new StringBuilder().
append(mediaType.type().toLowerCase(Locale.ENGLISH)).
append('/').
append(mediaType.subType().toLowerCase(Locale.ENGLISH));
final String suffix=mediaType.suffix();
if(suffix!=null) {
builder.append('+').append(suffix.toLowerCase(Locale.ENGLISH));
}
final Charset charset=mediaType.charset();
if(charset!=null) {
builder.append(";charset=").append(charset.name().toLowerCase(Locale.ENGLISH));
}
for(Entry<String,String> entry:mediaType.parameters().entrySet()) {
final String key=entry.getKey();
if(isStandardParameter(key)) {
continue;
}
builder.append(';').append(key.toLowerCase(Locale.ENGLISH)).append('=').append(entry.getValue());
}
return builder.toString();
} | java | {
"resource": ""
} |
q169501 | DynamicResourceResolver.run | validation | @Override
public void run() {
ApplicationContext ctx = ApplicationContext.getInstance();
LOGGER.debug("Starting resolution process on {}...",new Date());
try(WriteSession session=ctx.createSession()) {
ResourceSnapshot snapshot=
session.find(
ResourceSnapshot.class,
this.name,
DynamicResourceHandler.class);
DataSet dataSet = this.handler.get(snapshot);
Individual<?,?> individual =
dataSet.
individualOfId(ManagedIndividualId.createId(snapshot.name(),snapshot.templateId()));
SnapshotResolver snapshotResolver =
SnapshotResolver.
builder().
withReadSession(session).
withCanonicalBase(CANONICAL_BASE).
build();
URI snapshotEndpoint = snapshotResolver.toURI(snapshot);
individual.
addValue(
SNAPSHOT_ENDPOINT,
Literals.newLiteral(snapshotEndpoint));
individual.
addValue(
SNAPSHOT_RESOLUTION,
Literals.newLiteral(roundtrip(snapshotResolver,snapshotEndpoint,snapshot)));
this.handler.update(this.name, dataSet);
session.modify(snapshot);
session.saveChanges();
} catch (Exception e) {
LOGGER.error("Could not resolve resource",e);
} finally {
LOGGER.debug("Finalized resolution process");
}
} | java | {
"resource": ""
} |
q169502 | ImmutableTerm.compareTo | validation | @Override
public int compareTo(Term other) {
ImmutableTerm self = this;
if(self.getDeclaringVocabulary() != other.getDeclaringVocabulary()) {
throw new ClassCastException();
}
return self.ordinal - other.ordinal();
} | java | {
"resource": ""
} |
q169503 | NameProvider.pendingAttachmentNames | validation | public List<Name<String>> pendingAttachmentNames(String attachmentId) {
List<Name<String>> result = new ArrayList<Name<String>>();
NameSource source = this.attachmentNameSources.get(attachmentId);
if(source!=null) {
result.addAll(source.pendingNames);
}
return result;
} | java | {
"resource": ""
} |
q169504 | NameProvider.addAttachmentName | validation | public void addAttachmentName(String attachmentId, Name<String> nextName) {
nameSource(attachmentId).addName(nextName);
} | java | {
"resource": ""
} |
q169505 | NameProvider.nextAttachmentName | validation | public Name<String> nextAttachmentName(String attachmentId) {
NameSource result = this.attachmentNameSources.get(attachmentId);
if(result==null) {
result=new NameSource("attachment <<"+attachmentId+">>");
}
return result.nextName();
} | java | {
"resource": ""
} |
q169506 | NameProvider.create | validation | public static NameProvider create(Name<String> resource) {
Objects.requireNonNull(resource,"Owner name cannot be null");
return new NameProvider(resource);
} | java | {
"resource": ""
} |
q169507 | ImmutableMediaType.parseSuffix | validation | private static void parseSuffix(final MediaRange mr, final String mediaType) {
final String subType=mr.subType;
final int plusIdx=subType.lastIndexOf('+');
if(plusIdx==0) {
throw new InvalidMediaTypeException(mediaType,"missing subtype for structured media type ("+subType.substring(1)+")");
} else if(plusIdx==subType.length()-1) {
throw new InvalidMediaTypeException(mediaType,"missing suffix for structured media type ("+subType.substring(0,subType.length()-1)+")");
} else if(plusIdx>0) {
mr.subType=subType.substring(0,plusIdx);
mr.suffix=subType.substring(plusIdx+1);
} // Otherwise the subtype does not define a structuring syntax.
} | java | {
"resource": ""
} |
q169508 | ImmutableMediaType.checkQuotedString | validation | private static void checkQuotedString(final String quotedString) {
boolean quotedPair=false;
for(int i=0;i<quotedString.length();i++) {
final char ch=quotedString.charAt(i);
if(quotedPair) {
checkArgument(QUOTED_PAIR.get(ch),"Invalid quoted-pair character '%s' in quoted string '%s' at %d",ch,quotedString ,i);
quotedPair=false;
} else if(ch==SLASH) {
quotedPair=true;
} else {
checkArgument(QDTEXT.get(ch),"Invalid character '%s' in quoted string '%s' at %d",ch,quotedString ,i);
}
}
checkArgument(!quotedPair,"Missing quoted-pair character in quoted string '%s' at %d",quotedString,quotedString.length());
} | java | {
"resource": ""
} |
q169509 | CodePointIterator.next | validation | @Override
public Integer next() {
if(!hasNext()) {
throw new NoSuchElementException("No more codepoints available in the CharSequence");
}
this.index=this.next;
final Integer codePoint = Character.codePointAt(this.s, this.next);
this.next+=Character.charCount(codePoint);
return codePoint;
} | java | {
"resource": ""
} |
q169510 | DynamicResourceUpdater.run | validation | @Override
public void run() {
ApplicationContext ctx = ApplicationContext.getInstance();
Date date = new Date();
LOGGER.debug("Starting update process on {}...",date);
try(WriteSession session = ctx.createSession()) {
ResourceSnapshot snapshot = session.find(ResourceSnapshot.class,this.name,DynamicResourceHandler.class);
DataSet dataSet = this.handler.get(snapshot);
Individual<?,?> individual =
dataSet.
individualOfId(
ManagedIndividualId.
createId(this.name, DynamicResourceHandler.ID));
individual.
addValue(
REFRESHED_ON,
Literals.of(date).dateTime());
this.handler.update(this.name, dataSet);
session.modify(snapshot);
session.saveChanges();
} catch (Exception e) {
LOGGER.error("Could not update resource",e);
} finally {
LOGGER.debug("Finalized update process");
}
} | java | {
"resource": ""
} |
q169511 | URIRef.toURI | validation | URI toURI() {
StringBuilder builder=new StringBuilder();
if(defined(this.scheme)) {
builder.append(this.scheme);
builder.append(":");
}
if(defined(this.authority)) {
builder.append("//");
builder.append(this.authority);
}
if(defined(this.path)) {
builder.append(this.path);
}
if(defined(this.query)) {
builder.append("?");
builder.append(this.query);
}
if(defined(this.fragment)) {
builder.append("#");
builder.append(this.fragment);
}
String rawURI = builder.toString();
return URI.create(rawURI);
} | java | {
"resource": ""
} |
q169512 | RuntimeInstance.closeQuietly | validation | private static void closeQuietly(final InputStream is, final String message) {
if(is!=null) {
try {
is.close();
} catch (final Exception e) {
if(LOGGER.isWarnEnabled()) {
LOGGER.warn(message,e);
}
}
}
} | java | {
"resource": ""
} |
q169513 | Characters.isNameStartChar | validation | static boolean isNameStartChar(final int codePoint) {
return
(codePoint == ':') ||
(codePoint >= 'A' && codePoint <= 'Z') ||
(codePoint == '_') ||
(codePoint >= 'a' && codePoint <= 'z') ||
(codePoint >= 0xC0 && codePoint <= 0xD6) ||
(codePoint >= 0xD8 && codePoint <= 0xF6) ||
(codePoint >= 0xF8 && codePoint <= 0x2FF) ||
(codePoint >= 0x370 && codePoint <= 0x37D) ||
(codePoint >= 0x37F && codePoint <= 0x1FFF) ||
(codePoint >= 0x200C && codePoint <= 0x200D) ||
(codePoint >= 0x2070 && codePoint <= 0x218F) ||
(codePoint >= 0x2C00 && codePoint <= 0x2FEF) ||
(codePoint >= 0x3001 && codePoint <= 0xD7FF) ||
(codePoint >= 0xF900 && codePoint <= 0xFDCF) ||
(codePoint >= 0xFDF0 && codePoint <= 0xFFFD) ||
(codePoint >= 0x10000 && codePoint <= 0xEFFFF);
} | java | {
"resource": ""
} |
q169514 | Characters.isNameChar | validation | static boolean isNameChar(final int codePoint) {
return
isNameStartChar(codePoint) ||
(codePoint == '-') ||
(codePoint == '.') ||
(codePoint >= '0' && codePoint <= '9') ||
(codePoint == 0xB7) ||
(codePoint >= 0x0300 && codePoint <= 0x036F) ||
(codePoint >= 0x203F && codePoint <= 0x2040);
} | java | {
"resource": ""
} |
q169515 | HttpUtils.checkToken | validation | static void checkToken(final String token, final String message, Object... args) {
checkNotNull(message,"Message cannot be null");
try {
validateLength(token);
validateCharacters(token);
} catch (IllegalArgumentException e) {
throw new InvalidTokenException(String.format(message,args),token,e);
}
} | java | {
"resource": ""
} |
q169516 | DataTransformator.mediaType | validation | public DataTransformator mediaType(MediaType mediaType) {
checkNotNull(mediaType,MEDIA_TYPE_CANNOT_BE_NULL);
DataTransformator result = new DataTransformator(this);
result.setMediaType(mediaType);
return result;
} | java | {
"resource": ""
} |
q169517 | TypeAdapter.registerAdapterClass | validation | static void registerAdapterClass(Class<?> clazz) {
Objects.requireNonNull(clazz,"Adapter class cannot be null");
TypeAdapter.ADAPTER_CLASSES.addIfAbsent(clazz);
} | java | {
"resource": ""
} |
q169518 | TypeAdapter.createAdapter | validation | static <S,T> TypeAdapter<S,T> createAdapter(Class<? extends S> sourceType, Class<? extends T> targetType) {
return doCreateAdapter(targetType,AdapterMethodValidator.newInstance(targetType, sourceType));
} | java | {
"resource": ""
} |
q169519 | TypeAdapter.adapt | validation | static <S,T> T adapt(S object, Class<? extends T> resultClass) {
return TypeAdapter.<S,T>doCreateAdapter(resultClass, AdapterMethodValidator.newInstance(resultClass, object)).adapt(object);
} | java | {
"resource": ""
} |
q169520 | ImmutableNamespaces.withPrefix | validation | public ImmutableNamespaces withPrefix(String prefix, String namespaceURI) {
Objects.requireNonNull(prefix, "Prefix cannot be null");
Objects.requireNonNull(namespaceURI, "Namespace URI cannot be null");
ImmutableNamespaces result=new ImmutableNamespaces(this.map);
result.map.put(prefix, namespaceURI);
return result;
} | java | {
"resource": ""
} |
q169521 | ImmutableNamespaces.withoutPrefix | validation | public ImmutableNamespaces withoutPrefix(String... prefixes) {
ImmutableNamespaces result=new ImmutableNamespaces(this.map);
for(String prefix:prefixes) {
result.map.remove(prefix);
}
return result;
} | java | {
"resource": ""
} |
q169522 | XMLUtils.escapeXML | validation | public static String escapeXML(final CharSequence s) {
final StringBuilder sb = new StringBuilder(s.length() * 2);
final CodePointIterator iterator = new CodePointIterator(s);
while (iterator.hasNext()) {
final int codePoint = iterator.next();
if (codePoint == '<') {
sb.append(LT);
} else if (codePoint == '>') {
sb.append(GT);
} else if (codePoint == '\"') {
sb.append(QUOT);
} else if (codePoint == '&') {
sb.append(AMP);
} else if (codePoint == '\'') {
sb.append(APOS);
} else {
sb.appendCodePoint(codePoint);
}
}
return sb.toString();
} | java | {
"resource": ""
} |
q169523 | QueryableResourceHandler.query | validation | @Override
public DataSet query(ResourceSnapshot resource, Query query, ReadSession session) throws InvalidQueryException {
return QuerySupport.getDescription(resource.name(), query);
} | java | {
"resource": ""
} |
q169524 | InMemoryContainerHandler.addNameProvider | validation | public final void addNameProvider(Name<String> containerName, NameProvider provider) {
this.nameProviders.put(containerName, provider);
} | java | {
"resource": ""
} |
q169525 | InMemoryContainerHandler.nameProvider | validation | public final NameProvider nameProvider(Name<?> containerName) {
NameProvider result = this.nameProviders.get(containerName);
if(result==null) {
throw new ApplicationRuntimeException("Unknown container '"+containerName+"'");
}
return result;
} | java | {
"resource": ""
} |
q169526 | ApplicationEngine.unwrap | validation | public <T> T unwrap(final Class<? extends T> clazz) throws ApplicationEngineException {
checkNotNull(clazz,"Target class cannot be null");
if(!clazz.isInstance(this)) {
throw new ApplicationEngineException("Application Engine implementation is not compatible with "+clazz.getCanonicalName());
}
return clazz.cast(this);
} | java | {
"resource": ""
} |
q169527 | Path.isOutOfScope | validation | public boolean isOutOfScope() {
// Files are always on scope
if(this.directory==null) {
return false;
}
// First, normalize
final Path normalize=normalize();
// If now we are a file, we are in scope
if(normalize.directory==null) {
return false;
}
// If we find a segment which is '..' we are out of scope
final String[] segments=normalize.segments();
boolean result=false;
for(int i=0;i<segments.length && !result;i++) {
result=isDotSegment(segments[i]);
}
return result;
} | java | {
"resource": ""
} |
q169528 | Path.withDirectory | validation | public Path withDirectory(final String directory) {
final Path result = new Path(this);
result.setDirectory(directory);
return result;
} | java | {
"resource": ""
} |
q169529 | Path.withFile | validation | public Path withFile(final String file) {
final Path result = new Path(this);
result.setFile(file);
return result;
} | java | {
"resource": ""
} |
q169530 | Path.assembleRelativeSegments | validation | private Path assembleRelativeSegments(final Path path, final Path base, final Deque<String> segments) {
if(segments.isEmpty() && path.isDirectory() && base.isFile()) {
segments.add(CURRENT);
}
return Path.create(assembleSegments(segments,path.getFile()));
} | java | {
"resource": ""
} |
q169531 | Generics.getTypeParameter | validation | static <T> Class<T> getTypeParameter(Class<?> clazz, Class<? super T> bound) {
Type t = checkNotNull(clazz);
while (t instanceof Class<?>) {
t = ((Class<?>) t).getGenericSuperclass();
}
/**
* This is not guaranteed to work for all cases with convoluted piping
* of type parameters: but it can at least resolve straight-forward
* extension with single type parameter (as per [Issue-89]). And when it
* fails to do that, will indicate with specific exception.
*/
if(t instanceof ParameterizedType) {
Class<T> result=processParameterizedType(bound, (ParameterizedType) t);
if(result!=null) {
return result;
}
}
throw new IllegalStateException("Cannot figure out type parameterization for "+ clazz.getName());
} | java | {
"resource": ""
} |
q169532 | PrimitiveObjectFactory.create | validation | public static <T> PrimitiveObjectFactory<T> create(final Class<? extends T> valueClass) {
checkNotNull(valueClass, "Value class cannot be null");
checkArgument(valueClass.isPrimitive(), "Value class '" + valueClass.getName() + "' is not primitive");
return new PrimitiveObjectFactory<T>(valueClass);
} | java | {
"resource": ""
} |
q169533 | VariantUtils.createVariants | validation | public static List<Variant> createVariants(MediaType... mediaTypes) {
return
Variant.VariantListBuilder.
newInstance().
mediaTypes(mediaTypes).
encodings().
languages().
add().
build();
} | java | {
"resource": ""
} |
q169534 | IndividualReference.resolve | validation | @SuppressWarnings("unchecked")
public Individual<T,S> resolve(DataSet dataSet) {
return (Individual<T,S>) dataSet.individualOfId(ref());
} | java | {
"resource": ""
} |
q169535 | ViewGroupComparison.equalChildrenCountAs | validation | @Factory
public static <T extends ViewGroup> Matcher<T> equalChildrenCountAs(int value) {
return new ViewGroupComparison<T>(value, EQUAL, EQUAL);
} | java | {
"resource": ""
} |
q169536 | ViewGroupComparison.moreChildrenThan | validation | @Factory
public static <T extends ViewGroup> Matcher<T> moreChildrenThan(int value) {
return new ViewGroupComparison<T>(value, GREATER_THAN, GREATER_THAN);
} | java | {
"resource": ""
} |
q169537 | ViewGroupComparison.moreChildrenOrEqual | validation | @Factory
public static <T extends ViewGroup> Matcher<T> moreChildrenOrEqual(int value) {
return new ViewGroupComparison<T>(value, EQUAL, GREATER_THAN);
} | java | {
"resource": ""
} |
q169538 | ViewGroupComparison.lessChildrenThan | validation | @Factory
public static <T extends ViewGroup> Matcher<T> lessChildrenThan(int value) {
return new ViewGroupComparison<T>(value, LESS_THAN, LESS_THAN);
} | java | {
"resource": ""
} |
q169539 | ViewGroupComparison.lessChildrenOrEqual | validation | @Factory
public static <T extends ViewGroup> Matcher<T> lessChildrenOrEqual(int value) {
return new ViewGroupComparison<T>(value, LESS_THAN, EQUAL);
} | java | {
"resource": ""
} |
q169540 | MeasureClass.getMeasuresByYearState | validation | public Measures getMeasuresByYearState(String year, String stateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Measure.getMeasuresByYearState", new ArgMap("year", year, "stateId", stateId), Measures.class );
} | java | {
"resource": ""
} |
q169541 | MeasureClass.getMeasure | validation | public Measure getMeasure(String measureId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Measure.getMeasure", new ArgMap("measureId", measureId), Measure.class );
} | java | {
"resource": ""
} |
q169542 | RatingClass.getCandidateRating | validation | public CandidateRating getCandidateRating(String candidateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Rating.getCandidateRating", new ArgMap("candidateId", candidateId), CandidateRating.class );
} | java | {
"resource": ""
} |
q169543 | RatingClass.getRating | validation | public Rating getRating(String ratingId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Rating.getRating", new ArgMap("ratingId", ratingId), Rating.class );
} | java | {
"resource": ""
} |
q169544 | ElectionClass.getElectionByYearState | validation | public Elections getElectionByYearState(String year) throws VoteSmartException, VoteSmartErrorException {
return api.query("Election.getElectionByYearState", new ArgMap("year", year), Elections.class );
} | java | {
"resource": ""
} |
q169545 | ElectionClass.getElectionByZip | validation | public ElectionByZip getElectionByZip(String zip5) throws VoteSmartException, VoteSmartErrorException {
return api.query("Election.getElectionByZip", new ArgMap("zip5", zip5), ElectionByZip.class );
} | java | {
"resource": ""
} |
q169546 | ElectionClass.getStageCandidates | validation | public StageCandidates getStageCandidates(String electionId, String stageId, String party) throws VoteSmartException, VoteSmartErrorException {
return api.query("Election.getStageCandidates", new ArgMap("electionId", electionId, "stageId", stageId, "party", party), StageCandidates .class );
} | java | {
"resource": ""
} |
q169547 | AddressClass.getOfficeByOfficeState | validation | public AddressAddress getOfficeByOfficeState(String officeId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Address.getOfficeByOfficeState", new ArgMap("officeId", officeId), AddressAddress.class );
} | java | {
"resource": ""
} |
q169548 | OfficeClass.getOfficesByType | validation | public Offices getOfficesByType(String officeTypeId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Office.getOfficesByType", new ArgMap("officeTypeId", officeTypeId), Offices.class );
} | java | {
"resource": ""
} |
q169549 | OfficeClass.getOfficesByLevel | validation | public Offices getOfficesByLevel(String levelId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Office.getOfficesByLevel", new ArgMap("levelId", levelId), Offices.class );
} | java | {
"resource": ""
} |
q169550 | OfficeClass.getOfficesByTypeLevel | validation | public Offices getOfficesByTypeLevel(String officeTypeId, String officeLevelId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Office.getOfficesByTypeLevel", new ArgMap("officeTypeId", officeTypeId, "officeLevelId", officeLevelId), Offices.class );
} | java | {
"resource": ""
} |
q169551 | OfficeClass.getOfficesByBranchLevel | validation | public Offices getOfficesByBranchLevel(String branchId, String levelId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Office.getOfficesByBranchLevel", new ArgMap("branchId", branchId, "levelId", levelId), Offices.class );
} | java | {
"resource": ""
} |
q169552 | LocalClass.getCounties | validation | public Counties getCounties(String stateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Local.getCounties", new ArgMap("stateId", stateId), Counties.class );
} | java | {
"resource": ""
} |
q169553 | LocalClass.getCities | validation | public Cities getCities(String stateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Local.getCities", new ArgMap("stateId", stateId), Cities.class );
} | java | {
"resource": ""
} |
q169554 | LocalClass.getOfficials | validation | public LocalCandidateList getOfficials(String localId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Local.getOfficials", new ArgMap("localId", localId), LocalCandidateList.class );
} | java | {
"resource": ""
} |
q169555 | VoteSmart.query | validation | public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException {
BufferedReader reader = null;
HttpURLConnection conn = null;
String charSet = "utf-8";
try {
if ( isCaching(method, argMap) ) {
File file = getCacheFile(method, argMap);
long fileLength = file.length();
logger.fine("Length of File in cache:" + fileLength + ": " + file.getName());
if ( fileLength == 0L ) {
VoteSmart.cacheFileFromAPI(method, argMap, file);
}
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));
} else {
conn = VoteSmart.getConnectionFromAPI(method, argMap);
charSet = getCharset(conn);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charSet));
}
JAXBElement<T> e = unmarshaller.unmarshal( new StreamSource( reader ), responseType );
if ( e.getName().getLocalPart().equals("error") ) {
// ErrorBase error = unmarshaller.unmarshal( new StreamSource( reader = new StringReader(XMLStr) ), ErrorBase.class ).getValue();
throw new VoteSmartErrorException( ((ErrorBase)e.getValue()), method, argMap );
} else {
return e.getValue();
}
/*
Object o = unmarshaller.unmarshal( new StreamSource( reader ) );
if ( o instanceof ErrorBase ) {
throw new VoteSmartErrorException((ErrorBase) o, method, argMap);
} else {
@SuppressWarnings("unchecked")
T e = (T) o;
return e;
}
*/
} catch ( JAXBException e ) {
throw new VoteSmartException(e);
} catch (URISyntaxException e) {
throw new VoteSmartException(e);
} catch (IOException e) {
throw new VoteSmartException(e);
} finally {
suspendCache = false;
if ( conn != null ) conn.disconnect();
if ( reader != null ) {
try {
reader.close();
} catch (IOException e) {
throw new VoteSmartException(e);
}
}
}
} | java | {
"resource": ""
} |
q169556 | OfficialsClass.getStatewide | validation | public CandidateList getStatewide(String stateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Officials.getStatewide", new ArgMap("stateId", stateId), CandidateList.class );
} | java | {
"resource": ""
} |
q169557 | OfficialsClass.getByOfficeTypeState | validation | public CandidateList getByOfficeTypeState(String officeTypeId, String stateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Officials.getByOfficeTypeState", new ArgMap("officeTypeId", officeTypeId, "stateId", stateId), CandidateList.class );
} | java | {
"resource": ""
} |
q169558 | OfficialsClass.getByZip | validation | public CandidateList getByZip(String zip5) throws VoteSmartException, VoteSmartErrorException {
return api.query("Officials.getByZip", new ArgMap("zip5", zip5), CandidateList.class );
} | java | {
"resource": ""
} |
q169559 | CandidateBioClass.getAddlBio | validation | public AddlBio getAddlBio(String candidateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("CandidateBio.getAddlBio", new ArgMap("candidateId", candidateId), AddlBio.class );
} | java | {
"resource": ""
} |
q169560 | CandidateBioClass.getBio | validation | public Bio getBio(String candidateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("CandidateBio.getDetailedBio", new ArgMap("candidateId", candidateId), Bio.class );
} | java | {
"resource": ""
} |
q169561 | CandidatesClass.getByLastname | validation | public CandidateList getByLastname(String lastName, String electionYear) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByLastname", new ArgMap("lastName", lastName, "electionYear", electionYear), CandidateList.class );
} | java | {
"resource": ""
} |
q169562 | CandidatesClass.getByElection | validation | public CandidateList getByElection(String electionId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByElection", new ArgMap("electionId", electionId), CandidateList.class );
} | java | {
"resource": ""
} |
q169563 | CandidatesClass.getByDistrict | validation | public CandidateList getByDistrict(String districtId, String electionYear) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByDistrict", new ArgMap("districtId", districtId, "electionYear", electionYear), CandidateList.class );
} | java | {
"resource": ""
} |
q169564 | CommitteeClass.getCommitteesByTypeState | validation | public Committees getCommitteesByTypeState(String typeId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Committee.getCommitteesByTypeState", new ArgMap("typeId", typeId), Committees.class );
} | java | {
"resource": ""
} |
q169565 | CommitteeClass.getCommittee | validation | public Committee getCommittee(String committeeId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Committee.getCommittee", new ArgMap("committeeId", committeeId), Committee.class );
} | java | {
"resource": ""
} |
q169566 | CommitteeClass.getCommitteeMembers | validation | public CommitteeMembers getCommitteeMembers(String committeeId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Committee.getCommitteeMembers", new ArgMap("committeeId", committeeId), CommitteeMembers.class );
} | java | {
"resource": ""
} |
q169567 | LeadershipClass.getPositions | validation | public Leadership getPositions(String stateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Leadership.getPositions", new ArgMap("stateId", stateId), Leadership.class );
} | java | {
"resource": ""
} |
q169568 | LeadershipClass.getOfficials | validation | public Leaders getOfficials(String leadershipId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Leadership.getOfficials", new ArgMap("leadershipId", leadershipId), Leaders.class );
} | java | {
"resource": ""
} |
q169569 | SleepWakeup.sleep | validation | public static void sleep(int ms) {
long deadline = System.currentTimeMillis() + ms;
while (System.currentTimeMillis() < deadline) {
try {
Thread.sleep(Math.max(1, (deadline - System.currentTimeMillis()) / 2));
} catch (InterruptedException ignore) {}
}
} | java | {
"resource": ""
} |
q169570 | RealTimeTickSource.start | validation | public void start() {
if (timer != null)
throw new IllegalStateException("already running");
if (interval < BUSY_WAITING_THRESHOLD)
timer = new MyBusyTimer();
else if (interval < MILLISECOND_THRESHOLD)
timer = new MyWaitingTimer();
else
timer = new MyMillisecondTimer();
Thread thread = new Thread(timer, "timer");
thread.setDaemon(true);
thread.start();
} | java | {
"resource": ""
} |
q169571 | StreamGobbler.waitFor | validation | public void waitFor() throws Throwable {
while (!finished) {
try {
synchronized (this) {
this.wait(100);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (t != null)
throw t;
} | java | {
"resource": ""
} |
q169572 | StreamGobbler.close | validation | public void close() {
cancel = true;
try {
thread.interrupt();
waitFor();
} catch (Throwable ignore) {}
try {
is.close();
} catch (Exception ignore) {}
try {
os.close();
} catch (Exception ignore) {}
} | java | {
"resource": ""
} |
q169573 | MapUtils.merge | validation | public static <K, V, M extends Map<K, V>> M merge(Stream<? extends Map<K, V>> stream,
BinaryOperator<V> mergeFunction,
Supplier<M> mapSupplier) {
Assert.notNull(stream, "Missing map merge function!");
Assert.notNull(mergeFunction, "Missing map merge function!");
Assert.notNull(mapSupplier, "Missing map supplier!");
return stream.collect(mapSupplier,
(a, b) -> b.forEach((k, v) -> a.merge(k, v, mergeFunction)),
Map::putAll);
} | java | {
"resource": ""
} |
q169574 | MapUtils.split | validation | public static <K, V> List<Map<K, V>> split(Map<K, V> map, int limit) {
Assert.notNull(map, "Missing map!");
Assert.isTrue(limit > 0, "Map limit must be > 0!");
if (map.size() <= limit) {
return Collections.singletonList(map); // nothing to do
}
return map.entrySet().parallelStream().collect(mapSizer(limit));
} | java | {
"resource": ""
} |
q169575 | MapUtils.mapSizer | validation | private static <K, V> Collector<Map.Entry<K, V>, ?, List<Map<K, V>>> mapSizer(int limit) {
return Collector.of(ArrayList::new,
(l, e) -> {
if (l.isEmpty() || l.get(l.size() - 1).size() == limit) {
l.add(new HashMap<>());
}
l.get(l.size() - 1).put(e.getKey(), e.getValue());
},
(l1, l2) -> {
if (l1.isEmpty()) {
return l2;
}
if (l2.isEmpty()) {
return l1;
}
if (l1.get(l1.size() - 1).size() < limit) {
Map<K, V> map = l1.get(l1.size() - 1);
ListIterator<Map<K, V>> mapsIte = l2.listIterator(l2.size());
while (mapsIte.hasPrevious() && map.size() < limit) {
Iterator<Map.Entry<K, V>> ite = mapsIte.previous().entrySet().iterator();
while (ite.hasNext() && map.size() < limit) {
Map.Entry<K, V> entry = ite.next();
map.put(entry.getKey(), entry.getValue());
ite.remove();
}
if (!ite.hasNext()) {
mapsIte.remove();
}
}
}
l1.addAll(l2);
return l1;
}
);
} | java | {
"resource": ""
} |
q169576 | MapUtils.sort | validation | public static <K, V> Map<K, V> sort(Map<K, V> map, Comparator<Map.Entry<K, V>> comparator) {
Assert.notNull(map, "Missing map!");
Assert.notNull(comparator, "Missing comparator!");
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, comparator);
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
} | java | {
"resource": ""
} |
q169577 | MapUtils.firstValue | validation | public static <T> T firstValue(Map<String, T> map) {
if (map == null || map.size() == 0) {
return null;
}
String firstKey = map.keySet().iterator().next();
return map.get(firstKey);
} | java | {
"resource": ""
} |
q169578 | Assert.isNull | validation | public static <T> void isNull(T test, String message) {
isTrue(test == null, message);
} | java | {
"resource": ""
} |
q169579 | Assert.notNull | validation | public static <T> void notNull(T test, String message) {
isFalse(test == null, message);
} | java | {
"resource": ""
} |
q169580 | Assert.notNullOrEmptyTrimmed | validation | public static void notNullOrEmptyTrimmed(String value, String message) {
isFalse(StringUtils.isNullOrEmptyTrimmed(value), message);
} | java | {
"resource": ""
} |
q169581 | Assert.isNullOrEmpty | validation | public static <T> void isNullOrEmpty(Set<T> set, String message) {
isTrue(set == null || set.size() == 0, message);
} | java | {
"resource": ""
} |
q169582 | Assert.isNullOrEmpty | validation | public static <T> void isNullOrEmpty(T[] array, String message) {
isTrue(array == null || array.length == 0, message);
} | java | {
"resource": ""
} |
q169583 | ResourceUtils.getResourceAsString | validation | @Deprecated
public static String getResourceAsString(String resourceFile, Class clazz) {
Assert.notNullOrEmptyTrimmed(resourceFile, "Missing resource file!");
Scanner scanner = null;
try {
InputStream resource = clazz.getResourceAsStream(resourceFile);
scanner = new Scanner(resource, UTF_8);
return scanner.useDelimiter("\\A").next();
}
catch (Exception e) {
return null;
}
finally {
if (scanner != null) {
scanner.close();
}
}
} | java | {
"resource": ""
} |
q169584 | ResourceUtils.getResourceWords | validation | public static Set<String> getResourceWords(String resourceFile, Class clazz) {
Assert.notNullOrEmptyTrimmed(resourceFile, "Missing resource file!");
Scanner scanner = null;
try {
InputStream resource = clazz.getResourceAsStream(resourceFile);
scanner = new Scanner(resource, UTF_8);
Set<String> list = new LinkedHashSet<>();
while (scanner.hasNext()) {
String next = scanner.next();
if (next != null && next.trim().length() > 0) {
list.add(next);
}
}
return list;
}
catch (Exception e) {
return null;
}
finally {
if (scanner != null) {
scanner.close();
}
}
} | java | {
"resource": ""
} |
q169585 | ResourceUtils.getLastModifiedTime | validation | @Deprecated
public static Long getLastModifiedTime(String resourceFile, Class clazz) {
Assert.notNullOrEmptyTrimmed(resourceFile, "Missing resource file!");
try {
URL url = clazz.getResource(resourceFile);
return url.openConnection().getLastModified(); // get last modified date of resource
}
catch (IOException e) {
return null;
}
} | java | {
"resource": ""
} |
q169586 | ResourceUtils.getString | validation | public static String getString(final InputStream is, String encoding) {
if (is == null) {
return null;
}
if (StringUtils.isNullOrEmptyTrimmed(encoding)) {
encoding = UTF_8;
}
final char[] buffer = new char[BUFFER_SIZE];
final StringBuilder out = new StringBuilder();
try {
try (Reader in = new InputStreamReader(is, encoding)) {
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0) {
break;
}
out.append(buffer, 0, rsz);
}
}
}
catch (IOException ioe) {
throw new RuntimeException(ioe);
}
return out.toString();
} | java | {
"resource": ""
} |
q169587 | ResourceUtils.getBytes | validation | public static byte[] getBytes(InputStream is) {
if (is == null) {
return null;
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[BUFFER_SIZE];
try {
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
}
catch (IOException ignored) {
}
return buffer.toByteArray();
} | java | {
"resource": ""
} |
q169588 | ResourceUtils.readFileToString | validation | public static String readFileToString(File file) throws IOException {
Assert.isTrue(file.exists(), "File '" + file + "' does not exist");
Assert.isFalse(file.isDirectory(), "File '" + file + "' is a directory");
Assert.isTrue(file.canRead(), "File '" + file + "' cannot be read");
FileInputStream stream = new FileInputStream(file);
return getString(stream);
} | java | {
"resource": ""
} |
q169589 | ResourceUtils.getResourceAbsolutePath | validation | @Deprecated
public static String getResourceAbsolutePath(String resource, Class clazz) {
Assert.notNullOrEmptyTrimmed(resource, "Missing resource name!");
URL file = clazz.getResource(resource);
Assert.notNull(file, "Resource: '" + resource + "', not found!");
return file.getFile();
} | java | {
"resource": ""
} |
q169590 | KeyGenerator.generateString | validation | public static String generateString(int length) {
if (length <= 0 || length > 100) {
throw new IllegalArgumentException("Can't generate random id with length: " + length);
}
SecureRandom random = new SecureRandom();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(ELEMENTS.charAt(random.nextInt(ELEMENTS.length())));
}
return sb.toString();
} | java | {
"resource": ""
} |
q169591 | KeyGenerator.generateLong | validation | public static long generateLong(int length) {
if (length <= 0 || length > 19) {
throw new IllegalArgumentException("Can't generate random id with length: " + length);
}
SecureRandom random = new SecureRandom();
StringBuilder sb = new StringBuilder(length);
// 1st digit should not be a 0 or 9 if desired length is 19 (as max long is: 9223372036854775807)
if (length == 19) {
sb.append(NUMBERS_NO_NINE_AND_ZERO.charAt(random.nextInt(NUMBERS_NO_NINE_AND_ZERO.length())));
}
else {
sb.append(NUMBERS_NO_ZERO.charAt(random.nextInt(NUMBERS_NO_ZERO.length())));
}
// all other digits can contain a 0
for (int i = 1; i < length; i++) {
sb.append(NUMBERS.charAt(random.nextInt(NUMBERS.length())));
}
return Long.parseLong(sb.toString());
} | java | {
"resource": ""
} |
q169592 | ArrayUtils.join | validation | @SafeVarargs
public static <T> T[] join(final T[] array1, final T... array2) {
if (isEmpty(array1) && isEmpty(array2)) {
return null;
}
if (isEmpty(array1)) {
return array2;
}
if (isEmpty(array2)) {
return array1;
}
final Class<?> type1 = array1.getClass().getComponentType();
@SuppressWarnings("unchecked") // OK, because array is of type T
final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
int index = 0;
for (T item : array1) {
joinedArray[index++] = item;
}
for (T item : array2) {
joinedArray[index++] = item;
}
return joinedArray;
} | java | {
"resource": ""
} |
q169593 | SetUtils.split | validation | public static <T> List<Set<T>> split(Set<T> set, int maxSize) {
Assert.notNull(set, "Missing set to be split!");
Assert.isTrue(maxSize > 0, "Max size must be > 0!");
if (set.size() < maxSize) {
return Collections.singletonList(set);
}
List<Set<T>> list = new ArrayList<>();
Iterator<T> iterator = set.iterator();
while (iterator.hasNext()) {
Set<T> newSet = new HashSet<>();
for (int j = 0; j < maxSize && iterator.hasNext(); j++) {
T item = iterator.next();
newSet.add(item);
}
list.add(newSet);
}
return list;
} | java | {
"resource": ""
} |
q169594 | InstantTimeUtils.getMonthStart | validation | public static Instant getMonthStart(Instant time) {
Assert.notNull(time, "Missing date time");
LocalDateTime dateTime = LocalDateTime.ofInstant(time, ZoneOffset.UTC);
dateTime = dateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).with(ChronoField.MILLI_OF_SECOND, 0);
return dateTime.toInstant(ZoneOffset.UTC);
} | java | {
"resource": ""
} |
q169595 | InstantTimeUtils.getMonthEnd | validation | public static Instant getMonthEnd(Instant time) {
Assert.notNull(time, "Missing date time");
LocalDateTime dateTime = LocalDateTime.ofInstant(time, ZoneOffset.UTC);
dateTime = dateTime.withDayOfMonth(1).withHour(23).withMinute(59).withSecond(59).with(ChronoField.MILLI_OF_SECOND, 999);
dateTime = dateTime.plus(1, ChronoUnit.MONTHS).minus(1, ChronoUnit.DAYS);
return dateTime.toInstant(ZoneOffset.UTC);
} | java | {
"resource": ""
} |
q169596 | StringUtils.trimToNull | validation | public static String trimToNull(String text) {
text = trim(text);
if (text == null || text.isEmpty()) {
return null;
}
return text;
} | java | {
"resource": ""
} |
q169597 | StringUtils.capitalize | validation | public static String capitalize(String input) {
if (input == null) {
return null;
}
if (input.length() > 1) {
for (int i = 0; i < input.length(); i++) {
if (Character.isAlphabetic(input.charAt(i))) {
return input.substring(0, i) + Character.toString(input.charAt(i)).toUpperCase() + input.substring(i + 1);
}
}
}
return input.toUpperCase();
} | java | {
"resource": ""
} |
q169598 | StringUtils.join | validation | public static String join(Object[] args, String separator) {
return join(args, separator, null);
} | java | {
"resource": ""
} |
q169599 | StringUtils.join | validation | public static String join(Set<?> items, String separator) {
return join(items, separator, null);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.