_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q19700 | Configuration.set | train | public <T> void set(String key, T value) {
Preconditions.checkArgument(key != null && !key.isEmpty(), "Parameter 'key' must not be [" + key + "]");
values.put(key, value);
scope.put(key, scope, value);
} | java | {
"resource": ""
} |
q19701 | AbstractUPCEAN.calcChecksumChar | train | protected static char calcChecksumChar (@Nonnull final String sMsg, @Nonnegative final int nLength)
{
ValueEnforcer.notNull (sMsg, "Msg");
ValueEnforcer.isBetweenInclusive (nLength, "Length", 0, sMsg.length ());
return asChar (calcChecksum (sMsg.toCharArray (), nLength));
} | java | {
"resource": ""
} |
q19702 | UnicodeReader.scanSurrogates | train | protected char scanSurrogates() {
if (surrogatesSupported && Character.isHighSurrogate(ch)) {
char high = ch;
scanChar();
if (Character.isLowSurrogate(ch)) {
return high;
}
ch = high;
}
return 0;
} | java | {
"resource": ""
} |
q19703 | EAN8.validateMessage | train | @Nonnull
public static EValidity validateMessage (@Nullable final String sMsg)
{
final int nLen = StringHelper.getLength (sMsg);
if (nLen >= 7 && nLen <= 8)
if (AbstractUPCEAN.validateMessage (sMsg).isValid ())
return EValidity.VALID;
return EValidity.INVALID;
} | java | {
"resource": ""
} |
q19704 | PubapiVisitor.makeMethodString | train | protected String makeMethodString(ExecutableElement e) {
StringBuilder result = new StringBuilder();
for (Modifier modifier : e.getModifiers()) {
result.append(modifier.toString());
result.append(" ");
}
result.append(e.getReturnType().toString());
result.append(" ");
result.append(e.toString());
List<? extends TypeMirror> thrownTypes = e.getThrownTypes();
if (!thrownTypes.isEmpty()) {
result.append(" throws ");
for (Iterator<? extends TypeMirror> iterator = thrownTypes
.iterator(); iterator.hasNext();) {
TypeMirror typeMirror = iterator.next();
result.append(typeMirror.toString());
if (iterator.hasNext()) {
result.append(", ");
}
}
}
return result.toString();
} | java | {
"resource": ""
} |
q19705 | PubapiVisitor.makeVariableString | train | protected String makeVariableString(VariableElement e) {
StringBuilder result = new StringBuilder();
for (Modifier modifier : e.getModifiers()) {
result.append(modifier.toString());
result.append(" ");
}
result.append(e.asType().toString());
result.append(" ");
result.append(e.toString());
Object value = e.getConstantValue();
if (value != null) {
result.append(" = ");
if (e.asType().toString().equals("char")) {
int v = (int)value.toString().charAt(0);
result.append("'\\u"+Integer.toString(v,16)+"'");
} else {
result.append(value.toString());
}
}
return result.toString();
} | java | {
"resource": ""
} |
q19706 | DeploymentCache.add | train | public void add(Collection<Deployment> deployments)
{
for(Deployment deployment : deployments)
this.deployments.put(deployment.getId(), deployment);
} | java | {
"resource": ""
} |
q19707 | Infer.generateReturnConstraints | train | Type generateReturnConstraints(JCTree tree, Attr.ResultInfo resultInfo,
MethodType mt, InferenceContext inferenceContext) {
InferenceContext rsInfoInfContext = resultInfo.checkContext.inferenceContext();
Type from = mt.getReturnType();
if (mt.getReturnType().containsAny(inferenceContext.inferencevars) &&
rsInfoInfContext != emptyContext) {
from = types.capture(from);
//add synthetic captured ivars
for (Type t : from.getTypeArguments()) {
if (t.hasTag(TYPEVAR) && ((TypeVar)t).isCaptured()) {
inferenceContext.addVar((TypeVar)t);
}
}
}
Type qtype = inferenceContext.asUndetVar(from);
Type to = resultInfo.pt;
if (qtype.hasTag(VOID)) {
to = syms.voidType;
} else if (to.hasTag(NONE)) {
to = from.isPrimitive() ? from : syms.objectType;
} else if (qtype.hasTag(UNDETVAR)) {
if (resultInfo.pt.isReference()) {
to = generateReturnConstraintsUndetVarToReference(
tree, (UndetVar)qtype, to, resultInfo, inferenceContext);
} else {
if (to.isPrimitive()) {
to = generateReturnConstraintsPrimitive(tree, (UndetVar)qtype, to,
resultInfo, inferenceContext);
}
}
}
Assert.check(allowGraphInference || !rsInfoInfContext.free(to),
"legacy inference engine cannot handle constraints on both sides of a subtyping assertion");
//we need to skip capture?
Warner retWarn = new Warner();
if (!resultInfo.checkContext.compatible(qtype, rsInfoInfContext.asUndetVar(to), retWarn) ||
//unchecked conversion is not allowed in source 7 mode
(!allowGraphInference && retWarn.hasLint(Lint.LintCategory.UNCHECKED))) {
throw inferenceException
.setMessage("infer.no.conforming.instance.exists",
inferenceContext.restvars(), mt.getReturnType(), to);
}
return from;
} | java | {
"resource": ""
} |
q19708 | Infer.instantiateAsUninferredVars | train | private void instantiateAsUninferredVars(List<Type> vars, InferenceContext inferenceContext) {
ListBuffer<Type> todo = new ListBuffer<>();
//step 1 - create fresh tvars
for (Type t : vars) {
UndetVar uv = (UndetVar)inferenceContext.asUndetVar(t);
List<Type> upperBounds = uv.getBounds(InferenceBound.UPPER);
if (Type.containsAny(upperBounds, vars)) {
TypeSymbol fresh_tvar = new TypeVariableSymbol(Flags.SYNTHETIC, uv.qtype.tsym.name, null, uv.qtype.tsym.owner);
fresh_tvar.type = new TypeVar(fresh_tvar, types.makeIntersectionType(uv.getBounds(InferenceBound.UPPER)), null);
todo.append(uv);
uv.inst = fresh_tvar.type;
} else if (upperBounds.nonEmpty()) {
uv.inst = types.glb(upperBounds);
} else {
uv.inst = syms.objectType;
}
}
//step 2 - replace fresh tvars in their bounds
List<Type> formals = vars;
for (Type t : todo) {
UndetVar uv = (UndetVar)t;
TypeVar ct = (TypeVar)uv.inst;
ct.bound = types.glb(inferenceContext.asInstTypes(types.getBounds(ct)));
if (ct.bound.isErroneous()) {
//report inference error if glb fails
reportBoundError(uv, BoundErrorKind.BAD_UPPER);
}
formals = formals.tail;
}
} | java | {
"resource": ""
} |
q19709 | Infer.instantiatePolymorphicSignatureInstance | train | Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env,
MethodSymbol spMethod, // sig. poly. method or null if none
Resolve.MethodResolutionContext resolveContext,
List<Type> argtypes) {
final Type restype;
//The return type for a polymorphic signature call is computed from
//the enclosing tree E, as follows: if E is a cast, then use the
//target type of the cast expression as a return type; if E is an
//expression statement, the return type is 'void' - otherwise the
//return type is simply 'Object'. A correctness check ensures that
//env.next refers to the lexically enclosing environment in which
//the polymorphic signature call environment is nested.
switch (env.next.tree.getTag()) {
case TYPECAST:
JCTypeCast castTree = (JCTypeCast)env.next.tree;
restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ?
castTree.clazz.type :
syms.objectType;
break;
case EXEC:
JCTree.JCExpressionStatement execTree =
(JCTree.JCExpressionStatement)env.next.tree;
restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ?
syms.voidType :
syms.objectType;
break;
default:
restype = syms.objectType;
}
List<Type> paramtypes = Type.map(argtypes, new ImplicitArgType(spMethod, resolveContext.step));
List<Type> exType = spMethod != null ?
spMethod.getThrownTypes() :
List.of(syms.throwableType); // make it throw all exceptions
MethodType mtype = new MethodType(paramtypes,
restype,
exType,
syms.methodClass);
return mtype;
} | java | {
"resource": ""
} |
q19710 | Infer.checkWithinBounds | train | void checkWithinBounds(InferenceContext inferenceContext,
Warner warn) throws InferenceException {
MultiUndetVarListener mlistener = new MultiUndetVarListener(inferenceContext.undetvars);
List<Type> saved_undet = inferenceContext.save();
try {
while (true) {
mlistener.reset();
if (!allowGraphInference) {
//in legacy mode we lack of transitivity, so bound check
//cannot be run in parallel with other incoprporation rounds
for (Type t : inferenceContext.undetvars) {
UndetVar uv = (UndetVar)t;
IncorporationStep.CHECK_BOUNDS.apply(uv, inferenceContext, warn);
}
}
for (Type t : inferenceContext.undetvars) {
UndetVar uv = (UndetVar)t;
//bound incorporation
EnumSet<IncorporationStep> incorporationSteps = allowGraphInference ?
incorporationStepsGraph : incorporationStepsLegacy;
for (IncorporationStep is : incorporationSteps) {
if (is.accepts(uv, inferenceContext)) {
is.apply(uv, inferenceContext, warn);
}
}
}
if (!mlistener.changed || !allowGraphInference) break;
}
}
finally {
mlistener.detach();
if (incorporationCache.size() == MAX_INCORPORATION_STEPS) {
inferenceContext.rollback(saved_undet);
}
incorporationCache.clear();
}
} | java | {
"resource": ""
} |
q19711 | Infer.checkCompatibleUpperBounds | train | void checkCompatibleUpperBounds(UndetVar uv, InferenceContext inferenceContext) {
List<Type> hibounds =
Type.filter(uv.getBounds(InferenceBound.UPPER), new BoundFilter(inferenceContext));
Type hb = null;
if (hibounds.isEmpty())
hb = syms.objectType;
else if (hibounds.tail.isEmpty())
hb = hibounds.head;
else
hb = types.glb(hibounds);
if (hb == null || hb.isErroneous())
reportBoundError(uv, BoundErrorKind.BAD_UPPER);
} | java | {
"resource": ""
} |
q19712 | JwwfServer.bindWebapp | train | public JwwfServer bindWebapp(final Class<? extends User> user, String url) {
if (!url.endsWith("/"))
url = url + "/";
context.addServlet(new ServletHolder(new WebClientServelt(clientCreator)), url + "");
context.addServlet(new ServletHolder(new SkinServlet()), url + "__jwwf/skins/*");
ServletHolder fontServletHolder = new ServletHolder(new ResourceServlet());
fontServletHolder.setInitParameter("basePackage", "net/magik6k/jwwf/assets/fonts");
context.addServlet(fontServletHolder, url + "__jwwf/fonts/*");
context.addServlet(new ServletHolder(new APISocketServlet(new UserFactory() {
@Override
public User createUser() {
try {
User u = user.getDeclaredConstructor().newInstance();
u.setServer(jwwfServer);
return u;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
})), url + "__jwwf/socket");
for (JwwfPlugin plugin : plugins) {
if (plugin instanceof IPluginWebapp)
((IPluginWebapp) plugin).onWebappBound(this, url);
}
return this;
} | java | {
"resource": ""
} |
q19713 | JwwfServer.attachPlugin | train | public JwwfServer attachPlugin(JwwfPlugin plugin) {
plugins.add(plugin);
if (plugin instanceof IPluginGlobal)
((IPluginGlobal) plugin).onAttach(this);
return this;
} | java | {
"resource": ""
} |
q19714 | JwwfServer.startAndJoin | train | public JwwfServer startAndJoin() {
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
return this;
} | java | {
"resource": ""
} |
q19715 | XDBCodec.decode | train | public static InputStream decode(DataBinder binder, InputStream stream) throws ParserConfigurationException, SAXException, IOException {
XML.newSAXParser().parse(stream, new XDBHandler(binder));
return stream;
} | java | {
"resource": ""
} |
q19716 | TransTypes.addBridge | train | void addBridge(DiagnosticPosition pos,
MethodSymbol meth,
MethodSymbol impl,
ClassSymbol origin,
boolean hypothetical,
ListBuffer<JCTree> bridges) {
make.at(pos);
Type origType = types.memberType(origin.type, meth);
Type origErasure = erasure(origType);
// Create a bridge method symbol and a bridge definition without a body.
Type bridgeType = meth.erasure(types);
long flags = impl.flags() & AccessFlags | SYNTHETIC | BRIDGE |
(origin.isInterface() ? DEFAULT : 0);
if (hypothetical) flags |= HYPOTHETICAL;
MethodSymbol bridge = new MethodSymbol(flags,
meth.name,
bridgeType,
origin);
/* once JDK-6996415 is solved it should be checked if this approach can
* be applied to method addOverrideBridgesIfNeeded
*/
bridge.params = createBridgeParams(impl, bridge, bridgeType);
bridge.setAttributes(impl);
if (!hypothetical) {
JCMethodDecl md = make.MethodDef(bridge, null);
// The bridge calls this.impl(..), if we have an implementation
// in the current class, super.impl(...) otherwise.
JCExpression receiver = (impl.owner == origin)
? make.This(origin.erasure(types))
: make.Super(types.supertype(origin.type).tsym.erasure(types), origin);
// The type returned from the original method.
Type calltype = erasure(impl.type.getReturnType());
// Construct a call of this.impl(params), or super.impl(params),
// casting params and possibly results as needed.
JCExpression call =
make.Apply(
null,
make.Select(receiver, impl).setType(calltype),
translateArgs(make.Idents(md.params), origErasure.getParameterTypes(), null))
.setType(calltype);
JCStatement stat = (origErasure.getReturnType().hasTag(VOID))
? make.Exec(call)
: make.Return(coerce(call, bridgeType.getReturnType()));
md.body = make.Block(0, List.of(stat));
// Add bridge to `bridges' buffer
bridges.append(md);
}
// Add bridge to scope of enclosing class and `overridden' table.
origin.members().enter(bridge);
overridden.put(bridge, meth);
} | java | {
"resource": ""
} |
q19717 | TransTypes.addBridges | train | void addBridges(DiagnosticPosition pos, ClassSymbol origin, ListBuffer<JCTree> bridges) {
Type st = types.supertype(origin.type);
while (st.hasTag(CLASS)) {
// if (isSpecialization(st))
addBridges(pos, st.tsym, origin, bridges);
st = types.supertype(st);
}
for (List<Type> l = types.interfaces(origin.type); l.nonEmpty(); l = l.tail)
// if (isSpecialization(l.head))
addBridges(pos, l.head.tsym, origin, bridges);
} | java | {
"resource": ""
} |
q19718 | TransTypes.visitTypeApply | train | public void visitTypeApply(JCTypeApply tree) {
JCTree clazz = translate(tree.clazz, null);
result = clazz;
} | java | {
"resource": ""
} |
q19719 | TransTypes.translateTopLevelClass | train | public JCTree translateTopLevelClass(JCTree cdef, TreeMaker make) {
// note that this method does NOT support recursion.
this.make = make;
pt = null;
return translate(cdef, null);
} | java | {
"resource": ""
} |
q19720 | PackageIndexFrameWriter.addAllProfilesLink | train | protected void addAllProfilesLink(Content div) {
Content linkContent = getHyperLink(DocPaths.PROFILE_OVERVIEW_FRAME,
allprofilesLabel, "", "packageListFrame");
Content span = HtmlTree.SPAN(linkContent);
div.addContent(span);
} | java | {
"resource": ""
} |
q19721 | BiStream.throwIfNull | train | public BiStream<T, U> throwIfNull(BiPredicate<? super T, ? super U> biPredicate, Supplier<? extends RuntimeException> e) {
Predicate<T> predicate = (t) -> biPredicate.test(t, object);
return nonEmptyStream(stream.filter(predicate), e);
} | java | {
"resource": ""
} |
q19722 | Env.setCurrent | train | void setCurrent(TreePath path, DocCommentTree comment) {
currPath = path;
currDocComment = comment;
currElement = trees.getElement(currPath);
currOverriddenMethods = ((JavacTypes) types).getOverriddenMethods(currElement);
AccessKind ak = AccessKind.PUBLIC;
for (TreePath p = path; p != null; p = p.getParentPath()) {
Element e = trees.getElement(p);
if (e != null && e.getKind() != ElementKind.PACKAGE) {
ak = min(ak, AccessKind.of(e.getModifiers()));
}
}
currAccess = ak;
} | java | {
"resource": ""
} |
q19723 | Flags.valueOf | train | public static <E extends Enum<E>> Flags<E> valueOf(Class<E> type, String values) {
Flags<E> flags = new Flags<E>(type);
for (String text : values.trim().split(MULTI_VALUE_SEPARATOR)) {
flags.set(Enum.valueOf(type, text));
}
return flags;
} | java | {
"resource": ""
} |
q19724 | ProfilePackageFrameWriter.generate | train | public static void generate(ConfigurationImpl configuration,
PackageDoc packageDoc, int profileValue) {
ProfilePackageFrameWriter profpackgen;
try {
String profileName = Profile.lookup(profileValue).name;
profpackgen = new ProfilePackageFrameWriter(configuration, packageDoc,
profileName);
StringBuilder winTitle = new StringBuilder(profileName);
String sep = " - ";
winTitle.append(sep);
String pkgName = Util.getPackageName(packageDoc);
winTitle.append(pkgName);
Content body = profpackgen.getBody(false,
profpackgen.getWindowTitle(winTitle.toString()));
Content profName = new StringContent(profileName);
Content sepContent = new StringContent(sep);
Content pkgNameContent = new RawHtml(pkgName);
Content heading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, HtmlStyle.bar,
profpackgen.getTargetProfileLink("classFrame", profName, profileName));
heading.addContent(sepContent);
heading.addContent(profpackgen.getTargetProfilePackageLink(packageDoc,
"classFrame", pkgNameContent, profileName));
body.addContent(heading);
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.indexContainer);
profpackgen.addClassListing(div, profileValue);
body.addContent(div);
profpackgen.printHtmlDocument(
configuration.metakeywords.getMetaKeywords(packageDoc), false, body);
profpackgen.close();
} catch (IOException exc) {
configuration.standardmessage.error(
"doclet.exception_encountered",
exc.toString(), DocPaths.PACKAGE_FRAME.getPath());
throw new DocletAbortException(exc);
}
} | java | {
"resource": ""
} |
q19725 | Pairs.from | train | public static <First, Second> Pair<First, Second> from(
final First first, final Second second) {
return new ImmutablePair<First, Second>(first, second);
} | java | {
"resource": ""
} |
q19726 | Pairs.toArray | train | public static <CommonSuperType, First extends CommonSuperType, Second extends CommonSuperType>
CommonSuperType[] toArray(final Pair<First, Second> pair,
final Class<CommonSuperType> commonSuperType) {
@SuppressWarnings("unchecked")
final CommonSuperType[] array = (CommonSuperType[]) Array.newInstance(
commonSuperType, 2);
return toArray(pair, array, 0);
} | java | {
"resource": ""
} |
q19727 | Pairs.toArray | train | public static <CommonSuperType, First extends CommonSuperType, Second extends CommonSuperType>
CommonSuperType[] toArray(
final Pair<First, Second> pair,
final CommonSuperType[] target, final int offset) {
target[offset] = pair.getFirst();
target[offset + 1] = pair.getSecond();
return target;
} | java | {
"resource": ""
} |
q19728 | ExtendableService.setFilter | train | @Override
public void setFilter(Service.Filter filter) {
_filter = _filter == null ? filter : new CompoundServiceFilter(filter, _filter);
} | java | {
"resource": ""
} |
q19729 | ExtendableService.setFilters | train | public void setFilters(List<Service.Filter> filters) {
for (Service.Filter filter: filters) setFilter(filter);
} | java | {
"resource": ""
} |
q19730 | InteractionManager.findContext | train | private Interaction findContext(String id) {
for(int i= _currentInteractions.size() - 1; i >= 0; i--) {
Interaction ia= (Interaction) _currentInteractions.get(i);
if(ia.id.equals(id)) {
return ia;
}
}
return null;
} | java | {
"resource": ""
} |
q19731 | Batch.request | train | public List<RpcResponse> request(List<RpcRequest> reqList) {
for (RpcRequest req : reqList) {
this.reqList.add(req);
}
return null;
} | java | {
"resource": ""
} |
q19732 | Kinds.kindName | train | public static KindName kindName(int kind) {
switch (kind) {
case PCK: return KindName.PACKAGE;
case TYP: return KindName.CLASS;
case VAR: return KindName.VAR;
case VAL: return KindName.VAL;
case MTH: return KindName.METHOD;
default : throw new AssertionError("Unexpected kind: "+kind);
}
} | java | {
"resource": ""
} |
q19733 | Kinds.absentKind | train | public static KindName absentKind(int kind) {
switch (kind) {
case ABSENT_VAR:
return KindName.VAR;
case WRONG_MTHS: case WRONG_MTH: case ABSENT_MTH: case WRONG_STATICNESS:
return KindName.METHOD;
case ABSENT_TYP:
return KindName.CLASS;
default:
throw new AssertionError("Unexpected kind: "+kind);
}
} | java | {
"resource": ""
} |
q19734 | IBANCountryData.parseToElementValues | train | @Nonnull
@ReturnsMutableCopy
public ICommonsList <IBANElementValue> parseToElementValues (@Nonnull final String sIBAN)
{
ValueEnforcer.notNull (sIBAN, "IBANString");
final String sRealIBAN = IBANManager.unifyIBAN (sIBAN);
if (sRealIBAN.length () != m_nExpectedLength)
throw new IllegalArgumentException ("Passed IBAN has an invalid length. Expected " +
m_nExpectedLength +
" but found " +
sRealIBAN.length ());
final ICommonsList <IBANElementValue> ret = new CommonsArrayList <> (m_aElements.size ());
int nIndex = 0;
for (final IBANElement aElement : m_aElements)
{
final String sIBANPart = sRealIBAN.substring (nIndex, nIndex + aElement.getLength ());
ret.add (new IBANElementValue (aElement, sIBANPart));
nIndex += aElement.getLength ();
}
return ret;
} | java | {
"resource": ""
} |
q19735 | IBANCountryData.createFromString | train | @Nonnull
public static IBANCountryData createFromString (@Nonnull @Nonempty final String sCountryCode,
@Nonnegative final int nExpectedLength,
@Nullable final String sLayout,
@Nullable final String sFixedCheckDigits,
@Nullable final LocalDate aValidFrom,
@Nullable final LocalDate aValidTo,
@Nonnull final String sDesc)
{
ValueEnforcer.notEmpty (sDesc, "Desc");
if (sDesc.length () < 4)
throw new IllegalArgumentException ("Cannot converted passed string because it is too short!");
final ICommonsList <IBANElement> aList = _parseElements (sDesc);
final Pattern aPattern = _parseLayout (sCountryCode, nExpectedLength, sFixedCheckDigits, sLayout);
// And we're done
try
{
return new IBANCountryData (nExpectedLength, aPattern, sFixedCheckDigits, aValidFrom, aValidTo, aList);
}
catch (final IllegalArgumentException ex)
{
throw new IllegalArgumentException ("Failed to parse '" + sDesc + "': " + ex.getMessage ());
}
} | java | {
"resource": ""
} |
q19736 | AbstractControllerConfiguration.setControllerPath | train | protected final void setControllerPath(String path) {
requireNonNull(path, "Global path cannot be change to 'null'");
if (!"".equals(path) && !"/".equals(path)) {
this.controllerPath = pathCorrector.apply(path);
}
} | java | {
"resource": ""
} |
q19737 | AbstractClassScanner.scan | train | public void scan(final String[] packages) {
LOGGER.info("Scanning packages {}:", ArrayUtils.toString(packages));
for (final String pkg : packages) {
try {
final String pkgFile = pkg.replace('.', '/');
final Enumeration<URL> urls = getRootClassloader().getResources(pkgFile);
while (urls.hasMoreElements()) {
final URL url = urls.nextElement();
try {
final URI uri = getURI(url);
LOGGER.debug("Scanning {}", uri);
scan(uri, pkgFile);
} catch (final URISyntaxException e) {
LOGGER.debug("URL {} cannot be converted to a URI", url, e);
}
}
} catch (final IOException ex) {
throw new RuntimeException("The resources for the package" + pkg + ", could not be obtained",
ex);
}
}
LOGGER.info(
"Found {} matching classes and {} matching files",
matchingClasses.size(),
matchingFiles.size());
} | java | {
"resource": ""
} |
q19738 | JavapTask.run | train | int run(String[] args) {
try {
handleOptions(args);
// the following gives consistent behavior with javac
if (classes == null || classes.size() == 0) {
if (options.help || options.version || options.fullVersion)
return EXIT_OK;
else
return EXIT_CMDERR;
}
try {
return run();
} finally {
if (defaultFileManager != null) {
try {
defaultFileManager.close();
defaultFileManager = null;
} catch (IOException e) {
throw new InternalError(e);
}
}
}
} catch (BadArgs e) {
reportError(e.key, e.args);
if (e.showUsage) {
printLines(getMessage("main.usage.summary", progname));
}
return EXIT_CMDERR;
} catch (InternalError e) {
Object[] e_args;
if (e.getCause() == null)
e_args = e.args;
else {
e_args = new Object[e.args.length + 1];
e_args[0] = e.getCause();
System.arraycopy(e.args, 0, e_args, 1, e.args.length);
}
reportError("err.internal.error", e_args);
return EXIT_ABNORMAL;
} finally {
log.flush();
}
} | java | {
"resource": ""
} |
q19739 | MetaKeywords.getMetaKeywords | train | public String[] getMetaKeywords(Profile profile) {
if( configuration.keywords ) {
String profileName = profile.name;
return new String[] { profileName + " " + "profile" };
} else {
return new String[] {};
}
} | java | {
"resource": ""
} |
q19740 | TreeScanner.scan | train | public R scan(Tree node, P p) {
return (node == null) ? null : node.accept(this, p);
} | java | {
"resource": ""
} |
q19741 | ClientAddressAuthorizer.setAuthorizedPatternArray | train | public void setAuthorizedPatternArray(String[] patterns) {
Matcher matcher;
patterns: for (String pattern: patterns) {
if ((matcher = IPv4_ADDRESS_PATTERN.matcher(pattern)).matches()) {
short[] address = new short[4];
for (int i = 0; i < address.length; ++i) {
String p = matcher.group(i+1);
try {
address[i] = Short.parseShort(p);
if (address[i] > 255) {
_logger.warning("Invalid pattern ignored: " + pattern);
continue patterns;
}
} catch (Exception x) {
if ("*".equals(p)) {
address[i] = 256;
} else {
_logger.warning("Invalid pattern ignored: " + pattern);
continue patterns;
}
}
}
_logger.fine("normalized ipv4 address pattern = " + Strings.join(address, '.'));
_ipv4patterns.add(address);
} else if ((matcher = IPv6_ADDRESS_PATTERN.matcher(pattern)).matches()) {
short[] address = new short[16];
for (int i = 0; i < address.length; i += 2) {
String p = matcher.group(i/2+1);
try {
int v = Integer.parseInt(p, 16);
address[i] = (short)(v >> 8);
address[i+1] = (short)(v & 0x00ff);
} catch (Exception x) {
if ("*".equals(p)) {
address[i] = 256;
address[i+1] = 256;
} else {
_logger.warning("Invalid pattern ignored: " + pattern);
continue patterns;
}
}
}
_logger.fine("normalized ipv6 address pattern = " + Strings.join(address, '.'));
_ipv6patterns.add(address);
} else {
_logger.warning("Invalid pattern ignored: " + pattern);
}
}
} | java | {
"resource": ""
} |
q19742 | Main.findJavaSourceFiles | train | private boolean findJavaSourceFiles(String[] args) {
String prev = "";
for (String s : args) {
if (s.endsWith(".java") && !prev.equals("-xf") && !prev.equals("-if")) {
return true;
}
prev = s;
}
return false;
} | java | {
"resource": ""
} |
q19743 | Main.findAtFile | train | private boolean findAtFile(String[] args) {
for (String s : args) {
if (s.startsWith("@")) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q19744 | Main.findLogLevel | train | private String findLogLevel(String[] args) {
for (String s : args) {
if (s.startsWith("--log=") && s.length()>6) {
return s.substring(6);
}
if (s.equals("-verbose")) {
return "info";
}
}
return "info";
} | java | {
"resource": ""
} |
q19745 | Main.makeSureExists | train | private static boolean makeSureExists(File dir) {
// Make sure the dest directories exist.
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.error("Could not create the directory "+dir.getPath());
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q19746 | Main.checkPattern | train | private static void checkPattern(String s) throws ProblemException {
// Package names like foo.bar.gamma are allowed, and
// package names suffixed with .* like foo.bar.* are
// also allowed.
Pattern p = Pattern.compile("[a-zA-Z_]{1}[a-zA-Z0-9_]*(\\.[a-zA-Z_]{1}[a-zA-Z0-9_]*)*(\\.\\*)?+");
Matcher m = p.matcher(s);
if (!m.matches()) {
throw new ProblemException("The string \""+s+"\" is not a proper package name pattern.");
}
} | java | {
"resource": ""
} |
q19747 | Main.checkFilePattern | train | private static void checkFilePattern(String s) throws ProblemException {
// File names like foo/bar/gamma/Bar.java are allowed,
// as well as /bar/jndi.properties as well as,
// */bar/Foo.java
Pattern p = null;
if (File.separatorChar == '\\') {
p = Pattern.compile("\\*?(.+\\\\)*.+");
}
else if (File.separatorChar == '/') {
p = Pattern.compile("\\*?(.+/)*.+");
} else {
throw new ProblemException("This platform uses the unsupported "+File.separatorChar+
" as file separator character. Please add support for it!");
}
Matcher m = p.matcher(s);
if (!m.matches()) {
throw new ProblemException("The string \""+s+"\" is not a proper file name.");
}
} | java | {
"resource": ""
} |
q19748 | Main.hasOption | train | private static boolean hasOption(String[] args, String option) {
for (String a : args) {
if (a.equals(option)) return true;
}
return false;
} | java | {
"resource": ""
} |
q19749 | Main.rewriteOptions | train | private static void rewriteOptions(String[] args, String option, String new_option) {
for (int i=0; i<args.length; ++i) {
if (args[i].equals(option)) {
args[i] = new_option;
}
}
} | java | {
"resource": ""
} |
q19750 | Main.findDirectoryOption | train | private static File findDirectoryOption(String[] args, String option, String name, boolean needed, boolean allow_dups, boolean create)
throws ProblemException, ProblemException {
File dir = null;
for (int i = 0; i<args.length; ++i) {
if (args[i].equals(option)) {
if (dir != null) {
throw new ProblemException("You have already specified the "+name+" dir!");
}
if (i+1 >= args.length) {
throw new ProblemException("You have to specify a directory following "+option+".");
}
if (args[i+1].indexOf(File.pathSeparatorChar) != -1) {
throw new ProblemException("You must only specify a single directory for "+option+".");
}
dir = new File(args[i+1]);
if (!dir.exists()) {
if (!create) {
throw new ProblemException("This directory does not exist: "+dir.getPath());
} else
if (!makeSureExists(dir)) {
throw new ProblemException("Cannot create directory "+dir.getPath());
}
}
if (!dir.isDirectory()) {
throw new ProblemException("\""+args[i+1]+"\" is not a directory.");
}
}
}
if (dir == null && needed) {
throw new ProblemException("You have to specify "+option);
}
try {
if (dir != null)
return dir.getCanonicalFile();
} catch (IOException e) {
throw new ProblemException(""+e);
}
return null;
} | java | {
"resource": ""
} |
q19751 | Main.shouldBeFollowedByPath | train | private static boolean shouldBeFollowedByPath(String o) {
return o.equals("-s") ||
o.equals("-h") ||
o.equals("-d") ||
o.equals("-sourcepath") ||
o.equals("-classpath") ||
o.equals("-cp") ||
o.equals("-bootclasspath") ||
o.equals("-src");
} | java | {
"resource": ""
} |
q19752 | Main.addSrcBeforeDirectories | train | private static String[] addSrcBeforeDirectories(String[] args) {
List<String> newargs = new ArrayList<String>();
for (int i = 0; i<args.length; ++i) {
File dir = new File(args[i]);
if (dir.exists() && dir.isDirectory()) {
if (i == 0 || !shouldBeFollowedByPath(args[i-1])) {
newargs.add("-src");
}
}
newargs.add(args[i]);
}
return newargs.toArray(new String[0]);
} | java | {
"resource": ""
} |
q19753 | Main.checkSrcOption | train | private static void checkSrcOption(String[] args)
throws ProblemException {
Set<File> dirs = new HashSet<File>();
for (int i = 0; i<args.length; ++i) {
if (args[i].equals("-src")) {
if (i+1 >= args.length) {
throw new ProblemException("You have to specify a directory following -src.");
}
StringTokenizer st = new StringTokenizer(args[i+1], File.pathSeparator);
while (st.hasMoreElements()) {
File dir = new File(st.nextToken());
if (!dir.exists()) {
throw new ProblemException("This directory does not exist: "+dir.getPath());
}
if (!dir.isDirectory()) {
throw new ProblemException("\""+dir.getPath()+"\" is not a directory.");
}
if (dirs.contains(dir)) {
throw new ProblemException("The src directory \""+dir.getPath()+"\" is specified more than once!");
}
dirs.add(dir);
}
}
}
if (dirs.isEmpty()) {
throw new ProblemException("You have to specify -src.");
}
} | java | {
"resource": ""
} |
q19754 | Main.findFileOption | train | private static File findFileOption(String[] args, String option, String name, boolean needed)
throws ProblemException, ProblemException {
File file = null;
for (int i = 0; i<args.length; ++i) {
if (args[i].equals(option)) {
if (file != null) {
throw new ProblemException("You have already specified the "+name+" file!");
}
if (i+1 >= args.length) {
throw new ProblemException("You have to specify a file following "+option+".");
}
file = new File(args[i+1]);
if (file.isDirectory()) {
throw new ProblemException("\""+args[i+1]+"\" is not a file.");
}
if (!file.exists() && needed) {
throw new ProblemException("The file \""+args[i+1]+"\" does not exist.");
}
}
}
if (file == null && needed) {
throw new ProblemException("You have to specify "+option);
}
return file;
} | java | {
"resource": ""
} |
q19755 | Main.findBooleanOption | train | public static boolean findBooleanOption(String[] args, String option) {
for (int i = 0; i<args.length; ++i) {
if (args[i].equals(option)) return true;
}
return false;
} | java | {
"resource": ""
} |
q19756 | Main.findNumberOption | train | public static int findNumberOption(String[] args, String option) {
int rc = 0;
for (int i = 0; i<args.length; ++i) {
if (args[i].equals(option)) {
if (args.length > i+1) {
rc = Integer.parseInt(args[i+1]);
}
}
}
return rc;
} | java | {
"resource": ""
} |
q19757 | Strings.toHexString | train | public static String toHexString(byte[] raw) {
byte[] hex = new byte[2 * raw.length];
int index = 0;
for (byte b : raw) {
int v = b & 0x00ff;
hex[index++] = HEX_CHARS[v >>> 4];
hex[index++] = HEX_CHARS[v & 0xf];
}
try {
return new String(hex, "ASCII");
} catch (java.io.UnsupportedEncodingException x) {
throw new RuntimeException(x.getMessage(), x);
}
} | java | {
"resource": ""
} |
q19758 | Strings.toCamelCase | train | public static String toCamelCase(String text, char separator, boolean strict) {
char[] chars = text.toCharArray();
int base = 0, top = 0;
while (top < chars.length) {
while (top < chars.length && chars[top] == separator) {
++top;
}
if (top < chars.length) {
chars[base++] = Character.toUpperCase(chars[top++]);
}
if (strict) {
while (top < chars.length && chars[top] != separator) {
chars[base++] = Character.toLowerCase(chars[top++]);
}
} else {
while (top < chars.length && chars[top] != separator) {
chars[base++] = chars[top++];
}
}
}
return new String(chars, 0, base);
} | java | {
"resource": ""
} |
q19759 | Strings.toLowerCamelCase | train | public static String toLowerCamelCase(String text, char separator) {
char[] chars = text.toCharArray();
int base = 0, top = 0;
do {
while (top < chars.length && chars[top] != separator) {
chars[base++] = Character.toLowerCase(chars[top++]);
}
while (top < chars.length && chars[top] == separator) {
++top;
}
if (top < chars.length) {
chars[base++] = Character.toUpperCase(chars[top++]);
}
} while (top < chars.length);
return new String(chars, 0, base);
} | java | {
"resource": ""
} |
q19760 | Strings.splitCamelCase | train | public static String splitCamelCase(String text, String separator) {
return CAMEL_REGEX.matcher(text).replaceAll(separator);
} | java | {
"resource": ""
} |
q19761 | Strings.hash | train | public static String hash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
return Strings.toHexString(MessageDigest.getInstance("SHA").digest(text.getBytes("UTF-8")));
} | java | {
"resource": ""
} |
q19762 | Strings.extend | train | public static String extend(String text, char filler, int length) {
if (text.length() < length) {
char[] buffer = new char[length];
Arrays.fill(buffer, 0, length, filler);
System.arraycopy(text.toCharArray(), 0, buffer, 0, text.length());
return new String(buffer);
} else {
return text;
}
} | java | {
"resource": ""
} |
q19763 | Strings.substringBefore | train | public static String substringBefore(String text, char stopper) {
int p = text.indexOf(stopper);
return p < 0 ? text : text.substring(0, p);
} | java | {
"resource": ""
} |
q19764 | Strings.substringAfter | train | public static String substringAfter(String text, char match) {
return text.substring(text.indexOf(match)+1);
} | java | {
"resource": ""
} |
q19765 | Strings.join | train | public static String join(Object array, char separator, Object... pieces) {
StringBuilder sb = new StringBuilder();
for (int i = 0, ii = Array.getLength(array); i < ii; ++i) {
Object element = Array.get(array, i);
sb.append(element != null ? element.toString() : "null").append(separator);
}
for (int i = 0; i < pieces.length; ++i) {
sb.append(pieces[i] != null ? pieces[i].toString() : "null").append(separator);
}
if (sb.length() > 0) sb.setLength(sb.length()-1);
return sb.toString();
} | java | {
"resource": ""
} |
q19766 | Strings.join | train | public static <T> String join(Iterable<T> iterable, char separator, T... pieces) {
StringBuilder sb = new StringBuilder();
for (T element: iterable) {
sb.append(element != null ? element.toString() : "null").append(separator);
}
for (int i = 0; i < pieces.length; ++i) {
sb.append(pieces[i] != null ? pieces[i].toString() : "null").append(separator);
}
if (sb.length() > 0) sb.setLength(sb.length()-1);
return sb.toString();
} | java | {
"resource": ""
} |
q19767 | Types.rawClassOf | train | public static Class<?> rawClassOf(Type type) {
if (type instanceof Class<?>) {
return (Class<?>) type;
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType();
return (Class<?>) rawType;
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
return Array.newInstance(rawClassOf(componentType), 0).getClass();
} else if (type instanceof TypeVariable) {
return Object.class;
} else {
throw new IllegalArgumentException("Unsupported type " + type.getTypeName());
}
} | java | {
"resource": ""
} |
q19768 | ClassPredicates.classIs | train | public static Predicate<Class<?>> classIs(final Class<?> reference) {
return candidate -> candidate != null && candidate.equals(reference);
} | java | {
"resource": ""
} |
q19769 | ClassPredicates.classIsAssignableFrom | train | public static Predicate<Class<?>> classIsAssignableFrom(Class<?> ancestor) {
return candidate -> candidate != null && ancestor.isAssignableFrom(candidate);
} | java | {
"resource": ""
} |
q19770 | ClassPredicates.classImplements | train | public static Predicate<Class<?>> classImplements(Class<?> anInterface) {
if (!anInterface.isInterface()) {
throw new IllegalArgumentException("Class " + anInterface.getName() + " is not an interface");
}
return candidate -> candidate != null && !candidate.isInterface() && anInterface
.isAssignableFrom(candidate);
} | java | {
"resource": ""
} |
q19771 | ClassPredicates.executableModifierIs | train | public static <T extends Executable> Predicate<T> executableModifierIs(final int modifier) {
return candidate -> (candidate.getModifiers() & modifier) != 0;
} | java | {
"resource": ""
} |
q19772 | ClassPredicates.atLeastOneConstructorIsPublic | train | public static Predicate<Class<?>> atLeastOneConstructorIsPublic() {
return candidate -> candidate != null && Classes.from(candidate)
.constructors()
.anyMatch(executableModifierIs(Modifier.PUBLIC));
} | java | {
"resource": ""
} |
q19773 | Workbook.getOffset | train | protected int getOffset(long dt)
{
int ret = 0;
TimeZone tz = DateUtilities.getCurrentTimeZone();
if(tz != null)
ret = tz.getOffset(dt);
return ret;
} | java | {
"resource": ""
} |
q19774 | Util.isDeprecated | train | public static boolean isDeprecated(Doc doc) {
if (doc.tags("deprecated").length > 0) {
return true;
}
AnnotationDesc[] annotationDescList;
if (doc instanceof PackageDoc)
annotationDescList = ((PackageDoc)doc).annotations();
else
annotationDescList = ((ProgramElementDoc)doc).annotations();
for (int i = 0; i < annotationDescList.length; i++) {
if (annotationDescList[i].annotationType().qualifiedName().equals(
java.lang.Deprecated.class.getName())){
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q19775 | Util.propertyNameFromMethodName | train | public static String propertyNameFromMethodName(Configuration configuration, String name) {
String propertyName = null;
if (name.startsWith("get") || name.startsWith("set")) {
propertyName = name.substring(3);
} else if (name.startsWith("is")) {
propertyName = name.substring(2);
}
if ((propertyName == null) || propertyName.isEmpty()){
return "";
}
return propertyName.substring(0, 1).toLowerCase(configuration.getLocale())
+ propertyName.substring(1);
} | java | {
"resource": ""
} |
q19776 | Util.isJava5DeclarationElementType | train | public static boolean isJava5DeclarationElementType(FieldDoc elt) {
return elt.name().contentEquals(ElementType.ANNOTATION_TYPE.name()) ||
elt.name().contentEquals(ElementType.CONSTRUCTOR.name()) ||
elt.name().contentEquals(ElementType.FIELD.name()) ||
elt.name().contentEquals(ElementType.LOCAL_VARIABLE.name()) ||
elt.name().contentEquals(ElementType.METHOD.name()) ||
elt.name().contentEquals(ElementType.PACKAGE.name()) ||
elt.name().contentEquals(ElementType.PARAMETER.name()) ||
elt.name().contentEquals(ElementType.TYPE.name());
} | java | {
"resource": ""
} |
q19777 | Gen.normalizeMethod | train | void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<TypeCompound> initTAs) {
if (md.name == names.init && TreeInfo.isInitialConstructor(md)) {
// We are seeing a constructor that does not call another
// constructor of the same class.
List<JCStatement> stats = md.body.stats;
ListBuffer<JCStatement> newstats = new ListBuffer<JCStatement>();
if (stats.nonEmpty()) {
// Copy initializers of synthetic variables generated in
// the translation of inner classes.
while (TreeInfo.isSyntheticInit(stats.head)) {
newstats.append(stats.head);
stats = stats.tail;
}
// Copy superclass constructor call
newstats.append(stats.head);
stats = stats.tail;
// Copy remaining synthetic initializers.
while (stats.nonEmpty() &&
TreeInfo.isSyntheticInit(stats.head)) {
newstats.append(stats.head);
stats = stats.tail;
}
// Now insert the initializer code.
newstats.appendList(initCode);
// And copy all remaining statements.
while (stats.nonEmpty()) {
newstats.append(stats.head);
stats = stats.tail;
}
}
md.body.stats = newstats.toList();
if (md.body.endpos == Position.NOPOS)
md.body.endpos = TreeInfo.endPos(md.body.stats.last());
md.sym.appendUniqueTypeAttributes(initTAs);
}
} | java | {
"resource": ""
} |
q19778 | Gen.implementInterfaceMethods | train | void implementInterfaceMethods(ClassSymbol c, ClassSymbol site) {
for (List<Type> l = types.interfaces(c.type); l.nonEmpty(); l = l.tail) {
ClassSymbol i = (ClassSymbol)l.head.tsym;
for (Scope.Entry e = i.members().elems;
e != null;
e = e.sibling)
{
if (e.sym.kind == MTH && (e.sym.flags() & STATIC) == 0)
{
MethodSymbol absMeth = (MethodSymbol)e.sym;
MethodSymbol implMeth = absMeth.binaryImplementation(site, types);
if (implMeth == null)
addAbstractMethod(site, absMeth);
else if ((implMeth.flags() & IPROXY) != 0)
adjustAbstractMethod(site, implMeth, absMeth);
}
}
implementInterfaceMethods(i, site);
}
} | java | {
"resource": ""
} |
q19779 | Gen.addAbstractMethod | train | private void addAbstractMethod(ClassSymbol c,
MethodSymbol m) {
MethodSymbol absMeth = new MethodSymbol(
m.flags() | IPROXY | SYNTHETIC, m.name,
m.type, // was c.type.memberType(m), but now only !generics supported
c);
c.members().enter(absMeth); // add to symbol table
} | java | {
"resource": ""
} |
q19780 | Gen.makeStringBuffer | train | void makeStringBuffer(DiagnosticPosition pos) {
code.emitop2(new_, makeRef(pos, stringBufferType));
code.emitop0(dup);
callMethod(
pos, stringBufferType, names.init, List.<Type>nil(), false);
} | java | {
"resource": ""
} |
q19781 | Gen.appendStrings | train | void appendStrings(JCTree tree) {
tree = TreeInfo.skipParens(tree);
if (tree.hasTag(PLUS) && tree.type.constValue() == null) {
JCBinary op = (JCBinary) tree;
if (op.operator.kind == MTH &&
((OperatorSymbol) op.operator).opcode == string_add) {
appendStrings(op.lhs);
appendStrings(op.rhs);
return;
}
}
genExpr(tree, tree.type).load();
appendString(tree);
} | java | {
"resource": ""
} |
q19782 | Gen.bufferToString | train | void bufferToString(DiagnosticPosition pos) {
callMethod(
pos,
stringBufferType,
names.toString,
List.<Type>nil(),
false);
} | java | {
"resource": ""
} |
q19783 | Elements.getValue | train | public static <E> OptionalFunction<Selection<Element>, E> getValue() {
return OptionalFunction.of(selection -> selection.result().getValue());
} | java | {
"resource": ""
} |
q19784 | Elements.setValue | train | public static Consumer<Selection<Element>> setValue(Object newValue) {
return selection -> selection.result().setValue(newValue);
} | java | {
"resource": ""
} |
q19785 | IdUtil.validate | train | static
public boolean validate(String id){
if(id.equals("")){
return false;
} else
if(id.equals(".") || id.equals("..")){
return false;
}
Matcher matcher = IdUtil.pattern.matcher(id);
return matcher.matches();
} | java | {
"resource": ""
} |
q19786 | UiSelector.buildSelector | train | private UiSelector buildSelector(int selectorId, Object selectorValue) {
if (selectorId == SELECTOR_CHILD || selectorId == SELECTOR_PARENT) {
throw new UnsupportedOperationException();
// selector.getLastSubSelector().mSelectorAttributes.put(selectorId, selectorValue);
} else {
this.mSelectorAttributes.put(selectorId, selectorValue);
}
return this;
} | java | {
"resource": ""
} |
q19787 | UserData.get | train | public void get(String key, UserDataHandler handler) {
if (cache.containsKey(key)) {
try {
handler.data(key, cache.get(key));
} catch (Exception e) {
e.printStackTrace();
}
return;
}
user.sendGlobal("JWWF-storageGet", "{\"key\":" + Json.escapeString(key) + "}");
if (waitingHandlers.containsKey(key)) {
waitingHandlers.get(key).push(handler);
} else {
LinkedList<UserDataHandler> ll = new LinkedList<UserDataHandler>();
ll.push(handler);
waitingHandlers.put(key, ll);
}
} | java | {
"resource": ""
} |
q19788 | UserData.set | train | public void set(String key, String value) {
cache.put(key, value);
user.sendGlobal("JWWF-storageSet", "{\"key\":" + Json.escapeString(key) + ",\"value\":" + Json.escapeString(value) + "}");
} | java | {
"resource": ""
} |
q19789 | Scriptable.setObjects | train | public void setObjects(Map<String, Object> objects) {
for (Map.Entry<String, Object> entry: objects.entrySet()) {
js.put(entry.getKey(), entry.getValue());
}
} | java | {
"resource": ""
} |
q19790 | AbstractConfigurer.initializeContext | train | protected ApplicationContext initializeContext() {
Function<Class<Object>, List<Object>> getBeans = this::getBeans;
BeanFactory beanFactory = new BeanFactory(getBeans);
InitContext context = new InitContext();
AutoConfigurer.configureInitializers()
.forEach(initializer -> initializer.init(context, beanFactory));
List<AbstractReaderWriter> readersWriters = AutoConfigurer.configureReadersWriters();
ExceptionHandlerInterceptor exceptionHandlerInterceptor = new ExceptionHandlerInterceptor();
COMMON_INTERCEPTORS.add(exceptionHandlerInterceptor);
Map<Boolean, List<Reader>> readers = createTransformers(
concat(beanFactory.getAll(Reader.class), context.getReaders(), readersWriters));
Map<Boolean, List<Writer>> writers = createTransformers(
concat(beanFactory.getAll(Writer.class), context.getWriters(), readersWriters));
List<Interceptor> interceptors = sort(
concat(beanFactory.getAll(Interceptor.class), context.getInterceptors(), COMMON_INTERCEPTORS));
List<ExceptionConfiguration> handlers =
concat(beanFactory.getAll(ExceptionConfiguration.class), context.getExceptionConfigurations(), COMMON_HANDLERS);
List<ControllerConfiguration> controllers =
concat(beanFactory.getAll(ControllerConfiguration.class), context.getControllerConfigurations());
orderDuplicationCheck(interceptors);
Map<Class<? extends Exception>, InternalExceptionHandler> handlerMap =
handlers.stream()
.peek(ExceptionConfiguration::initialize)
.flatMap(config -> config.getExceptionHandlers().stream())
.peek(handler -> {
populateHandlerWriters(writers, handler, nonNull(handler.getResponseType()));
logExceptionHandler(handler);
})
.collect(toMap(InternalExceptionHandler::getExceptionClass, identity()));
context.setExceptionHandlers(handlerMap);
controllers.stream()
.peek(ControllerConfiguration::initialize)
.flatMap(config -> config.getRoutes().stream())
.peek(route -> {
route.interceptor(interceptors.toArray(new Interceptor[interceptors.size()]));
populateRouteReaders(readers, route);
populateRouteWriters(writers, route);
logRoute(route);
}).forEach(context::addRoute);
ApplicationContextImpl applicationContext = new ApplicationContextImpl();
applicationContext.setRoutes(context.getRoutes());
applicationContext.setExceptionHandlers(context.getExceptionHandlers());
exceptionHandlerInterceptor.setApplicationContext(applicationContext);
return applicationContext;
} | java | {
"resource": ""
} |
q19791 | Singleton.slow | train | public synchronized T slow(Factory<T> p, Object... args) throws Exception {
T result = _value;
if (isMissing(result)) {
_value = result = p.make(args);
}
return result;
} | java | {
"resource": ""
} |
q19792 | PointerCoords.clear | train | public void clear() {
mPackedAxisBits = 0;
x = 0;
y = 0;
pressure = 0;
size = 0;
touchMajor = 0;
touchMinor = 0;
toolMajor = 0;
toolMinor = 0;
orientation = 0;
} | java | {
"resource": ""
} |
q19793 | PointerCoords.copyFrom | train | public void copyFrom(PointerCoords other) {
final long bits = other.mPackedAxisBits;
mPackedAxisBits = bits;
if (bits != 0) {
final float[] otherValues = other.mPackedAxisValues;
final int count = Long.bitCount(bits);
float[] values = mPackedAxisValues;
if (values == null || count > values.length) {
values = new float[otherValues.length];
mPackedAxisValues = values;
}
System.arraycopy(otherValues, 0, values, 0, count);
}
x = other.x;
y = other.y;
pressure = other.pressure;
size = other.size;
touchMajor = other.touchMajor;
touchMinor = other.touchMinor;
toolMajor = other.toolMajor;
toolMinor = other.toolMinor;
orientation = other.orientation;
} | java | {
"resource": ""
} |
q19794 | PointerCoords.getAxisValue | train | public float getAxisValue(int axis) {
switch (axis) {
case AXIS_X:
return x;
case AXIS_Y:
return y;
case AXIS_PRESSURE:
return pressure;
case AXIS_SIZE:
return size;
case AXIS_TOUCH_MAJOR:
return touchMajor;
case AXIS_TOUCH_MINOR:
return touchMinor;
case AXIS_TOOL_MAJOR:
return toolMajor;
case AXIS_TOOL_MINOR:
return toolMinor;
case AXIS_ORIENTATION:
return orientation;
default: {
if (axis < 0 || axis > 63) {
throw new IllegalArgumentException("Axis out of range.");
}
final long bits = mPackedAxisBits;
final long axisBit = 1L << axis;
if ((bits & axisBit) == 0) {
return 0;
}
final int index = Long.bitCount(bits & (axisBit - 1L));
return mPackedAxisValues[index];
}
}
} | java | {
"resource": ""
} |
q19795 | PointerCoords.setAxisValue | train | public void setAxisValue(int axis, float value) {
switch (axis) {
case AXIS_X:
x = value;
break;
case AXIS_Y:
y = value;
break;
case AXIS_PRESSURE:
pressure = value;
break;
case AXIS_SIZE:
size = value;
break;
case AXIS_TOUCH_MAJOR:
touchMajor = value;
break;
case AXIS_TOUCH_MINOR:
touchMinor = value;
break;
case AXIS_TOOL_MAJOR:
toolMajor = value;
break;
case AXIS_TOOL_MINOR:
toolMinor = value;
break;
case AXIS_ORIENTATION:
orientation = value;
break;
default: {
if (axis < 0 || axis > 63) {
throw new IllegalArgumentException("Axis out of range.");
}
final long bits = mPackedAxisBits;
final long axisBit = 1L << axis;
final int index = Long.bitCount(bits & (axisBit - 1L));
float[] values = mPackedAxisValues;
if ((bits & axisBit) == 0) {
if (values == null) {
values = new float[INITIAL_PACKED_AXIS_VALUES];
mPackedAxisValues = values;
} else {
final int count = Long.bitCount(bits);
if (count < values.length) {
if (index != count) {
System.arraycopy(values, index, values, index + 1,
count - index);
}
} else {
float[] newValues = new float[count * 2];
System.arraycopy(values, 0, newValues, 0, index);
System.arraycopy(values, index, newValues, index + 1,
count - index);
values = newValues;
mPackedAxisValues = values;
}
}
mPackedAxisBits = bits | axisBit;
}
values[index] = value;
}
}
} | java | {
"resource": ""
} |
q19796 | Util.set | train | public static Set<String> set(String... ss) {
Set<String> set = new HashSet<String>();
set.addAll(Arrays.asList(ss));
return set;
} | java | {
"resource": ""
} |
q19797 | ExecutorUtils.newThreadFactory | train | public static ThreadFactory newThreadFactory(final String format, final boolean daemon) {
final String nameFormat;
if (!format.contains("%d")) {
nameFormat = format + "-%d";
} else {
nameFormat = format;
}
return new ThreadFactoryBuilder() //
.setNameFormat(nameFormat) //
.setDaemon(daemon) //
.build();
} | java | {
"resource": ""
} |
q19798 | Comment.tags | train | Tag[] tags(String tagname) {
ListBuffer<Tag> found = new ListBuffer<Tag>();
String target = tagname;
if (target.charAt(0) != '@') {
target = "@" + target;
}
for (Tag tag : tagList) {
if (tag.kind().equals(target)) {
found.append(tag);
}
}
return found.toArray(new Tag[found.length()]);
} | java | {
"resource": ""
} |
q19799 | Comment.paramTags | train | private ParamTag[] paramTags(boolean typeParams) {
ListBuffer<ParamTag> found = new ListBuffer<ParamTag>();
for (Tag next : tagList) {
if (next instanceof ParamTag) {
ParamTag p = (ParamTag)next;
if (typeParams == p.isTypeParameter()) {
found.append(p);
}
}
}
return found.toArray(new ParamTag[found.length()]);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.