_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q19400
CachedResultSet.rename
train
public CachedResultSet rename(String... names) { for (int i = 0; i < names.length; ++i) { this.columns[i] = names[i]; } return this; }
java
{ "resource": "" }
q19401
CachedResultSet.buildIndex
train
public Map<String, Integer> buildIndex() { Map<String, Integer> index = new HashMap<String, Integer>(); for (int i = 0; i < columns.length; ++i) { index.put(columns[i], i); } return index; }
java
{ "resource": "" }
q19402
PaperclipRepository.attach
train
@Programmatic public Paperclip attach( final DocumentAbstract documentAbstract, final String roleName, final Object attachTo) { Paperclip paperclip = findByDocumentAndAttachedToAndRoleName( documentAbstract, attachTo, roleName); if(paperclip != null) { return paperclip; } final Class<? extends Paperclip> subtype = subtypeClassFor(attachTo); paperclip = repositoryService.instantiate(subtype); paperclip.setDocument(documentAbstract); paperclip.setRoleName(roleName); if(documentAbstract instanceof Document) { final Document document = (Document) documentAbstract; paperclip.setDocumentCreatedAt(document.getCreatedAt()); } if(!repositoryService.isPersistent(attachTo)) { transactionService.flushTransaction(); } final Bookmark bookmark = bookmarkService.bookmarkFor(attachTo); paperclip.setAttachedTo(attachTo); paperclip.setAttachedToStr(bookmark.toString()); repositoryService.persistAndFlush(paperclip); return paperclip; }
java
{ "resource": "" }
q19403
JavaTokenizer.scanFraction
train
private void scanFraction(int pos) { skipIllegalUnderscores(); if ('0' <= reader.ch && reader.ch <= '9') { scanDigits(pos, 10); } int sp1 = reader.sp; if (reader.ch == 'e' || reader.ch == 'E') { reader.putChar(true); skipIllegalUnderscores(); if (reader.ch == '+' || reader.ch == '-') { reader.putChar(true); } skipIllegalUnderscores(); if ('0' <= reader.ch && reader.ch <= '9') { scanDigits(pos, 10); return; } lexError(pos, "malformed.fp.lit"); reader.sp = sp1; } }
java
{ "resource": "" }
q19404
JavaTokenizer.isMagicComment
train
private boolean isMagicComment() { assert reader.ch == '@'; int parens = 0; boolean stringLit = false; int lbp = reader.bp; char lch = reader.buf[++lbp]; if (!Character.isJavaIdentifierStart(lch)) { // The first thing after the @ has to be the annotation identifier return false; } while (lbp < reader.buflen) { lch = reader.buf[++lbp]; // We are outside any annotation values if (Character.isWhitespace(lch) && !spacesincomments && parens == 0) { return false; } else if (lch == '@' && parens == 0) { // At most one annotation per magic comment return false; } else if (lch == '(' && !stringLit) { ++parens; } else if (lch == ')' && !stringLit) { --parens; } else if (lch == '"') { // TODO: handle more complicated string literals, // char literals, escape sequences, unicode, etc. stringLit = !stringLit; } else if (lch == '*' && !stringLit && lbp + 1 < reader.buflen && reader.buf[lbp+1] == '/') { // We reached the end of the comment, make sure no // parens are open return parens == 0; } else if (!Character.isJavaIdentifierPart(lch) && !Character.isWhitespace(lch) && lch != '.' && // separator in fully-qualified annotation name // TODO: this also allows /*@A...*/ which should not be recognized. !spacesincomments && parens == 0 && !stringLit) { return false; } // Do we need anything else for annotation values, e.g. String literals? } // came to end of file before '*/' return false; }
java
{ "resource": "" }
q19405
JavaTokenizer.processComment
train
protected Tokens.Comment processComment(int pos, int endPos, CommentStyle style) { if (scannerDebug) System.out.println("processComment(" + pos + "," + endPos + "," + style + ")=|" + new String(reader.getRawCharacters(pos, endPos)) + "|"); char[] buf = reader.getRawCharacters(pos, endPos); return new BasicComment<UnicodeReader>(new UnicodeReader(fac, buf, buf.length), style); }
java
{ "resource": "" }
q19406
VATManager.isZeroVATAllowed
train
public boolean isZeroVATAllowed (@Nonnull final Locale aCountry, final boolean bUndefinedValue) { ValueEnforcer.notNull (aCountry, "Country"); // first get locale specific VAT types final VATCountryData aVATCountryData = getVATCountryData (aCountry); return aVATCountryData != null ? aVATCountryData.isZeroVATAllowed () : bUndefinedValue; }
java
{ "resource": "" }
q19407
VATManager.getVATCountryData
train
@Nullable public VATCountryData getVATCountryData (@Nonnull final Locale aLocale) { ValueEnforcer.notNull (aLocale, "Locale"); final Locale aCountry = CountryCache.getInstance ().getCountry (aLocale); return m_aVATItemsPerCountry.get (aCountry); }
java
{ "resource": "" }
q19408
VATManager.findVATItem
train
@Nullable public IVATItem findVATItem (@Nullable final EVATItemType eType, @Nullable final BigDecimal aPercentage) { if (eType == null || aPercentage == null) return null; return findFirst (x -> x.getType ().equals (eType) && x.hasPercentage (aPercentage)); }
java
{ "resource": "" }
q19409
VATManager.findFirst
train
@Nullable public IVATItem findFirst (@Nonnull final Predicate <? super IVATItem> aFilter) { return CollectionHelper.findFirst (m_aAllVATItems.values (), aFilter); }
java
{ "resource": "" }
q19410
VATManager.findAll
train
@Nonnull @ReturnsMutableCopy public ICommonsList <IVATItem> findAll (@Nonnull final Predicate <? super IVATItem> aFilter) { final ICommonsList <IVATItem> ret = new CommonsArrayList <> (); CollectionHelper.findAll (m_aAllVATItems.values (), aFilter, ret::add); return ret; }
java
{ "resource": "" }
q19411
StringUtilities.serialize
train
static private String serialize(Throwable ex, int depth, int level) { StringBuffer buff = new StringBuffer(); String str = ex.toString(); // Split the first line if it's too long int pos = str.indexOf(":"); if(str.length() < 80 || pos == -1) { buff.append(str); } else { String str1 = str.substring(0, pos); String str2 = str.substring(pos+2); if(str2.indexOf(str1) == -1) { buff.append(str1); buff.append(": \n\t"); } buff.append(str2); } if(depth > 0) { StackTraceElement[] elements = ex.getStackTrace(); for(int i = 0; i < elements.length; i++) { buff.append("\n\tat "); buff.append(elements[i]); if(i == (depth-1) && elements.length > depth) { buff.append("\n\t... "+(elements.length-depth)+" more ..."); i = elements.length; } } } if(ex.getCause() != null && level < 3) { buff.append("\nCaused by: "); buff.append(serialize(ex.getCause(), depth, ++level)); } return buff.toString(); }
java
{ "resource": "" }
q19412
StringUtilities.serialize
train
public static String serialize(Object[] objs) { StringBuffer buff = new StringBuffer(); for(int i = 0; i < objs.length; i++) { if(objs[i] != null) { buff.append(objs[i].toString()); if(i != objs.length-1) buff.append(","); } } return buff.toString(); }
java
{ "resource": "" }
q19413
StringUtilities.encode
train
public static String encode(String str) { String ret = str; try { // Obfuscate the string if(ret != null) ret = new String(Base64.encodeBase64(ret.getBytes())); } catch(NoClassDefFoundError e) { System.out.println("WARNING: unable to encode: " +e.getClass().getName()+": "+e.getMessage()); } return ret; }
java
{ "resource": "" }
q19414
StringUtilities.encodeBytes
train
public static String encodeBytes(byte[] bytes) { String ret = null; try { // Obfuscate the string if(bytes != null) ret = new String(Base64.encodeBase64(bytes)); } catch(NoClassDefFoundError e) { ret = new String(bytes); System.out.println("WARNING: unable to encode: " +e.getClass().getName()+": "+e.getMessage()); } return ret; }
java
{ "resource": "" }
q19415
StringUtilities.decode
train
public static String decode(String str) { String ret = str; try { // De-obfuscate the string if(ret != null) ret = new String(Base64.decodeBase64(ret.getBytes())); } catch(NoClassDefFoundError e) { System.out.println("WARNING: unable to decode: " +e.getClass().getName()+": "+e.getMessage()); } return ret; }
java
{ "resource": "" }
q19416
StringUtilities.decodeBytes
train
public static byte[] decodeBytes(String str) { byte[] ret = null; try { // De-obfuscate the string if(str != null) ret = Base64.decodeBase64(str.getBytes()); } catch(NoClassDefFoundError e) { ret = str.getBytes(); System.out.println("WARNING: unable to decode: " +e.getClass().getName()+": "+e.getMessage()); } return ret; }
java
{ "resource": "" }
q19417
StringUtilities.truncate
train
public static String truncate(String str, int count) { if(count < 0 || str.length() <= count) return str; int pos = count; for(int i = count; i >= 0 && !Character.isWhitespace(str.charAt(i)); i--, pos--); return str.substring(0, pos)+"..."; }
java
{ "resource": "" }
q19418
StringUtilities.getOccurenceCount
train
public static int getOccurenceCount(char c, String s) { int ret = 0; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == c) ++ret; } return ret; }
java
{ "resource": "" }
q19419
StringUtilities.getOccurrenceCount
train
public static int getOccurrenceCount(String expr, String str) { int ret = 0; Pattern p = Pattern.compile(expr); Matcher m = p.matcher(str); while(m.find()) ++ret; return ret; }
java
{ "resource": "" }
q19420
StringUtilities.endsWith
train
public static boolean endsWith(StringBuffer buffer, String suffix) { if (suffix.length() > buffer.length()) return false; int endIndex = suffix.length() - 1; int bufferIndex = buffer.length() - 1; while (endIndex >= 0) { if (buffer.charAt(bufferIndex) != suffix.charAt(endIndex)) return false; bufferIndex--; endIndex--; } return true; }
java
{ "resource": "" }
q19421
StringUtilities.toReadableForm
train
public static String toReadableForm(String str) { String ret = str; if(str != null && str.length() > 0 && str.indexOf("\n") != -1 && str.indexOf("\r") == -1) { str.replaceAll("\n", "\r\n"); } return ret; }
java
{ "resource": "" }
q19422
StringUtilities.urlEncode
train
public static String urlEncode(String str) { String ret = str; try { ret = URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.severe("Failed to encode value: "+str); } return ret; }
java
{ "resource": "" }
q19423
StringUtilities.stripSpaces
train
public static String stripSpaces(String s) { StringBuffer buff = new StringBuffer(); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c != ' ') buff.append(c); } return buff.toString(); }
java
{ "resource": "" }
q19424
StringUtilities.removeControlCharacters
train
public static String removeControlCharacters(String s, boolean removeCR) { String ret = s; if(ret != null) { ret = ret.replaceAll("_x000D_",""); if(removeCR) ret = ret.replaceAll("\r",""); } return ret; }
java
{ "resource": "" }
q19425
StringUtilities.printCharacters
train
public static void printCharacters(String s) { if(s != null) { logger.info("string length="+s.length()); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); logger.info("char["+i+"]="+c+" ("+(int)c+")"); } } }
java
{ "resource": "" }
q19426
StringUtilities.stripDoubleQuotes
train
public static String stripDoubleQuotes(String s) { String ret = s; if(hasDoubleQuotes(s)) ret = s.substring(1, s.length()-1); return ret; }
java
{ "resource": "" }
q19427
StringUtilities.stripClassNames
train
public static String stripClassNames(String str) { String ret = str; if(ret != null) { while(ret.startsWith("java.security.PrivilegedActionException:") || ret.startsWith("com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl:") || ret.startsWith("javax.jms.JMSSecurityException:")) { ret = ret.substring(ret.indexOf(":")+1).trim(); } } return ret; }
java
{ "resource": "" }
q19428
StringUtilities.stripDomain
train
public static String stripDomain(String hostname) { String ret = hostname; int pos = hostname.indexOf("."); if(pos != -1) ret = hostname.substring(0,pos); return ret; }
java
{ "resource": "" }
q19429
BaseClassFinderService.findClass
train
public Class<?> findClass(String className, String versionRange) { //if (ClassServiceBootstrap.repositoryAdmin == null) // return null; Class<?> c = this.getClassFromBundle(null, className, versionRange); if (c == null) { Object resource = this.deployThisResource(ClassFinderActivator.getPackageName(className, false), versionRange, false); if (resource != null) { c = this.getClassFromBundle(null, className, versionRange); // It is possible that the newly started bundle registered itself if (c == null) c = this.getClassFromBundle(resource, className, versionRange); } } return c; }
java
{ "resource": "" }
q19430
BaseClassFinderService.findResourceURL
train
public URL findResourceURL(String resourcePath, String versionRange) { //if (ClassServiceBootstrap.repositoryAdmin == null) // return null; URL url = this.getResourceFromBundle(null, resourcePath, versionRange); if (url == null) { Object resource = this.deployThisResource(ClassFinderActivator.getPackageName(resourcePath, true), versionRange, false); if (resource != null) url = this.getResourceFromBundle(resource, resourcePath, versionRange); } return url; }
java
{ "resource": "" }
q19431
BaseClassFinderService.findResourceBundle
train
public ResourceBundle findResourceBundle(String resourcePath, Locale locale, String versionRange) { //if (ClassServiceBootstrap.repositoryAdmin == null) // return null; ResourceBundle resourceBundle = this.getResourceBundleFromBundle(null, resourcePath, locale, versionRange); if (resourceBundle == null) { Object resource = this.deployThisResource(ClassFinderActivator.getPackageName(resourcePath, true), versionRange, false); if (resource != null) { resourceBundle = this.getResourceBundleFromBundle(resource, resourcePath, locale, versionRange); if (resourceBundle == null) { Class<?> c = this.getClassFromBundle(resource, resourcePath, versionRange); if (c != null) { try { resourceBundle = (ResourceBundle)c.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); // Never } catch (IllegalAccessException e) { e.printStackTrace(); // Never } catch (Exception e) { e.printStackTrace(); // Never } } } } } return resourceBundle; }
java
{ "resource": "" }
q19432
BaseClassFinderService.shutdownService
train
public boolean shutdownService(String serviceClass, Object service) { if (service == null) return false; if (bundleContext == null) return false; String filter = null; if (serviceClass == null) if (!(service instanceof String)) serviceClass = service.getClass().getName(); if (service instanceof String) filter = ClassServiceUtility.addToFilter("", BundleConstants.SERVICE_PID, (String)service); ServiceReference[] refs; try { refs = bundleContext.getServiceReferences(serviceClass, filter); if ((refs == null) || (refs.length == 0)) return false; for (ServiceReference reference : refs) { if ((bundleContext.getService(reference) == service) || (service instanceof String)) { if (refs.length == 1) { // Last/only one, shut down the service // Lame code String dependentBaseBundleClassName = service.getClass().getName(); String packageName = ClassFinderActivator.getPackageName(dependentBaseBundleClassName, false); if (service instanceof String) packageName = (String)service; Bundle bundle = this.findBundle(null, bundleContext, packageName, null); if (bundle != null) if ((bundle.getState() & Bundle.ACTIVE) != 0) { try { bundle.stop(); } catch (BundleException e) { e.printStackTrace(); } } return true; } } } } catch (InvalidSyntaxException e1) { e1.printStackTrace(); } return false; // Not found? }
java
{ "resource": "" }
q19433
BaseClassFinderService.startBundle
train
public void startBundle(Bundle bundle) { if (bundle != null) if ((bundle.getState() != Bundle.ACTIVE) && (bundle.getState() != Bundle.STARTING)) { try { bundle.start(); } catch (BundleException e) { e.printStackTrace(); } } }
java
{ "resource": "" }
q19434
BaseClassFinderService.getProperties
train
@SuppressWarnings("unchecked") @Override public Dictionary<String, String> getProperties(String servicePid) { Dictionary<String, String> properties = null; try { if (servicePid != null) { ServiceReference caRef = bundleContext.getServiceReference(ConfigurationAdmin.class.getName()); if (caRef != null) { ConfigurationAdmin configAdmin = (ConfigurationAdmin)bundleContext.getService(caRef); Configuration config = configAdmin.getConfiguration(servicePid); properties = config.getProperties(); } } } catch (IOException e) { e.printStackTrace(); } return properties; }
java
{ "resource": "" }
q19435
BaseClassFinderService.saveProperties
train
@Override public boolean saveProperties(String servicePid, Dictionary<String, String> properties) { try { if (servicePid != null) { ServiceReference caRef = bundleContext.getServiceReference(ConfigurationAdmin.class.getName()); if (caRef != null) { ConfigurationAdmin configAdmin = (ConfigurationAdmin)bundleContext.getService(caRef); Configuration config = configAdmin.getConfiguration(servicePid); config.update(properties); return true; } } } catch (IOException e) { e.printStackTrace(); } return false; }
java
{ "resource": "" }
q19436
Bytes.read
train
public static byte[] read(InputStream in, boolean closeAfterwards) throws IOException { byte[] buffer = new byte[32*1024]; ByteArrayOutputStream bas = new ByteArrayOutputStream(); for (int length; (length = in.read(buffer, 0, buffer.length)) > -1; bas.write(buffer, 0, length)); if (closeAfterwards) in.close(); return bas.toByteArray(); }
java
{ "resource": "" }
q19437
AlertPolicyCache.add
train
public void add(Collection<AlertPolicy> policies) { for(AlertPolicy policy : policies) this.policies.put(policy.getId(), policy); }
java
{ "resource": "" }
q19438
AlertPolicyCache.alertChannels
train
public AlertChannelCache alertChannels(long policyId) { AlertChannelCache cache = channels.get(policyId); if(cache == null) channels.put(policyId, cache = new AlertChannelCache(policyId)); return cache; }
java
{ "resource": "" }
q19439
AlertPolicyCache.setAlertChannels
train
public void setAlertChannels(Collection<AlertChannel> channels) { for(AlertChannel channel : channels) { // Add the channel to any policies it is associated with List<Long> policyIds = channel.getLinks().getPolicyIds(); for(long policyId : policyIds) { AlertPolicy policy = policies.get(policyId); if(policy != null) alertChannels(policyId).add(channel); else logger.severe(String.format("Unable to find policy for channel '%s': %d", channel.getName(), policyId)); } } }
java
{ "resource": "" }
q19440
AlertPolicyCache.alertConditions
train
public AlertConditionCache alertConditions(long policyId) { AlertConditionCache cache = conditions.get(policyId); if(cache == null) conditions.put(policyId, cache = new AlertConditionCache(policyId)); return cache; }
java
{ "resource": "" }
q19441
AlertPolicyCache.nrqlAlertConditions
train
public NrqlAlertConditionCache nrqlAlertConditions(long policyId) { NrqlAlertConditionCache cache = nrqlConditions.get(policyId); if(cache == null) nrqlConditions.put(policyId, cache = new NrqlAlertConditionCache(policyId)); return cache; }
java
{ "resource": "" }
q19442
AlertPolicyCache.externalServiceAlertConditions
train
public ExternalServiceAlertConditionCache externalServiceAlertConditions(long policyId) { ExternalServiceAlertConditionCache cache = externalServiceConditions.get(policyId); if(cache == null) externalServiceConditions.put(policyId, cache = new ExternalServiceAlertConditionCache(policyId)); return cache; }
java
{ "resource": "" }
q19443
AlertPolicyCache.syntheticsAlertConditions
train
public SyntheticsAlertConditionCache syntheticsAlertConditions(long policyId) { SyntheticsAlertConditionCache cache = syntheticsConditions.get(policyId); if(cache == null) syntheticsConditions.put(policyId, cache = new SyntheticsAlertConditionCache(policyId)); return cache; }
java
{ "resource": "" }
q19444
AlertPolicyCache.pluginsAlertConditions
train
public PluginsAlertConditionCache pluginsAlertConditions(long policyId) { PluginsAlertConditionCache cache = pluginsConditions.get(policyId); if(cache == null) pluginsConditions.put(policyId, cache = new PluginsAlertConditionCache(policyId)); return cache; }
java
{ "resource": "" }
q19445
AlertPolicyCache.infraAlertConditions
train
public InfraAlertConditionCache infraAlertConditions(long policyId) { InfraAlertConditionCache cache = infraConditions.get(policyId); if(cache == null) infraConditions.put(policyId, cache = new InfraAlertConditionCache(policyId)); return cache; }
java
{ "resource": "" }
q19446
Log.defaultWriter
train
static PrintWriter defaultWriter(Context context) { PrintWriter result = context.get(outKey); if (result == null) context.put(outKey, result = new PrintWriter(System.err)); return result; }
java
{ "resource": "" }
q19447
Log.initRound
train
public void initRound(Log other) { this.noticeWriter = other.noticeWriter; this.warnWriter = other.warnWriter; this.errWriter = other.errWriter; this.sourceMap = other.sourceMap; this.recorded = other.recorded; this.nerrors = other.nerrors; this.nwarnings = other.nwarnings; }
java
{ "resource": "" }
q19448
JavacState.setVisibleSources
train
public void setVisibleSources(Map<String,Source> vs) { visibleSrcs = new HashSet<URI>(); for (String s : vs.keySet()) { Source src = vs.get(s); visibleSrcs.add(src.file().toURI()); } }
java
{ "resource": "" }
q19449
JavacState.save
train
public void save() throws IOException { if (!needsSaving) return; try (FileWriter out = new FileWriter(javacStateFilename)) { StringBuilder b = new StringBuilder(); long millisNow = System.currentTimeMillis(); Date d = new Date(millisNow); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); b.append("# javac_state ver 0.3 generated "+millisNow+" "+df.format(d)+"\n"); b.append("# This format might change at any time. Please do not depend on it.\n"); b.append("# M module\n"); b.append("# P package\n"); b.append("# S C source_tobe_compiled timestamp\n"); b.append("# S L link_only_source timestamp\n"); b.append("# G C generated_source timestamp\n"); b.append("# A artifact timestamp\n"); b.append("# D dependency\n"); b.append("# I pubapi\n"); b.append("# R arguments\n"); b.append("R ").append(theArgs).append("\n"); // Copy over the javac_state for the packages that did not need recompilation. now.copyPackagesExcept(prev, recompiledPackages, new HashSet<String>()); // Save the packages, ie package names, dependencies, pubapis and artifacts! // I.e. the lot. Module.saveModules(now.modules(), b); String s = b.toString(); out.write(s, 0, s.length()); } }
java
{ "resource": "" }
q19450
JavacState.performJavaCompilations
train
public boolean performJavaCompilations(File binDir, String serverSettings, String[] args, Set<String> recentlyCompiled, boolean[] rcValue) { Map<String,Transformer> suffixRules = new HashMap<String,Transformer>(); suffixRules.put(".java", compileJavaPackages); compileJavaPackages.setExtra(serverSettings); compileJavaPackages.setExtra(args); rcValue[0] = perform(binDir, suffixRules); recentlyCompiled.addAll(taintedPackages()); clearTaintedPackages(); boolean again = !packagesWithChangedPublicApis.isEmpty(); taintPackagesDependingOnChangedPackages(packagesWithChangedPublicApis, recentlyCompiled); packagesWithChangedPublicApis = new HashSet<String>(); return again && rcValue[0]; }
java
{ "resource": "" }
q19451
JavacState.addFileToTransform
train
private void addFileToTransform(Map<Transformer,Map<String,Set<URI>>> gs, Transformer t, Source s) { Map<String,Set<URI>> fs = gs.get(t); if (fs == null) { fs = new HashMap<String,Set<URI>>(); gs.put(t, fs); } Set<URI> ss = fs.get(s.pkg().name()); if (ss == null) { ss = new HashSet<URI>(); fs.put(s.pkg().name(), ss); } ss.add(s.file().toURI()); }
java
{ "resource": "" }
q19452
DeprecatedAPIListBuilder.buildDeprecatedAPIInfo
train
private void buildDeprecatedAPIInfo(Configuration configuration) { PackageDoc[] packages = configuration.packages; PackageDoc pkg; for (int c = 0; c < packages.length; c++) { pkg = packages[c]; if (Util.isDeprecated(pkg)) { getList(PACKAGE).add(pkg); } } ClassDoc[] classes = configuration.root.classes(); for (int i = 0; i < classes.length; i++) { ClassDoc cd = classes[i]; if (Util.isDeprecated(cd)) { if (cd.isOrdinaryClass()) { getList(CLASS).add(cd); } else if (cd.isInterface()) { getList(INTERFACE).add(cd); } else if (cd.isException()) { getList(EXCEPTION).add(cd); } else if (cd.isEnum()) { getList(ENUM).add(cd); } else if (cd.isError()) { getList(ERROR).add(cd); } else if (cd.isAnnotationType()) { getList(ANNOTATION_TYPE).add(cd); } } composeDeprecatedList(getList(FIELD), cd.fields()); composeDeprecatedList(getList(METHOD), cd.methods()); composeDeprecatedList(getList(CONSTRUCTOR), cd.constructors()); if (cd.isEnum()) { composeDeprecatedList(getList(ENUM_CONSTANT), cd.enumConstants()); } if (cd.isAnnotationType()) { composeDeprecatedList(getList(ANNOTATION_TYPE_MEMBER), ((AnnotationTypeDoc) cd).elements()); } } sortDeprecatedLists(); }
java
{ "resource": "" }
q19453
Validator.parse
train
public Object parse(String text) throws DataValidationException { try { preValidate(text); Object object = _valueOf.invoke(text); postValidate(object); return object; } catch (DataValidationException x) { throw x; } catch (IllegalArgumentException x) { // various format errors from valueOf() - ignore the details throw new DataValidationException("FORMAT", _name, text); } catch (Throwable t) { throw new DataValidationException("", _name, text, t); } }
java
{ "resource": "" }
q19454
Validator.preValidate
train
public void preValidate(String text) throws DataValidationException { // size Trace.g.std.note(Validator.class, "preValidate: size = " + _size); if (_size > 0 && text.length() > _size) { throw new DataValidationException("SIZE", _name, text); } // pattern Trace.g.std.note(Validator.class, "preValidate: pattern = " + _pattern); if (_pattern != null && !_pattern.matcher(text).matches()) { throw new DataValidationException("PATTERN", _name, text); } }
java
{ "resource": "" }
q19455
Validator.postValidate
train
@SuppressWarnings("unchecked") public void postValidate(Object object) throws DataValidationException { if (_values != null || _ranges != null) { if (_values != null) for (Object value: _values) { if (value.equals(object)) return; } if (_ranges != null) for (@SuppressWarnings("rawtypes") Range r: _ranges) { @SuppressWarnings("rawtypes") Comparable o = (Comparable)object; if (r.inclusive) { if ((r.min == null || r.min.compareTo(o) <= 0) && (r.max == null || o.compareTo(r.max) <= 0)) { return; } } else { if ((r.min == null || r.min.compareTo(o) < 0) && (r.max == null || o.compareTo(r.max) < 0)) { return; } } } throw new DataValidationException("VALUES/RANGES", _name, object); } }
java
{ "resource": "" }
q19456
Player.startRobot
train
public void startRobot(Robot newRobot) { newRobot.getData().setActiveState(DEFAULT_START_STATE); Thread newThread = new Thread(robotsThreads, newRobot, "Bot-" + newRobot.getSerialNumber()); newThread.start(); // jumpstarts the robot }
java
{ "resource": "" }
q19457
Player.loadPlayers
train
public static List<Player> loadPlayers(List<String> playersFiles) throws PlayerException { log.info("[loadPlayers] Loading all players"); List<Player> players = new ArrayList<>(); if (playersFiles.size() < 1) { log.warn("[loadPlayers] No players to load"); } for (String singlePath : playersFiles) { Player single = new Player(new File(singlePath)); players.add(single); } return players; }
java
{ "resource": "" }
q19458
DashboardCache.add
train
public void add(Collection<Dashboard> dashboards) { for(Dashboard dashboard : dashboards) this.dashboards.put(dashboard.getId(), dashboard); }
java
{ "resource": "" }
q19459
ThresholdEventWriter.write
train
@Override public synchronized void write(final Event event) throws IOException { if (!acceptsEvents) { log.warn("Writer not ready, discarding event: {}", event); return; } delegate.write(event); uncommittedWriteCount++; commitIfNeeded(); }
java
{ "resource": "" }
q19460
ThresholdEventWriter.forceCommit
train
@Managed(description = "Commit locally spooled events for flushing") @Override public synchronized void forceCommit() throws IOException { log.debug("Performing commit on delegate EventWriter [{}]", delegate.getClass()); delegate.commit(); uncommittedWriteCount = 0; lastCommitNanos = getNow(); }
java
{ "resource": "" }
q19461
OptionalFunction.orElse
train
public OptionalFunction<T, R> orElse(Supplier<R> supplier) { return new OptionalFunction<>(function, supplier); }
java
{ "resource": "" }
q19462
OptionalFunction.orElseThrow
train
public OptionalFunction<T, R> orElseThrow(Supplier<? extends RuntimeException> exceptionSupplier) { return new OptionalFunction<>(this.function, () -> { throw exceptionSupplier.get(); }); }
java
{ "resource": "" }
q19463
AppTimeZone.getTimeZone
train
public static TimeZone getTimeZone(String name) { TimeZone ret = null; if(timezones != null) { for(int i = 0; i < timezones.length && ret == null; i++) { if(timezones[i].getName().equals(name)) ret = timezones[i].getTimeZone(); } } return ret; }
java
{ "resource": "" }
q19464
AppTimeZone.getTimeZoneById
train
public static TimeZone getTimeZoneById(String id) { TimeZone ret = null; if(timezones != null) { for(int i = 0; i < timezones.length && ret == null; i++) { if(timezones[i].getId().equals(id)) ret = timezones[i].getTimeZone(); } } return ret; }
java
{ "resource": "" }
q19465
AppTimeZone.getTimeZoneByIdIgnoreCase
train
public static TimeZone getTimeZoneByIdIgnoreCase(String id) { TimeZone ret = null; if(timezones != null) { id = id.toLowerCase(); for(int i = 0; i < timezones.length && ret == null; i++) { if(timezones[i].getId().toLowerCase().equals(id)) ret = timezones[i].getTimeZone(); } } return ret; }
java
{ "resource": "" }
q19466
AppTimeZone.getDisplayName
train
private String getDisplayName() { long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset()); long minutes = Math.abs(TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset()) -TimeUnit.HOURS.toMinutes(hours)); return String.format("(GMT%+d:%02d) %s", hours, minutes, tz.getID()); }
java
{ "resource": "" }
q19467
MandatoryWarningHandler.report
train
public void report(DiagnosticPosition pos, String msg, Object... args) { JavaFileObject currentSource = log.currentSourceFile(); if (verbose) { if (sourcesWithReportedWarnings == null) sourcesWithReportedWarnings = new HashSet<JavaFileObject>(); if (log.nwarnings < log.MaxWarnings) { // generate message and remember the source file logMandatoryWarning(pos, msg, args); sourcesWithReportedWarnings.add(currentSource); } else if (deferredDiagnosticKind == null) { // set up deferred message if (sourcesWithReportedWarnings.contains(currentSource)) { // more errors in a file that already has reported warnings deferredDiagnosticKind = DeferredDiagnosticKind.ADDITIONAL_IN_FILE; } else { // warnings in a new source file deferredDiagnosticKind = DeferredDiagnosticKind.IN_FILE; } deferredDiagnosticSource = currentSource; deferredDiagnosticArg = currentSource; } else if ((deferredDiagnosticKind == DeferredDiagnosticKind.IN_FILE || deferredDiagnosticKind == DeferredDiagnosticKind.ADDITIONAL_IN_FILE) && !equal(deferredDiagnosticSource, currentSource)) { // additional errors in more than one source file deferredDiagnosticKind = DeferredDiagnosticKind.ADDITIONAL_IN_FILES; deferredDiagnosticArg = null; } } else { if (deferredDiagnosticKind == null) { // warnings in a single source deferredDiagnosticKind = DeferredDiagnosticKind.IN_FILE; deferredDiagnosticSource = currentSource; deferredDiagnosticArg = currentSource; } else if (deferredDiagnosticKind == DeferredDiagnosticKind.IN_FILE && !equal(deferredDiagnosticSource, currentSource)) { // warnings in multiple source files deferredDiagnosticKind = DeferredDiagnosticKind.IN_FILES; deferredDiagnosticArg = null; } } }
java
{ "resource": "" }
q19468
ProtocolUtils.combineInts
train
public static long combineInts(String high, String low) throws NumberFormatException { int highInt = Integer.parseInt(high); int lowInt = Integer.parseInt(low); /* * Shift the high integer into the upper 32 bits and add the low * integer. However, since this is really a single set of bits split in * half, the low part cannot be treated as negative by itself. Since * Java has no unsigned types, the top half of the long created by * up-casting the lower integer must be zeroed out before it's added. */ return ((long)highInt << 32) + (lowInt & 0x00000000FFFFFFFFL); }
java
{ "resource": "" }
q19469
ProtocolUtils.splitLong
train
public static Pair<String, String> splitLong(long value) { return Pair.of(String.valueOf((int)(value >> 32)), String.valueOf((int)value)); }
java
{ "resource": "" }
q19470
CommandUtils.sendExpectOk
train
public static void sendExpectOk(SocketManager socketManager, String message) throws IOException { expectOk(socketManager.sendAndWait(message)); }
java
{ "resource": "" }
q19471
CommandUtils.expectOk
train
public static void expectOk(String response) throws ProtocolException { if (!"OK".equalsIgnoreCase(response)) { throw new ProtocolException(response, Direction.RECEIVE); } }
java
{ "resource": "" }
q19472
Messager.printError
train
public void printError(SourcePosition pos, String msg) { if (diagListener != null) { report(DiagnosticType.ERROR, pos, msg); return; } if (nerrors < MaxErrors) { String prefix = (pos == null) ? programName : pos.toString(); errWriter.println(prefix + ": " + getText("javadoc.error") + " - " + msg); errWriter.flush(); prompt(); nerrors++; } }
java
{ "resource": "" }
q19473
StructTypeConverter.unmarshal
train
public Object unmarshal(Object map) throws RpcException { return unmarshal(getTypeClass(), map, this.s, this.isOptional); }
java
{ "resource": "" }
q19474
StructTypeConverter.marshal
train
@SuppressWarnings("unchecked") public Object marshal(Object o) throws RpcException { if (o == null) { return returnNullIfOptional(); } else if (o instanceof BStruct) { return validateMap(structToMap(o, this.s), this.s); } else if (o instanceof Map) { return validateMap((Map)o, this.s); } else { String msg = "Unable to convert class: " + o.getClass().getName(); throw RpcException.Error.INVALID_RESP.exc(msg); } }
java
{ "resource": "" }
q19475
GAEBlobServlet.getUploadUrl
train
private void getUploadUrl(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { LOGGER.debug("Get blobstore upload url"); String callback = req.getParameter(CALLBACK_PARAM); if (null == callback) { callback = req.getRequestURI(); } String keepQueryParam = req.getParameter(KEEP_QUERY_PARAM); // Forward any existing query parameters, e.g. access_token if (null != keepQueryParam) { final String queryString = req.getQueryString(); callback = String.format("%s?%s", callback, null != queryString ? queryString : ""); } Map<String, String> response = ImmutableMap.of("uploadUrl", blobstoreService.createUploadUrl(callback)); PrintWriter out = resp.getWriter(); resp.setContentType(JsonCharacterEncodingResponseFilter.APPLICATION_JSON_UTF8); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(out, response); out.close(); }
java
{ "resource": "" }
q19476
GAEBlobServlet.getEncodeFileName
train
private static String getEncodeFileName(String userAgent, String fileName) { String encodedFileName = fileName; try { if (userAgent.contains("MSIE") || userAgent.contains("Opera")) { encodedFileName = URLEncoder.encode(fileName, "UTF-8"); } else { encodedFileName = "=?UTF-8?B?" + new String(BaseEncoding.base64().encode(fileName.getBytes("UTF-8"))) + "?="; } } catch (Exception e) { LOGGER.error(e.getMessage()); } return encodedFileName; }
java
{ "resource": "" }
q19477
Annotate.enterAnnotation
train
Attribute.Compound enterAnnotation(JCAnnotation a, Type expected, Env<AttrContext> env) { return enterAnnotation(a, expected, env, false); }
java
{ "resource": "" }
q19478
Annotate.getContainingType
train
private Type getContainingType(Attribute.Compound currentAnno, DiagnosticPosition pos, boolean reportError) { Type origAnnoType = currentAnno.type; TypeSymbol origAnnoDecl = origAnnoType.tsym; // Fetch the Repeatable annotation from the current // annotation's declaration, or null if it has none Attribute.Compound ca = origAnnoDecl.attribute(syms.repeatableType.tsym); if (ca == null) { // has no Repeatable annotation if (reportError) log.error(pos, "duplicate.annotation.missing.container", origAnnoType, syms.repeatableType); return null; } return filterSame(extractContainingType(ca, pos, origAnnoDecl), origAnnoType); }
java
{ "resource": "" }
q19479
XlsxWorkbook.getSheetNames
train
@Override public String[] getSheetNames() { String[] ret = null; if(sheets != null) { ret = new String[sheets.size()]; for(int i = 0; i < sheets.size(); i++) { Sheet sheet = (Sheet)sheets.get(i); ret[i] = sheet.getName(); } } return ret; }
java
{ "resource": "" }
q19480
XlsxWorkbook.getSharedString
train
public String getSharedString(int i) { String ret = null; CTRst string = strings.getSi().get(i); if(string != null && string.getT() != null) ret = string.getT().getValue(); if(ret == null) // cell has multiple formats or fonts { List<CTRElt> list = string.getR(); if(list.size() > 0) { for(CTRElt lt : list) { String str = lt.getT().getValue(); if(str != null) { if(ret == null) ret = ""; ret += str; } } } } return ret; }
java
{ "resource": "" }
q19481
XlsxWorkbook.getFormatCode
train
public String getFormatCode(long id) { if(numFmts == null) cacheFormatCodes(); return (String)numFmts.get(new Long(id)); }
java
{ "resource": "" }
q19482
XlsxWorkbook.addFormatCode
train
private void addFormatCode(CTNumFmt fmt) { if(numFmts == null) numFmts = new HashMap(); numFmts.put(fmt.getNumFmtId(), fmt.getFormatCode()); }
java
{ "resource": "" }
q19483
XlsxWorkbook.getFormatId
train
private long getFormatId(String formatCode) { long ret = 0L; if(formatCode != null && formatCode.length() > 0) { if(numFmts != null) { Iterator it = numFmts.entrySet().iterator(); while(it.hasNext() && ret == 0L) { java.util.Map.Entry entry = (java.util.Map.Entry)it.next(); Long id = (Long)entry.getKey(); String code = (String)entry.getValue(); if(code != null && code.equals(formatCode)) ret = id.longValue(); } } // If not found, also search // the built-in formats if(ret == 0L) { Long l = (Long)builtinNumFmts.get(formatCode); if(l != null) ret = l.longValue(); } // If still not found, // create a new format if(ret == 0L) { CTNumFmts numFmts = stylesheet.getNumFmts(); if(numFmts == null) { numFmts = new CTNumFmts(); stylesheet.setNumFmts(numFmts); } List list = numFmts.getNumFmt(); CTNumFmt numFmt = new CTNumFmt(); numFmt.setNumFmtId(getMaxNumFmtId()+1); numFmt.setFormatCode(formatCode); list.add(numFmt); numFmts.setCount((long)list.size()); addFormatCode(numFmt); ret = numFmt.getNumFmtId(); } } return ret; }
java
{ "resource": "" }
q19484
XlsxWorkbook.getMaxNumFmtId
train
private long getMaxNumFmtId() { long ret = 163; List list = stylesheet.getNumFmts().getNumFmt(); for(int i = 0; i < list.size(); i++) { CTNumFmt numFmt = (CTNumFmt)list.get(i); if(numFmt.getNumFmtId() > ret) ret = numFmt.getNumFmtId(); } return ret; }
java
{ "resource": "" }
q19485
cufftHandle.setSize
train
void setSize(int x, int y, int z) { this.sizeX = x; this.sizeY = y; this.sizeZ = z; }
java
{ "resource": "" }
q19486
MethodUtils.invoke
train
public static Object invoke(Object source, String methodName, Class<?>[] parameterTypes, Object[] parameterValues) throws MethodException { Class<? extends Object> clazz = source.getClass(); Method method; if (ArrayUtils.isEmpty(parameterTypes)) { method = findMethod(clazz, methodName, EMPTY_PARAMETER_CLASSTYPES); return invoke(source, method, EMPTY_PARAMETER_VALUES); } method = findMethod(clazz, methodName, parameterTypes); return invoke(source, method, parameterValues); }
java
{ "resource": "" }
q19487
MethodUtils.invoke
train
public static Object invoke(Object source, Method method, Object[] parameterValues) throws MethodException { try { return method.invoke(source, parameterValues); } catch (Exception e) { throw new MethodException(INVOKE_METHOD_FAILED, e); } }
java
{ "resource": "" }
q19488
ApplicationHostCache.add
train
public void add(Collection<ApplicationHost> applicationHosts) { for(ApplicationHost applicationHost : applicationHosts) this.applicationHosts.put(applicationHost.getId(), applicationHost); }
java
{ "resource": "" }
q19489
ApplicationHostCache.applicationInstances
train
public ApplicationInstanceCache applicationInstances(long applicationHostId) { ApplicationInstanceCache cache = applicationInstances.get(applicationHostId); if(cache == null) applicationInstances.put(applicationHostId, cache = new ApplicationInstanceCache(applicationHostId)); return cache; }
java
{ "resource": "" }
q19490
ApplicationHostCache.addApplicationInstances
train
public void addApplicationInstances(Collection<ApplicationInstance> applicationInstances) { for(ApplicationInstance applicationInstance : applicationInstances) { // Add the instance to any application hosts it is associated with long applicationHostId = applicationInstance.getLinks().getApplicationHost(); ApplicationHost applicationHost = applicationHosts.get(applicationHostId); if(applicationHost != null) applicationInstances(applicationHostId).add(applicationInstance); else logger.severe(String.format("Unable to find application host for application instance '%s': %d", applicationInstance.getName(), applicationHostId)); } }
java
{ "resource": "" }
q19491
ClassReader.instance
train
public static ClassReader instance(Context context) { ClassReader instance = context.get(classReaderKey); if (instance == null) instance = new ClassReader(context, true); return instance; }
java
{ "resource": "" }
q19492
ClassReader.init
train
private void init(Symtab syms, boolean definitive) { if (classes != null) return; if (definitive) { Assert.check(packages == null || packages == syms.packages); packages = syms.packages; Assert.check(classes == null || classes == syms.classes); classes = syms.classes; } else { packages = new HashMap<Name, PackageSymbol>(); classes = new HashMap<Name, ClassSymbol>(); } packages.put(names.empty, syms.rootPackage); syms.rootPackage.completer = thisCompleter; syms.unnamedPackage.completer = thisCompleter; }
java
{ "resource": "" }
q19493
ClassReader.readClassFile
train
private void readClassFile(ClassSymbol c) throws IOException { int magic = nextInt(); if (magic != JAVA_MAGIC) throw badClassFile("illegal.start.of.class.file"); minorVersion = nextChar(); majorVersion = nextChar(); int maxMajor = Target.MAX().majorVersion; int maxMinor = Target.MAX().minorVersion; if (majorVersion > maxMajor || majorVersion * 1000 + minorVersion < Target.MIN().majorVersion * 1000 + Target.MIN().minorVersion) { if (majorVersion == (maxMajor + 1)) log.warning("big.major.version", currentClassFile, majorVersion, maxMajor); else throw badClassFile("wrong.version", Integer.toString(majorVersion), Integer.toString(minorVersion), Integer.toString(maxMajor), Integer.toString(maxMinor)); } else if (checkClassFile && majorVersion == maxMajor && minorVersion > maxMinor) { printCCF("found.later.version", Integer.toString(minorVersion)); } indexPool(); if (signatureBuffer.length < bp) { int ns = Integer.highestOneBit(bp) << 1; signatureBuffer = new byte[ns]; } readClass(c); }
java
{ "resource": "" }
q19494
ClassReader.enterPackage
train
public PackageSymbol enterPackage(Name name, PackageSymbol owner) { return enterPackage(TypeSymbol.formFullName(name, owner)); }
java
{ "resource": "" }
q19495
DaySchedule.shutdown
train
public void shutdown() { interrupt(); try { join(); } catch (Exception x) { _logger.log(Level.WARNING, "Failed to see DaySchedule thread joining", x); } }
java
{ "resource": "" }
q19496
WebListener.contextInitialized
train
@Override public void contextInitialized(ServletContextEvent sce) { Gig.bootstrap(sce.getServletContext()); Jaguar.assemble(this); }
java
{ "resource": "" }
q19497
DocumentTemplateFSAbstract.upsertType
train
protected DocumentType upsertType( String reference, String name, ExecutionContext executionContext) { DocumentType documentType = documentTypeRepository.findByReference(reference); if(documentType != null) { documentType.setName(name); } else { documentType = documentTypeRepository.create(reference, name); } return executionContext.addResult(this, documentType); }
java
{ "resource": "" }
q19498
CallLookup.getCurrentSocket
train
public static Socket getCurrentSocket() { ConnectionHandler handler = connectionMap.get(Thread.currentThread()); return (handler == null ? null : handler.getSocket()); }
java
{ "resource": "" }
q19499
ParamConfig.prepareParameter
train
public void prepareParameter(Map<String, Object> extra) { if (from != null) { from.prepareParameter(extra); } }
java
{ "resource": "" }