_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q169300 | Rulebases.getRulebase | validation | public List<Rulebases.Rulebase> getRulebase() {
if (rulebase == null) {
rulebase = new ArrayList<Rulebases.Rulebase>();
}
return this.rulebase;
} | java | {
"resource": ""
} |
q169301 | UpdateAliasesLibsMojo.addAlias | validation | private void addAlias(ArrayList<HashMap<String,Object>> list, String aliasName) {
for (HashMap<String, Object> h : list) {
String name = (String) h.get("name");
if (name != null && name.equals(aliasName)) {
return; // avoid duplicates
}
}
HashMap<String, Object> h = new HashMap<String, Object>();
h.put("isClasspathFile", Boolean.TRUE);
h.put("name", aliasName);
h.put("includeInDeployment", Boolean.TRUE);
list.add(h);
} | java | {
"resource": ""
} |
q169302 | UpdateAliasesLibsMojo.processFile | validation | public void processFile(File f) throws MojoExecutionException {
try {
RepositoryModel repositoryModel = new RepositoryModel(f);
ArrayList<HashMap<String, Object>> aliases = readXMLBean(repositoryModel, f);
// reset old references
if (!keepOriginalAliasLib) {
aliases.clear();
}
// adding the JAR dependencies
for (Dependency dependency : jarDependencies) {
addAlias(aliases, getJarAlias(dependency, false));
}
writeXMLBean(repositoryModel, f, aliases);
} catch (Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
} | java | {
"resource": ""
} |
q169303 | TOperation.getRest | validation | public List<JAXBElement<? extends TExtensibleAttributesDocumented>> getRest() {
if (rest == null) {
rest = new ArrayList<JAXBElement<? extends TExtensibleAttributesDocumented>>();
}
return this.rest;
} | java | {
"resource": ""
} |
q169304 | NameValuePairs.getNVPair | validation | public List<JAXBElement<? extends NVPairType>> getNVPair() {
if (nvPair == null) {
nvPair = new ArrayList<JAXBElement<? extends NVPairType>>();
}
return this.nvPair;
} | java | {
"resource": ""
} |
q169305 | POMManager.addDependency | validation | public static void addDependency(File pom, Dependency dependency, Log logger) throws IOException, XmlPullParserException {
Model model = getModelFromPOM(pom, logger);
model.addDependency(dependency);
writeModelToPOM(model, pom, logger);
} | java | {
"resource": ""
} |
q169306 | POMManager.removeDependency | validation | public static void removeDependency(File pom, Dependency dependency, Log logger) throws IOException, XmlPullParserException {
Model model = getModelFromPOM(pom, logger);
for (Iterator<Dependency> it = model.getDependencies().iterator(); it.hasNext();){
if (dependenciesEqual(it.next(), dependency)) {
it.remove();
}
}
writeModelToPOM(model, pom, logger);
} | java | {
"resource": ""
} |
q169307 | POMManager.dependencyExists | validation | private static boolean dependencyExists(Dependency dependency, List<Dependency> dependencies) {
for (Dependency d : dependencies) {
if (dependenciesEqual(dependency, d)) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q169308 | POMManager.dependencyExists | validation | public static boolean dependencyExists(File pom, Dependency dependency, Log logger) throws IOException, XmlPullParserException {
Model model = getModelFromPOM(pom, logger);
return dependencyExists(dependency, model.getDependencies());
} | java | {
"resource": ""
} |
q169309 | POMManager.addProjectAsModule | validation | public static void addProjectAsModule(File pom, String relativePath, String profileId, Log logger) throws IOException, XmlPullParserException {
if (relativePath == null) return;
Model model = getModelFromPOM(pom, logger);
relativePath = relativePath.replace("\\", "/");
if (profileId != null && !profileId.isEmpty()) {
Profile p = getProfile(model, profileId);
if (p != null) {
p.addModule(relativePath);
}
} else {
model.addModule(relativePath);
}
writeModelToPOM(model, pom, logger);
} | java | {
"resource": ""
} |
q169310 | POMManager.moduleExists | validation | public static boolean moduleExists(File pom, String relativePath, String profileId, Log logger) throws IOException, XmlPullParserException {
if (relativePath == null) return false;
Model model = getModelFromPOM(pom, logger);
relativePath = relativePath.replace("\\", "/");
if (profileId != null && !profileId.isEmpty()) {
Profile p = getProfile(model, profileId);
if (p != null) {
return p.getModules().indexOf(relativePath) >= 0;
}
} else {
return model.getModules().indexOf(relativePath) >= 0;
}
return false;
} | java | {
"resource": ""
} |
q169311 | AbstractBWArtifactMojo.getArtifactFile | validation | protected File getArtifactFile(File basedir, String finalName, String classifier) {
if (classifier == null) {
classifier = "";
} else if (classifier.trim().length() > 0 && !classifier.startsWith("-")) {
classifier = "-" + classifier;
}
return new File(basedir, finalName + classifier + getArtifactFileExtension());
} | java | {
"resource": ""
} |
q169312 | XPathResourceBuilderMojo.execute | validation | public void execute() throws MojoExecutionException {
if (this.resources.size() == 0) {
throw new MojoExecutionException("No resources configured");
}
// Prefered to count error instead of failing on the first one.
int errCount = 0;
// Iterate on all configured resources.
for (final XPathResource r : this.resources) {
try {
classBytesToBWJavaXPath(r);
} catch (Exception e) {
super.getLog().error(e);
errCount++;
}
}
if (errCount > 0) {
throw new MojoExecutionException("There was " + errCount
+ " error(s) during goal execution, check above.");
}
} | java | {
"resource": ""
} |
q169313 | XPathResourceBuilderMojo.extractFileContent | validation | protected String extractFileContent(final String filename)
throws IOException {
final StringBuilder sb = new StringBuilder();
String temp = "";
final BufferedReader bufferedReader = new BufferedReader(
new FileReader(filename));
try {
while (temp != null) {
temp = bufferedReader.readLine();
if (temp != null) {
sb.append(temp);
}
}
return sb.toString();
} finally {
bufferedReader.close();
}
} | java | {
"resource": ""
} |
q169314 | GenerateXMLFromPropertiesMojo.updateRepoInstances | validation | private void updateRepoInstances() {
RepoInstances repoInstances = application.getRepoInstances();
RvRepoInstance rvRepoInstance = repoInstances.getRvRepoInstance();
rvRepoInstance.setDiscoveryTimout(BigInteger.valueOf(repoRvDiscoveryTimeout));
rvRepoInstance.setTimeout(BigInteger.valueOf(repoRvTimeout));
rvRepoInstance.setDaemon(repoRvDaemon);
rvRepoInstance.setService(repoRvService);
rvRepoInstance.setNetwork(repoRvNetwork);
rvRepoInstance.setRegionalSubject(repoRvRegionalSubject);
rvRepoInstance.setOperationRetry(BigInteger.valueOf(repoRvOperationRetry));
rvRepoInstance.setExtraPropertyFile(repoRvExtraPropertyFile);
rvRepoInstance.setServer(repoRvServer);
rvRepoInstance.setUser(repoRvUser);
rvRepoInstance.setPassword(repoRvPassword);
HttpRepoInstance httpRepoInstance = repoInstances.getHttpRepoInstance();
httpRepoInstance.setTimeout(BigInteger.valueOf(repoHttpTimeout));
httpRepoInstance.setUrl(repoHttpUrl);
httpRepoInstance.setServer(repoHttpServer);
httpRepoInstance.setUser(repoHttpUser);
httpRepoInstance.setPassword(repoHttpPassword);
httpRepoInstance.setExtraPropertyFile(repoHttpExtraPropertyFile);
LocalRepoInstance localRepoInstance = repoInstances.getLocalRepoInstance();
EncodingType encoding;
try {
encoding = EncodingType.valueOf(repoLocalEncoding);
} catch (IllegalArgumentException e) {
encoding = EncodingType.UTF_8;
}
localRepoInstance.setEncoding(encoding);
repoInstances.setRvRepoInstance(rvRepoInstance);
repoInstances.setHttpRepoInstance(httpRepoInstance);
repoInstances.setLocalRepoInstance(localRepoInstance);
RepoType repoType;
try {
repoType = RepoType.valueOf(repoSelectInstance.toUpperCase());
} catch (IllegalArgumentException e) {
repoType = RepoType.LOCAL;
}
repoInstances.setSelected(repoType);
} | java | {
"resource": ""
} |
q169315 | Repository.getAny | validation | public List<java.lang.Object> getAny() {
if (any == null) {
any = new ArrayList<java.lang.Object>();
}
return this.any;
} | java | {
"resource": ""
} |
q169316 | Driver.newInstance | validation | private static <T> T newInstance(Class<T> clazz, Object... params) throws SQLException {
try {
if (params == null || params.length == 0) {
return clazz.newInstance();
} else {
for (Constructor<?> ctor : clazz.getConstructors()) {
if (ctor.getParameterTypes().length != params.length) {
continue;
}
int paramIndex = 0;
for (Class<?> paramType : ctor.getParameterTypes()) {
if (!paramType.isInstance(params[paramIndex])) {
break;
}
paramIndex++;
}
if (paramIndex != params.length) {
continue;
}
@SuppressWarnings("unchecked")
Constructor<T> theCtor = (Constructor<T>) ctor;
return theCtor.newInstance(params);
}
throw new SQLException("Constructor not found for " + clazz);
}
} catch (ReflectiveOperationException reflectiveOperationException) {
throw new SQLException(reflectiveOperationException);
}
} | java | {
"resource": ""
} |
q169317 | ProxyClass.createClass | validation | public <T> Class<T> createClass() {
return (Class<T>) Proxy.getProxyClass(getClassLoader(), getInterfaces());
} | java | {
"resource": ""
} |
q169318 | ProxyClass.createConstructor | validation | public <T> Constructor<T> createConstructor() {
try {
return this.<T>createClass().getConstructor(InvocationHandler.class);
} catch (NoSuchMethodException noSuchMethodException) {
throw new ProxyException(noSuchMethodException);
}
} | java | {
"resource": ""
} |
q169319 | MetricHelper.startStatementExecuteTimer | validation | public Timer.Context startStatementExecuteTimer(Query query) {
ensureSqlId(query);
String name = metricNamingStrategy.getStatementExecuteTimer(query.getSql(), query.getSqlId());
return startTimer(name);
} | java | {
"resource": ""
} |
q169320 | MetricHelper.startCallableStatementLifeTimer | validation | public Timer.Context startCallableStatementLifeTimer(Query query) {
ensureSqlId(query);
String name = metricNamingStrategy.getCallableStatementLifeTimer(query.getSql(), query.getSqlId());
return startTimer(name);
} | java | {
"resource": ""
} |
q169321 | MetricHelper.startResultSetLifeTimer | validation | public Timer.Context startResultSetLifeTimer(Query query) {
ensureSqlId(query);
String name = metricNamingStrategy.getResultSetLifeTimer(query.getSql(), query.getSqlId());
return startTimer(name);
} | java | {
"resource": ""
} |
q169322 | MetricHelper.markResultSetRowMeter | validation | public void markResultSetRowMeter(Query query) {
ensureSqlId(query);
String name = metricNamingStrategy.getResultSetRowMeter(query.getSql(), query.getSqlId());
markMeter(name);
} | java | {
"resource": ""
} |
q169323 | JdbcProxyFactory.newProxy | validation | private <T> T newProxy(JdbcProxyHandler<T> proxyHandler) {
return proxyFactory.newProxy(proxyHandler, proxyHandler.getProxyClass());
} | java | {
"resource": ""
} |
q169324 | JdbcProxyFactory.wrapConnection | validation | public Connection wrapConnection(Connection wrappedConnection) {
Timer.Context lifeTimerContext = metricHelper.startConnectionLifeTimer();
return newProxy(new ConnectionProxyHandler(wrappedConnection, this, lifeTimerContext));
} | java | {
"resource": ""
} |
q169325 | JdbcProxyFactory.wrapStatement | validation | public Statement wrapStatement(Statement statement) {
Timer.Context lifeTimerContext = getMetricHelper().startStatementLifeTimer();
return newProxy(new StatementProxyHandler(statement, this, lifeTimerContext));
} | java | {
"resource": ""
} |
q169326 | JdbcProxyFactory.wrapPreparedStatement | validation | public PreparedStatement wrapPreparedStatement(PreparedStatement preparedStatement, String sql) {
Query query = new Query(sql);
Timer.Context lifeTimerContext = getMetricHelper().startPreparedStatementLifeTimer(query);
return newProxy(new PreparedStatementProxyHandler(preparedStatement, this, query, lifeTimerContext));
} | java | {
"resource": ""
} |
q169327 | JdbcProxyFactory.wrapCallableStatement | validation | public CallableStatement wrapCallableStatement(CallableStatement callableStatement, String sql) {
Query query = new Query(sql);
Timer.Context lifeTimerContext = getMetricHelper().startCallableStatementLifeTimer(query);
return newProxy(new CallableStatementProxyHandler(callableStatement, this, query, lifeTimerContext));
} | java | {
"resource": ""
} |
q169328 | JdbcProxyFactory.getResultSetType | validation | private Class<? extends ResultSet> getResultSetType(ResultSet resultSet) {
Class<? extends ResultSet> resultSetType;
if (resultSet instanceof RowSet) {
if (resultSet instanceof CachedRowSet) {
if (resultSet instanceof WebRowSet) {
if (resultSet instanceof FilteredRowSet) {
resultSetType = FilteredRowSet.class;
} else if (resultSet instanceof JoinRowSet) {
resultSetType = JoinRowSet.class;
} else {
resultSetType = WebRowSet.class;
}
} else {
resultSetType = CachedRowSet.class;
}
} else if (resultSet instanceof JdbcRowSet) {
resultSetType = JdbcRowSet.class;
} else {
resultSetType = RowSet.class;
}
} else {
resultSetType = ResultSet.class;
}
return resultSetType;
} | java | {
"resource": ""
} |
q169329 | CowExecutor.buildArgs | validation | protected String[] buildArgs() {
String result[] = new String[0];
List<String> args = new ArrayList<String>();
if (lang != null && lang.length() > 0) {
args.add(flagify(CowsayCli.Opt.LANG.toString()));
args.add(lang);
}
if (html) {
args.add(flagify(CowsayCli.Opt.HTML.toString()));
}
if (alt != null && alt.length() > 0) {
args.add(flagify(CowsayCli.Opt.ALT.toString()));
args.add(alt);
}
if (wrap != null) {
args.add(flagify(CowsayCli.Opt.WRAP_AT.toString()));
args.add(wrap);
}
buildFaceArgs(args);
args.add(message);
return args.toArray(result);
} | java | {
"resource": ""
} |
q169330 | CowExecutor.buildFaceArgs | validation | private void buildFaceArgs(final List<String> args) {
if (mode != null && CowFace.isKnownMode(mode)) {
args.add(flagify(mode));
} else {
if (eyes != null) {
args.add(flagify(CowsayCli.Opt.EYES.toString()));
args.add(eyes);
}
if (tongue != null) {
args.add(flagify(CowsayCli.Opt.TONGUE.toString()));
args.add(tongue);
}
if (cowfile != null) {
args.add(flagify(CowsayCli.Opt.COWFILE.toString()));
args.add(cowfile);
}
}
} | java | {
"resource": ""
} |
q169331 | CowExecutor.execute | validation | public String execute() throws IllegalStateException {
validate();
String[] args = buildArgs();
String result;
if (think) {
result = Cowsay.think(args);
} else {
result = Cowsay.say(args);
}
return result;
} | java | {
"resource": ""
} |
q169332 | CowsayTask.execute | validation | @Override
public void execute() throws BuildException {
try {
String moo = executor.execute();
if (this.property != null && this.property.length() > 0) {
getProject().setProperty(this.property, moo);
} else {
System.out.println(moo);
}
} catch (IllegalStateException ex) {
throw new BuildException(ex.getMessage(), ex);
}
} | java | {
"resource": ""
} |
q169333 | I18n.setLanguage | validation | public static void setLanguage(final String language) {
currentLocale = new Locale(language);
messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
} | java | {
"resource": ""
} |
q169334 | I18n.getMessage | validation | protected static String getMessage(final String key) {
if (messages == null) {
setLanguage(DEFAULT_LANG);
}
return messages.getString(key);
} | java | {
"resource": ""
} |
q169335 | Cowsay.sayOrThink | validation | private static String sayOrThink(final String[] args, final boolean think) {
try {
boolean isThought = think;
String wordwrap = null;
CommandLine commandLine = CowsayCli.parseCmdArgs(args);
if (commandLine != null) {
if (commandLine.hasOption(CowsayCli.Opt.HELP.toString())) {
CowsayCli.showCmdLineHelp();
}
else if (commandLine.hasOption(CowsayCli.Opt.LIST_COWS.toString())) {
String[] files = Cowloader.listAllCowfiles();
if (files != null) {
return StringUtils.join(files, System.getProperty("line.separator"));
}
}
else {
String cowfileSpec = null;
CowFace cowFace = null;
if (commandLine.hasOption(CowsayCli.Opt.WRAP_AT.toString())) {
wordwrap = commandLine.getOptionValue(CowsayCli.Opt.WRAP_AT.toString());
}
else if (commandLine.hasOption(CowsayCli.Opt.NOWRAP.toString())) {
wordwrap = "0";
}
cowFace = getCowFaceByMode(commandLine);
if (cowFace == null) {
// if we are in here no modes were set
if (commandLine.hasOption(CowsayCli.Opt.COWFILE.toString())) {
cowfileSpec = commandLine.getOptionValue(CowsayCli.Opt.COWFILE.toString());
}
cowFace = getCowFace(commandLine);
}
if (commandLine.hasOption(CowsayCli.Opt.THINK.toString())) {
isThought = true;
}
if (cowfileSpec == null) {
cowfileSpec = Cowloader.DEFAULT_COW;
}
String cowTemplate = Cowloader.load(cowfileSpec);
if (cowTemplate != null) {
String moosages[] = commandLine.getArgs();
String moosage = StringUtils.join(moosages, " ");
if (moosage != null && moosage.length() > 0) {
Message message = new Message(moosage, isThought);
if (wordwrap != null) {
message.setWordwrap(wordwrap);
}
String cow = CowFormatter.formatCow(cowTemplate, cowFace, message);
cow = formatHtml(commandLine, cow, moosage, isThought);
return cow;
}
}
}
}
}
catch (CowParseException ex) {
Logger.getLogger(Cowsay.class.getName()).log(Level.SEVERE, null, ex);
}
return "";
} | java | {
"resource": ""
} |
q169336 | Cowsay.formatHtml | validation | private static String formatHtml(final CommandLine commandLine, final String plainCow, final String moosage,
final boolean isThought) {
String cow = plainCow;
if (commandLine.hasOption(CowsayCli.Opt.HTML.toString())) {
cow = StringEscapeUtils.escapeHtml4(cow);
cow = "<figure><pre>" + cow + "</pre><figcaption style=\"left:-999px; position:absolute\">";
String alt;
if (commandLine.hasOption(CowsayCli.Opt.ALT.toString())) {
alt = commandLine.getOptionValue(CowsayCli.Opt.ALT.toString());
}
else {
alt = isThought ? I18n.getMessage("altthink") : I18n.getMessage("altsay");
}
String escaped = StringEscapeUtils.escapeHtml4(moosage);
cow += String.format(alt, escaped);
cow += "</figcaption></figure>";
}
return cow;
} | java | {
"resource": ""
} |
q169337 | Cowsay.getCowFaceByMode | validation | private static CowFace getCowFaceByMode(final CommandLine commandLine) {
CowFace cowFace = null;
Set<String> modes = CowFace.COW_MODES.keySet();
for (String mode : modes) {
if (commandLine.hasOption(mode)) {
cowFace = CowFace.getByMode(mode);
break;
}
}
return cowFace;
} | java | {
"resource": ""
} |
q169338 | Cowsay.getCowFace | validation | private static CowFace getCowFace(final CommandLine commandLine) {
CowFace cowFace;
cowFace = new CowFace();
if (commandLine.hasOption(CowsayCli.Opt.EYES.toString())) {
cowFace.setEyes(commandLine.getOptionValue(CowsayCli.Opt.EYES.toString()));
}
if (commandLine.hasOption(CowsayCli.Opt.TONGUE.toString())) {
cowFace.setTongue(commandLine.getOptionValue(CowsayCli.Opt.TONGUE.toString()));
}
return cowFace;
} | java | {
"resource": ""
} |
q169339 | CowFormatter.extractCowTemplate | validation | private static String extractCowTemplate(final String cow) throws CowParseException {
Matcher matcher = COWSTART_RE.matcher(cow);
if (matcher.find(0)) {
String result = matcher.replaceFirst("");
return result;
} else {
throw new CowParseException("Could not parse cow " + cow);
}
} | java | {
"resource": ""
} |
q169340 | Cowloader.load | validation | public static String load(final String cowfileSpec) {
String effectiveCowfileSpec = (cowfileSpec != null) ? cowfileSpec.trim() : DEFAULT_COW;
if (effectiveCowfileSpec.length() > 0) {
if (!effectiveCowfileSpec.endsWith(COWFILE_EXT)) {
effectiveCowfileSpec += COWFILE_EXT;
}
InputStream cowInputStream;
if (effectiveCowfileSpec.indexOf(File.separatorChar) >= 0) {
cowInputStream = getCowFromPath(effectiveCowfileSpec);
} else {
cowInputStream = getCowFromCowPath(effectiveCowfileSpec);
}
if (cowInputStream == null) {
// Maybe there should be a verbose mode where we log this sort of error instead of silently failing?
cowInputStream = getCowFromResources(DEFAULT_COW + COWFILE_EXT);
}
if (cowInputStream != null) {
String cow = cowInputStreamToString(cowInputStream);
return cow;
}
}
return null; // should never happen
} | java | {
"resource": ""
} |
q169341 | Cowloader.cowInputStreamToString | validation | private static String cowInputStreamToString(final InputStream cowInputStream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(cowInputStream));
StringBuilder sb = new StringBuilder();
String line;
try {
String newLine = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append(newLine);
}
reader.close();
} catch (IOException ex) {
Logger.getLogger(Cowloader.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (cowInputStream != null) {
try {
cowInputStream.close();
} catch (IOException ex) {
Logger.getLogger(Cowloader.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return sb.toString();
} | java | {
"resource": ""
} |
q169342 | Cowloader.getCowFromPath | validation | private static InputStream getCowFromPath(final String path) {
String cwd = System.getProperty("user.dir"); // TODO is this really CWD?
if (cwd != null) {
File cowfile = new File(cwd, path);
if (isCowfile(cowfile)) {
return cowfileToCowInputStream(cowfile);
}
}
// maybe it's an absolute path?
File cowfile = new File(path);
if (isCowfile(cowfile)) {
return cowfileToCowInputStream(cowfile);
}
return null;
} | java | {
"resource": ""
} |
q169343 | Cowloader.getCowFromCowPath | validation | private static InputStream getCowFromCowPath(final String cowName) {
String cowPath = System.getenv("COWPATH");
if (cowPath != null) {
String[] paths = cowPath.split(File.pathSeparator);
if (paths != null) {
for (String path : paths) {
File cowfile = getCowfile(path, cowName);
if (cowfile != null) {
return cowfileToCowInputStream(cowfile);
}
}
}
}
return getCowFromResources(cowName);
} | java | {
"resource": ""
} |
q169344 | Cowloader.isCowfile | validation | private static boolean isCowfile(final File cowfile) {
if (cowfile != null && cowfile.exists()) {
return cowfile.getName().endsWith(COWFILE_EXT);
}
return false;
} | java | {
"resource": ""
} |
q169345 | Cowloader.cowfileToCowInputStream | validation | private static InputStream cowfileToCowInputStream(final File cowfile) {
InputStream cowInputStream = null;
try {
cowInputStream = new FileInputStream(cowfile);
} catch (FileNotFoundException ex) {
Logger.getLogger(Cowloader.class.getName()).log(Level.SEVERE, null, ex);
}
return cowInputStream;
} | java | {
"resource": ""
} |
q169346 | Cowloader.getCowfile | validation | private static File getCowfile(final String folder, final String cowName) {
File[] cowfiles = getCowFiles(folder);
for (File cowfile : cowfiles) {
if (cowfile.getName().equals(cowName)) {
return cowfile;
}
}
return null;
} | java | {
"resource": ""
} |
q169347 | Cowloader.getCowFiles | validation | private static File[] getCowFiles(final String folder) {
File dir = new File(folder);
File[] files;
files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(final File dir, final String name) {
return name.endsWith(".cow");
}
});
return files;
} | java | {
"resource": ""
} |
q169348 | CowFace.getByMode | validation | protected static CowFace getByMode(final String mode) {
if (mode != null) {
return COW_MODES.get(mode);
}
return null;
} | java | {
"resource": ""
} |
q169349 | CowFace.setEyes | validation | public final void setEyes(final String eyes) {
if (eyes != null && eyes.length() > 0) {
if (eyes.length() > 2) {
this.eyes = eyes.substring(0, 2);
} else {
this.eyes = eyes;
}
}
} | java | {
"resource": ""
} |
q169350 | CowFace.setTongue | validation | public final void setTongue(final String tongue) {
if (tongue != null && tongue.length() > 0) {
if (tongue.length() > 2) {
this.tongue = tongue.substring(0, 2);
} else {
this.tongue = tongue;
}
}
} | java | {
"resource": ""
} |
q169351 | CowFace.isKnownMode | validation | public static final boolean isKnownMode(final String mode) {
Set<String> modes = COW_MODES.keySet();
return modes.contains(mode);
} | java | {
"resource": ""
} |
q169352 | CowsayCli.parseCmdArgs | validation | public static CommandLine parseCmdArgs(final String[] argv) {
final CommandLineParser cmdLineParser = new DefaultParser();
try {
CommandLine parsed = cmdLineParser.parse(options, argv, true);
if (parsed.hasOption(Opt.LANG.text)) {
String language = parsed.getOptionValue(Opt.LANG.text);
if (language != null) {
I18n.setLanguage(language);
}
}
return parsed;
}
catch (MissingArgumentException ex) {
Option option = ex.getOption();
String flag = option.getOpt();
if (flag == null) {
flag = option.getLongOpt();
}
Logger.getLogger(CowsayCli.class.getName()).log(Level.INFO, I18n.getMessage("missingarg"), flag);
}
catch (ParseException ex) {
Logger.getLogger(CowsayCli.class.getName()).log(Level.FINEST, null, ex);
}
return null;
} | java | {
"resource": ""
} |
q169353 | CowsayCli.showCmdLineHelp | validation | public static void showCmdLineHelp() {
HelpFormatter formatter = new HelpFormatter();
updateOptionDescriptions();
formatter.printHelp(I18n.getMessage("usage"), options);
} | java | {
"resource": ""
} |
q169354 | Bubble.formatBubble | validation | private static String formatBubble(final BubbleWrap bubble, final String message, final int longestLine) {
String newLine = System.getProperty("line.separator");
String[] lines = message.split(newLine);
StringBuilder sb = new StringBuilder();
sb.append(bubble.buildTop(longestLine));
if (lines.length > 1) {
sb.append(bubble.formatMultiOpen(lines[0], longestLine));
for (int i = 1; i < (lines.length - 1); i++) {
sb.append(bubble.formatMultiMid(lines[i], longestLine));
}
sb.append(bubble.formatMultiEnd(lines[(lines.length - 1)], longestLine));
} else {
sb.append(bubble.formatSingle(lines[0]));
}
sb.append(bubble.buildBottom(longestLine));
return sb.toString();
} | java | {
"resource": ""
} |
q169355 | Message.wrapMessage | validation | private String wrapMessage(final String message) {
// Note that the original cowsay wraps lines mid-word.
// This version differs in that it wraps between words if possible.
int wrap = getWordwrap();
if (wrap <= 0) {
return message;
}
final List<String> result = new ArrayList<String>();
String newLine = System.getProperty("line.separator");
String[] lines = message.split(newLine);
for (String line : lines) {
result.add(WordUtils.wrap(line, wrap, null, true));
}
return StringUtils.join(result, newLine);
} | java | {
"resource": ""
} |
q169356 | Message.formatMessage | validation | private String formatMessage(final String message) {
String result;
if (message != null) {
result = wrapMessage(message);
int longestLine = getLongestLineLen(result);
if (!isThought) {
result = Bubble.formatSpeech(result, longestLine);
} else {
result = Bubble.formatThought(result, longestLine);
}
return result;
}
return "";
} | java | {
"resource": ""
} |
q169357 | Message.setWordwrap | validation | public void setWordwrap(final String wordwrap) {
try {
int ww = Integer.parseInt(wordwrap);
if (ww >= 0) {
this.wordwrap = ww;
}
} catch(Throwable ignore) {
// ignore
}
} | java | {
"resource": ""
} |
q169358 | Message.getLongestLineLen | validation | private static int getLongestLineLen(final String message) {
String newLine = System.getProperty("line.separator");
String[] lines = message.split(newLine);
int maxLen = 0;
for (String line : lines) {
maxLen = Math.max(maxLen, line.length());
}
return maxLen;
} | java | {
"resource": ""
} |
q169359 | LogglyClient.log | validation | public boolean log(String message) {
if (message == null) return false;
boolean ok;
try {
ok = loggly.log(token, tags, message).isExecuted();
} catch (Exception e) {
e.printStackTrace();
ok = false;
}
return ok;
} | java | {
"resource": ""
} |
q169360 | LogglyClient.log | validation | public void log(String message, final Callback callback) {
if (message == null) return;
loggly.log(token,
tags,
message,
new retrofit2.Callback<LogglyResponse>() {
@Override
public void onResponse(Call<LogglyResponse> call, Response<LogglyResponse> response) {
callback.success();
}
@Override
public void onFailure(Call<LogglyResponse> call, Throwable throwable) {
callback.failure(throwable.getMessage());
}
});
} | java | {
"resource": ""
} |
q169361 | LogglyClient.logBulk | validation | public void logBulk(Collection<String> messages, final Callback callback) {
if (messages == null) return;
String parcel = joinStrings(messages);
if (parcel.isEmpty()) return;
loggly.logBulk(token,
tags,
parcel,
new retrofit2.Callback<LogglyResponse>() {
@Override
public void onResponse(Call<LogglyResponse> call, Response<LogglyResponse> response) {
callback.success();
}
@Override
public void onFailure(Call<LogglyResponse> call, Throwable throwable) {
callback.failure(throwable.getMessage());
}
});
} | java | {
"resource": ""
} |
q169362 | LogglyClient.joinStrings | validation | private String joinStrings(Collection<String> messages) {
StringBuilder b = new StringBuilder();
for (String s : messages) {
if (s == null || s.isEmpty()) {
continue;
}
// Preserve new-lines in this event by replacing them
// with "\r". Otherwise, they're processed as event
// delimiters, resulting in unintentional multiple events.
b.append(s.replaceAll("[\r\n]", "\r")).append('\n');
}
return b.toString();
} | java | {
"resource": ""
} |
q169363 | LogglyClientDemo.main | validation | public static void main(String... args) {
if (args.length == 0 || args[0].trim().isEmpty()) {
System.err.println("missing argument: loggly token\nsee http://loggly.com/docs/customer-token-authentication-token/");
System.exit(1);
}
final String TOKEN = args[0];
final ILogglyClient loggly = new LogglyClient(TOKEN);
System.out.println("posting single event to Loggly asynchronously...");
loggly.log("Hello!\nThis is a\nmulti-line event!\n",
new LogglyClient.Callback() {
public void success() {
System.out.println("callback succeeded");
}
public void failure(String error) {
System.err.println("callback failed: " + error);
}
});
System.out.println("posting bulk events to Loggly asynchronously...");
loggly.logBulk(Arrays.asList("E1", "E2"),
new LogglyClient.Callback() {
public void success() {
System.out.println("bulk callback succeeded");
}
public void failure(String error) {
System.err.println("bulk callback failed: " + error);
}
});
System.out.println("posting single event to Loggly...");
boolean ok = loggly.log("Hello!\nThis is a\nmulti-line event!\n");
System.out.println(ok ? "ok" : "err");
System.out.println("posting single JSON event to Loggly...");
final String json = "{ \"timestamp\": \"2015-01-01T12:34:00Z\", \"message\": \"Event 100\", \"count\": 100 }";
ok = loggly.log(json);
System.out.println(ok ? "ok" : "err");
System.out.println("posting bulk events to Loggly...");
ok = loggly.logBulk("This is a\nmulti-line event 1", "Event 2", "Event 3");
System.out.println(ok ? "ok" : "err");
System.out.println("setting log tags to 'foo', 'bar', and 'baz'...");
loggly.setTags("foo", "bar,baz");
ok = loggly.log("This should be tagged with 'foo', 'bar', and 'baz'");
System.out.println(ok ? "ok" : "err");
} | java | {
"resource": ""
} |
q169364 | Catalog.getSchemas | validation | public SortedMap<String,Schema> getSchemas() throws SQLException {
synchronized(getSchemasLock) {
if(getSchemasCache==null) {
SortedMap<String,Schema> newSchemas = new TreeMap<>(DatabaseMetaData.getCollator());
try (ResultSet results = metaData.getMetaData().getSchemas()) {
ResultSetMetaData resultsMeta = results.getMetaData();
while(results.next()) {
int colCount = resultsMeta.getColumnCount();
//System.err.println("DEBUG: Catalog: getSchemas(): colCount=" + colCount);
//for(int i=1; i<=colCount; i++) {
// resultsMeta.getColumnName(i);
// System.err.println("DEBUG: Catalog: getSchemas(): resultsMeta.getColumnName("+i+")=" + resultsMeta.getColumnName(i));
//}
//System.err.println("DEBUG: Catalog: getSchemas(): results.getString(\"table_catalog\")=" + results.getString("table_catalog"));
//System.err.println("DEBUG: Catalog: getSchemas(): results.getString(\"TABLE_CATALOG\")=" + results.getString("TABLE_CATALOG"));
if(
colCount==1 // PostgreSQL 8.3 only returns one column
|| results.getString("TABLE_CATALOG") == null // PostgreSQL 9.4 driver returns null
|| name.equals(results.getString("TABLE_CATALOG")) // Other driver
) {
Schema newSchema = new Schema(this, results.getString("TABLE_SCHEM"));
if(newSchemas.put(newSchema.getName(), newSchema)!=null) throw new AssertionError("Duplicate schema: "+newSchema);
}
}
}
getSchemasCache = AoCollections.optimalUnmodifiableSortedMap(newSchemas);
}
return getSchemasCache;
}
} | java | {
"resource": ""
} |
q169365 | Catalog.getSchema | validation | public Schema getSchema(String name) throws NoRowException, SQLException {
Schema schema = getSchemas().get(name);
if(schema==null) throw new NoRowException("name=" + name);
return schema;
} | java | {
"resource": ""
} |
q169366 | AutoGitContextListener.contextInitialized | validation | @Override
public void contextInitialized(ServletContextEvent sce) {
try {
ServletContext sc;
synchronized(servletContextLock) {
servletContext = sce.getServletContext();
sc = servletContext;
}
// Find the top level directory
String gitToplevelPath = sc.getInitParameter(GIT_TOPLEVEL_CONTEXT_PARAM);
File gitToplevelRaw;
if(gitToplevelPath == null || gitToplevelPath.isEmpty()) {
// Default to web root
String rootRealPath = sc.getRealPath("/");
if(rootRealPath == null) throw new IllegalStateException("Unable to find web root and " + GIT_TOPLEVEL_CONTEXT_PARAM + " context parameter not provided");
gitToplevelRaw = new File(rootRealPath);
} else {
if(gitToplevelPath.startsWith("~/")) {
gitToplevelRaw = new File(System.getProperty("user.home"), gitToplevelPath.substring(2));
} else {
gitToplevelRaw = new File(gitToplevelPath);
}
}
if(DEBUG) sc.log("gitToplevelRaw: " + gitToplevelRaw);
Path gtl;
synchronized(gitToplevelLock) {
gitToplevel = gitToplevelRaw.getCanonicalFile().toPath();
gtl = gitToplevel;
}
if(DEBUG) sc.log("gitToplevel: " + gtl);
// Make sure root exists and is readable
if(!Files.isDirectory(gtl, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Git toplevel is not a directory: " + gtl);
if(!Files.isReadable(gtl)) throw new IOException("Unable to read Git toplevel directory: " + gtl);
// Recursively watch for any changes in the directory
if(DEBUG) sc.log("Starting watcher");
WatchService w;
synchronized(watcherLock) {
watcher = gtl.getFileSystem().newWatchService();
w = watcher;
}
resync();
if(DEBUG) sc.log("Starting watchThread");
synchronized(watcherThreadLock) {
watcherThread = new Thread(watcherRunnable);
watcherThread.start();
}
if(DEBUG) sc.log("Starting changeThread");
synchronized(changedThreadLock) {
changedThread = new Thread(changedRunnable);
changedThread.start();
}
sc.setAttribute(APPLICATION_SCOPE_KEY, this);
} catch(IOException e) {
throw new WrappedException(e);
}
} | java | {
"resource": ""
} |
q169367 | AutoGitContextListener.resync | validation | private void resync() throws IOException {
Path gtl;
synchronized(gitToplevelLock) {
gtl = gitToplevel;
}
WatchService w;
synchronized(watcherLock) {
w = watcher;
}
if(gtl != null && w != null) {
synchronized(registered) {
Set<Path> extraKeys = new HashSet<>(registered.keySet());
resync(w, gtl, extraKeys);
for(Path extraKey : extraKeys) {
if(DEBUG) log("Canceling watch key: " + extraKey);
registered.remove(extraKey).cancel();
}
}
}
} | java | {
"resource": ""
} |
q169368 | Schema.getTables | validation | public SortedMap<String,Table> getTables() throws SQLException {
synchronized(getTablesLock) {
if(getTablesCache==null) {
SortedMap<String,Table> newTables = new TreeMap<>(DatabaseMetaData.getCollator());
try (ResultSet results = catalog.getMetaData().getMetaData().getTables(catalog.getName(), name, null, null)) {
while(results.next()) {
Table newTable = new Table(this, results.getString("TABLE_NAME"), results.getString("TABLE_TYPE"));
if(newTables.put(newTable.getName(), newTable)!=null) throw new AssertionError("Duplicate table: "+newTable);
}
}
getTablesCache = AoCollections.optimalUnmodifiableSortedMap(newTables);
}
return getTablesCache;
}
} | java | {
"resource": ""
} |
q169369 | Schema.getTable | validation | public Table getTable(String name) throws NoRowException, SQLException {
Table table = getTables().get(name);
if(table==null) throw new NoRowException();
return table;
} | java | {
"resource": ""
} |
q169370 | TempFileResult.writeToImpl | validation | private void writeToImpl(Writer out, long writeStart, long writeEnd) throws IOException {
try ( // TODO: If copying to another SegmentedBufferedWriter or AutoTempFileWriter, we have a chance here for disk-to-disk block level copying instead of going through all the conversions.
RandomAccessFile raf = new RandomAccessFile(tempFile.getFile(), "r")) {
byte[] bytes = BufferManager.getBytes();
try {
char[] chars = BufferManager.getChars();
try {
long index = writeStart;
raf.seek(index<<1);
while(index<writeEnd) {
// Read a block
long blockSizeLong = (writeEnd - index)<<1;
int blockSize = blockSizeLong > BufferManager.BUFFER_SIZE ? BufferManager.BUFFER_SIZE : (int)blockSizeLong;
assert (blockSize&1) == 0 : "Must be an even number for UTF-16 conversion";
raf.readFully(bytes, 0, blockSize);
// Convert to characters
for(
int bpos=0, cpos=0;
bpos<blockSize;
bpos+=2, cpos++
) {
chars[cpos] = IoUtils.bufferToChar(bytes, bpos);
}
// Write to output
out.write(chars, 0, blockSize>>1);
// Update location
index += blockSize>>1;
}
} finally {
BufferManager.release(chars, false);
}
} finally {
BufferManager.release(bytes, false);
}
}
} | java | {
"resource": ""
} |
q169371 | DatabaseMetaData.getCatalogs | validation | public SortedMap<String,Catalog> getCatalogs() throws SQLException {
synchronized(getCatalogsLock) {
if(getCatalogsCache==null) {
SortedMap<String,Catalog> newCatalogs = new TreeMap<>(englishCollator);
try (ResultSet results = metaData.getCatalogs()) {
while(results.next()) {
Catalog newCatalog = new Catalog(this, results.getString(1));
if(newCatalogs.put(newCatalog.getName(), newCatalog)!=null) throw new AssertionError("Duplicate catalog: "+newCatalog);
}
}
getCatalogsCache = AoCollections.optimalUnmodifiableSortedMap(newCatalogs);
}
return getCatalogsCache;
}
} | java | {
"resource": ""
} |
q169372 | DatabaseMetaData.getCatalog | validation | public Catalog getCatalog(String name) throws NoRowException, SQLException {
Catalog catalog = getCatalogs().get(name);
if(catalog==null) throw new NoRowException();
return catalog;
} | java | {
"resource": ""
} |
q169373 | CharArrayBufferWriter.getBuffer | validation | private char[] getBuffer(int additional) throws IOException {
long newLen = (long)length + additional;
if(newLen > MAX_LENGTH) throw new IOException("Maximum buffer length is " + MAX_LENGTH + ", " + newLen + " requested");
char[] buf = this.buffer;
int bufLen = buf.length;
if(newLen > bufLen) {
// Find the next power of two that will hold all of the contents
int newBufLen = bufLen==0 ? BufferManager.BUFFER_SIZE : (bufLen << 1);
while(newBufLen < newLen) {
newBufLen <<= 1;
}
char[] newBuf =
(newBufLen == BufferManager.BUFFER_SIZE)
? BufferManager.getChars()
: new char[newBufLen];
System.arraycopy(buf, 0, newBuf, 0, length);
// Recycle buffer
if(bufLen == BufferManager.BUFFER_SIZE) {
BufferManager.release(buf, false);
}
buf = newBuf;
this.buffer = buf;
}
return buf;
} | java | {
"resource": ""
} |
q169374 | LoggingResult.log | validation | private void log(Encoder encoder) throws IOException {
if(encoder==null) log.write("null");
else {
String className = encoder.getClass().getName();
// Some shortcuts from the ao-encoding project, classnames used here to avoid hard dependency
if("com.aoindustries.encoding.JavaScriptInXhtmlAttributeEncoder".equals(className)) {
log.write("javaScriptInXhtmlAttributeEncoder");
} else if("com.aoindustries.encoding.JavaScriptInXhtmlEncoder".equals(className)) {
log.write("javaScriptInXhtmlEncoder");
} else if("com.aoindustries.encoding.TextInXhtmlAttributeEncoder".equals(className)) {
log.write("textInXhtmlAttributeEncoder");
} else {
log.write(className);
}
}
} | java | {
"resource": ""
} |
q169375 | LoggingResult.log | validation | private void log(Writer writer) throws IOException {
if(writer==null) {
log.write("null");
} else if(writer instanceof LoggingWriter) {
LoggingWriter loggingWriter = (LoggingWriter)writer;
log.write("writer[");
log.write(Long.toString(loggingWriter.getId()));
log.write(']');
} else if(writer instanceof EncoderWriter) {
EncoderWriter encoderWriter = (EncoderWriter)writer;
log.write("new EncoderWriter(");
log(encoderWriter.getEncoder());
log.write(", ");
log(encoderWriter.getOut());
log.write(')');
} else {
String classname = writer.getClass().getName();
if(classname.equals("org.apache.jasper.runtime.BodyContentImpl")) log.write("bodyContent");
else if(classname.equals("org.apache.jasper.runtime.JspWriterImpl")) log.write("jspWriter");
else log.write(classname);
}
} | java | {
"resource": ""
} |
q169376 | LexicalPositions.zeroWithFile | validation | public static <F> LexicalPosition<F> zeroWithFile(
final F file)
{
return LexicalPosition.of(0, 0, Optional.of(file));
} | java | {
"resource": ""
} |
q169377 | SegmentedResult.append | validation | private void append(int segmentIndex, int off, int len, StringBuilder buffer) {
switch(segmentTypes[segmentIndex]) {
case SegmentedWriter.TYPE_STRING :
buffer.append(
(String)segmentValues[segmentIndex],
off,
off + len
);
break;
case SegmentedWriter.TYPE_CHAR_NEWLINE :
assert off==0;
assert len==1;
buffer.append('\n');
break;
case SegmentedWriter.TYPE_CHAR_QUOTE :
assert off==0;
assert len==1;
buffer.append('"');
break;
case SegmentedWriter.TYPE_CHAR_APOS :
assert off==0;
assert len==1;
buffer.append('\'');
break;
case SegmentedWriter.TYPE_CHAR_OTHER :
assert off==0;
assert len==1;
buffer.append(((Character)segmentValues[segmentIndex]).charValue());
break;
default :
throw new AssertionError();
}
} | java | {
"resource": ""
} |
q169378 | SegmentedResult.writeSegment | validation | private void writeSegment(int segmentIndex, int off, int len, Encoder encoder, Writer out) throws IOException {
switch(segmentTypes[segmentIndex]) {
case SegmentedWriter.TYPE_STRING :
encoder.write(
(String)segmentValues[segmentIndex],
off,
len,
out
);
break;
case SegmentedWriter.TYPE_CHAR_NEWLINE :
assert off==0;
assert len==1;
encoder.write('\n', out);
break;
case SegmentedWriter.TYPE_CHAR_QUOTE :
assert off==0;
assert len==1;
encoder.write('"', out);
break;
case SegmentedWriter.TYPE_CHAR_APOS :
assert off==0;
assert len==1;
encoder.write('\'', out);
break;
case SegmentedWriter.TYPE_CHAR_OTHER :
assert off==0;
assert len==1;
encoder.write((Character)segmentValues[segmentIndex], out);
break;
default :
throw new AssertionError();
}
} | java | {
"resource": ""
} |
q169379 | SegmentedResult.charAt | validation | private static char charAt(byte type, Object value, int charIndex) {
switch(type) {
case SegmentedWriter.TYPE_STRING :
return ((String)value).charAt(charIndex);
case SegmentedWriter.TYPE_CHAR_NEWLINE :
assert charIndex==0;
return '\n';
case SegmentedWriter.TYPE_CHAR_QUOTE :
assert charIndex==0;
return '"';
case SegmentedWriter.TYPE_CHAR_APOS :
assert charIndex==0;
return '\'';
case SegmentedWriter.TYPE_CHAR_OTHER :
assert charIndex==0;
return (Character)value;
default :
throw new AssertionError();
}
} | java | {
"resource": ""
} |
q169380 | Database.getSqlDataTypes | validation | private Map<String,Class<?>> getSqlDataTypes() throws SQLException {
if(sqlDataTypes == null) {
// Load custom types from ServiceLoader
Map<String,Class<?>> newMap = new LinkedHashMap<>();
Iterator<SQLData> iter = ServiceLoader.load(SQLData.class).iterator();
while(iter.hasNext()) {
SQLData sqlData = iter.next();
newMap.put(sqlData.getSQLTypeName(), sqlData.getClass());
}
sqlDataTypes = newMap;
}
return sqlDataTypes;
} | java | {
"resource": ""
} |
q169381 | Table.getColumnMap | validation | public SortedMap<String,Column> getColumnMap() throws SQLException {
synchronized(getColumnMapLock) {
if(getColumnMapCache==null) {
SortedMap<String,Column> newColumnMap = new TreeMap<>(DatabaseMetaData.getCollator());
try (ResultSet results = schema.getCatalog().getMetaData().getMetaData().getColumns(schema.getCatalog().getName(), schema.getName(), name, null)) {
while(results.next()) {
Column newColumn = new Column(
this,
results.getString("COLUMN_NAME"),
results.getInt("DATA_TYPE"),
results.getString("TYPE_NAME"),
getInteger(results, "COLUMN_SIZE"),
getInteger(results, "DECIMAL_DIGITS"),
results.getInt("NULLABLE"),
results.getString("COLUMN_DEF"),
getInteger(results, "CHAR_OCTET_LENGTH"),
results.getInt("ORDINAL_POSITION"),
results.getString("IS_NULLABLE"),
results.getString("IS_AUTOINCREMENT")
);
if(newColumnMap.put(newColumn.getName(), newColumn)!=null) throw new AssertionError("Duplicate column: "+newColumn);
}
}
getColumnMapCache = AoCollections.optimalUnmodifiableSortedMap(newColumnMap);
}
return getColumnMapCache;
}
} | java | {
"resource": ""
} |
q169382 | Table.getColumn | validation | public Column getColumn(String name) throws NoRowException, SQLException {
Column column = getColumnMap().get(name);
if(column==null) throw new NoRowException();
return column;
} | java | {
"resource": ""
} |
q169383 | Table.getColumns | validation | public List<Column> getColumns() throws SQLException {
synchronized(getColumnsLock) {
if(getColumnsCache==null) {
SortedMap<String,Column> columnMap = getColumnMap();
List<Column> newColumns = new ArrayList<>(columnMap.size());
for(int i=0; i<columnMap.size(); i++) newColumns.add(null);
for(Column column : columnMap.values()) {
int ordinalPosition = column.getOrdinalPosition();
if(newColumns.set(ordinalPosition-1, column)!=null) throw new SQLException("Duplicate ordinal position: "+ordinalPosition);
}
for(int i=0; i<newColumns.size(); i++) {
if(newColumns.get(i)==null) throw new SQLException("Missing ordinal position: "+(i+1));
}
getColumnsCache = AoCollections.optimalUnmodifiableList(newColumns);
}
return getColumnsCache;
}
} | java | {
"resource": ""
} |
q169384 | Table.getColumn | validation | public Column getColumn(int ordinalPosition) throws NoRowException, SQLException {
try {
return getColumns().get(ordinalPosition-1);
} catch(IndexOutOfBoundsException exc) {
throw new NoRowException(exc);
}
} | java | {
"resource": ""
} |
q169385 | Table.getImportedTables | validation | public Set<? extends Table> getImportedTables() throws SQLException {
synchronized(getImportedTablesLock) {
if(getImportedTablesCache==null) {
Set<Table> newImportedTables = new LinkedHashSet<>();
Catalog catalog = schema.getCatalog();
DatabaseMetaData metaData = catalog.getMetaData();
try (ResultSet results = schema.getCatalog().getMetaData().getMetaData().getImportedKeys(schema.getCatalog().getName(), schema.getName(), name)) {
while(results.next()) {
String pkCat = results.getString("PKTABLE_CAT");
Catalog pkCatalog = pkCat==null ? catalog : metaData.getCatalog(pkCat);
newImportedTables.add(
pkCatalog
.getSchema(results.getString("PKTABLE_SCHEM"))
.getTable(results.getString("PKTABLE_NAME"))
);
}
}
getImportedTablesCache = AoCollections.optimalUnmodifiableSet(newImportedTables);
}
return getImportedTablesCache;
}
} | java | {
"resource": ""
} |
q169386 | Table.getExportedTables | validation | public Set<? extends Table> getExportedTables() throws SQLException {
synchronized(getExportedTablesLock) {
if(getExportedTablesCache==null) {
Set<Table> newExportedTables = new LinkedHashSet<>();
Catalog catalog = schema.getCatalog();
DatabaseMetaData metaData = catalog.getMetaData();
try (ResultSet results = schema.getCatalog().getMetaData().getMetaData().getExportedKeys(schema.getCatalog().getName(), schema.getName(), name)) {
while(results.next()) {
String fkCat = results.getString("FKTABLE_CAT");
Catalog fkCatalog = fkCat==null ? catalog : metaData.getCatalog(fkCat);
newExportedTables.add(
fkCatalog
.getSchema(results.getString("FKTABLE_SCHEM"))
.getTable(results.getString("FKTABLE_NAME"))
);
}
}
getExportedTablesCache = AoCollections.optimalUnmodifiableSet(newExportedTables);
}
return getExportedTablesCache;
}
} | java | {
"resource": ""
} |
q169387 | SegmentedWriter.addSegment | validation | private void addSegment(byte type, Object value, int off, int len) {
assert !isClosed;
assert len>0 : "Empty segments should never be added";
final int arraylen = segmentValues.length;
if(segmentCount==arraylen) {
// Need to grow
if(arraylen==0) {
this.segmentTypes = new byte[START_LEN];
this.segmentValues = new Object[START_LEN];
this.segmentOffsets = new int[START_LEN];
this.segmentLengths = new int[START_LEN];
} else {
// Double capacity and copy
int newLen = arraylen<<1;
byte[] newTypes = new byte[newLen];
System.arraycopy(segmentTypes, 0, newTypes, 0, arraylen);
this.segmentTypes = newTypes;
Object[] newValues = new Object[newLen];
System.arraycopy(segmentValues, 0, newValues, 0, arraylen);
this.segmentValues = newValues;
int[] newOffsets = new int[newLen];
System.arraycopy(segmentOffsets, 0, newOffsets, 0, arraylen);
this.segmentOffsets = newOffsets;
int[] newLengths = new int[newLen];
System.arraycopy(segmentLengths, 0, newLengths, 0, arraylen);
this.segmentLengths = newLengths;
}
}
segmentTypes[segmentCount] = type;
segmentValues[segmentCount] = value;
segmentOffsets[segmentCount] = off;
segmentLengths[segmentCount++] = len;
} | java | {
"resource": ""
} |
q169388 | LoggingWriter.log | validation | private void log(char ch) throws IOException {
if(ch=='\t') log.write("'\\t'");
else if(ch=='\b') log.write("'\\b'");
else if(ch=='\n') log.write("'\\n'");
else if(ch=='\r') log.write("'\\r'");
else if(ch=='\f') log.write("'\\f'");
else if(ch=='\'') log.write("'\\'");
else if(ch=='\\') log.write("'\\\\'");
else if(ch=='"') log.write("'\\\"'");
else if(ch<' ') {
log.write("'\\u");
String hex = Integer.toHexString(ch);
for(int l=hex.length(); l<4; l++) log.write('0');
log.write(hex);
log.write('\'');
} else {
log.write('\'');
log.write(ch);
log.write('\'');
}
} | java | {
"resource": ""
} |
q169389 | LoggingWriter.log | validation | private void log(String value) throws IOException {
if(value==null) {
log.write("(String)null");
} else {
log.write('"');
for(int i=0, len=value.length(); i<len; i++) {
char ch = value.charAt(i);
if(ch=='\t') log.write("\\t");
else if(ch=='\b') log.write("\\b");
else if(ch=='\n') log.write("\\n");
else if(ch=='\r') log.write("\\r");
else if(ch=='\f') log.write("\\f");
else if(ch=='\\') log.write("\\\\");
else if(ch=='"') log.write("\\\"");
else if(ch<' ') {
log.write("\\u");
String hex = Integer.toHexString(ch);
for(int l=hex.length(); l<4; l++) log.write('0');
log.write(hex);
} else {
log.write(ch);
}
}
log.write('"');
}
} | java | {
"resource": ""
} |
q169390 | Values.putAll | validation | public static ContentValues putAll(ContentValues target, Object... values) {
int length = values.length;
checkArgument(length % 2 == 0, "values length must be a multiple of two");
for (int i = 0; i < length; i += 2) {
String key = (String) values[i];
Object val = values[i + 1];
if (val == null) {
target.putNull(key);
} else if (val instanceof String) {
target.put(key, (String) val);
} else if (val instanceof Long) {
target.put(key, (Long) val);
} else if (val instanceof Integer) {
target.put(key, (Integer) val);
} else if (val instanceof Boolean) {
target.put(key, (Boolean) val);
} else if (val instanceof Double) {
target.put(key, (Double) val);
} else if (val instanceof Float) {
target.put(key, (Float) val);
} else if (val instanceof byte[]) {
target.put(key, (byte[]) val);
} else if (val instanceof Byte) {
target.put(key, (Byte) val);
} else if (val instanceof Short) {
target.put(key, (Short) val);
} else {
throw new IllegalArgumentException(
"ContentValues does not support values of type " + val.getClass().getName()
+ " (provided for key '" + key + "')");
}
} | java | {
"resource": ""
} |
q169391 | GoogleMaps.moveCameraToLastLocation | validation | public void moveCameraToLastLocation(GoogleMap map, float zoom) {
mProvider.getLastLocation().subscribe(location -> map.moveCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), zoom)));
} | java | {
"resource": ""
} |
q169392 | GoogleMaps.animateCameraToIncludePosition | validation | public void animateCameraToIncludePosition(GoogleMap map, LatLng position, long delay) {
if (!map.getProjection().getVisibleRegion().latLngBounds.contains(position)) {
if (delay > 0) {
new Handler(Looper.getMainLooper())
.postDelayed(() -> doAnimateCameraToIncludePosition(map, position), delay);
} else {
doAnimateCameraToIncludePosition(map, position);
}
}
} | java | {
"resource": ""
} |
q169393 | Reveals.circleToRect | validation | public static Animator circleToRect(View circle, View rect) {
return circleRect(circle, rect, true);
} | java | {
"resource": ""
} |
q169394 | Reveals.circleFromRect | validation | public static Animator circleFromRect(View circle, View rect) {
return circleRect(circle, rect, false);
} | java | {
"resource": ""
} |
q169395 | Transitions.arcMotion | validation | public static Transition arcMotion(Context context) {
if (sArc == null) {
sArc = TransitionInflater.from(context).inflateTransition(
R.transition.sprockets_arc_motion);
}
return sArc;
} | java | {
"resource": ""
} |
q169396 | Spans.bold | validation | public static StyleSpan bold(int i) {
if (sBolds == null) {
sBolds = new ArrayList<>();
sBolds.add(bold());
}
if (i < sBolds.size()) {
return sBolds.get(i);
} else {
StyleSpan bold = new StyleSpan(Typeface.BOLD);
sBolds.add(bold);
return bold;
}
} | java | {
"resource": ""
} |
q169397 | Animators.scaleIn | validation | public static ViewPropertyAnimator scaleIn(View view) {
return scale(view, 1.0f, enterScreen(), R.integer.anim_duration_enter);
} | java | {
"resource": ""
} |
q169398 | Animators.scaleOut | validation | public static ViewPropertyAnimator scaleOut(View view) {
return scale(view, 0.0f, exitScreen(), R.integer.anim_duration_exit);
} | java | {
"resource": ""
} |
q169399 | Animators.scaleShowNext | validation | public static ViewPropertyAnimator scaleShowNext(ViewSwitcher view, Runnable endAction) {
return scale(view, view::showNext, endAction);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.