_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q13800 | StripInvalidXmlCharactersFilter.filter | train | private static String filter(String s) {
int len = s.length();
StringBuilder filtered = new StringBuilder(len);
int pos = 0;
while(pos < len) {
char ch1 = s.charAt(pos++);
if(Character.isHighSurrogate(ch1)) {
// Handle surrogates
if(pos < len) {
char ch2 = s.charAt(pos++);
if(Character.isLowSurrogate(ch2)) {
if(isValidCharacter(Character.toCodePoint(ch1, ch2))) {
filtered.append(ch1).append(ch2);
}
} else {
// High surrogate not followed by low surrogate, invalid
}
} else {
// High surrogate at end of string, invalid
}
} else {
// Not surrogates
if(isValidCharacter(ch1)) {
filtered.append(ch1);
}
}
}
assert filtered.length() <= len;
return filtered.length() != len ? filtered.toString() : s;
} | java | {
"resource": ""
} |
q13801 | AutoEncodingFilteredTag.doTag | train | protected void doTag(Writer out) throws JspException, IOException {
JspFragment body = getJspBody();
if(body!=null) {
// Check for JspWriter to avoid a JspWriter wrapping a JspWriter
body.invoke(
(out instanceof JspWriter)
? null
: out
);
}
} | java | {
"resource": ""
} |
q13802 | QuestionRelationExtractor.extractPolar | train | private static BinRelation extractPolar(DTree tree) {
// TODO: HERE.
DNode rootVerb = tree.getRoots().get(0);
// rootVerb.getChildren().
BinRelation binRelation = new BinRelation();
return binRelation;
} | java | {
"resource": ""
} |
q13803 | StringEventStream.createEvent | train | private Event createEvent(String obs) {
int lastSpace = obs.lastIndexOf(StringUtils.SPACE);
Event event = null;
if (lastSpace != -1) {
String label = obs.substring(lastSpace + 1);
String[] contexts = obs.substring(0, lastSpace).split("\\s+");
// Split name and value
float[] values = RealValueFileEventStream.parseContexts(contexts);
// Label, feature name, feature value
event = new Event(label, contexts, values);
}
return event;
} | java | {
"resource": ""
} |
q13804 | StanfordParser.stanfordTokenize | train | public static List<CoreLabel> stanfordTokenize(String str) {
TokenizerFactory<? extends HasWord> tf = PTBTokenizer.coreLabelFactory();
// ptb3Escaping=false -> '(' not converted as '-LRB-', Dont use it, it will cause Dependency resolution err.
Tokenizer<? extends HasWord> originalWordTokenizer = tf.getTokenizer(new StringReader(str), "ptb3Escaping=false");
Tokenizer<? extends HasWord> tokenizer = tf.getTokenizer(new StringReader(str));
List<? extends HasWord> originalTokens = originalWordTokenizer.tokenize();
List<? extends HasWord> tokens = tokenizer.tokenize();
// Curse you Stanford!
List<CoreLabel> coreLabels = new ArrayList<>(tokens.size());
for (int i = 0; i < tokens.size(); i++) {
CoreLabel coreLabel = new CoreLabel();
coreLabel.setWord(tokens.get(i).word());
coreLabel.setOriginalText(originalTokens.get(i).word());
coreLabel.setValue(tokens.get(i).word());
coreLabel.setBeginPosition(((CoreLabel) tokens.get(i)).beginPosition());
coreLabel.setEndPosition(((CoreLabel) tokens.get(i)).endPosition());
coreLabels.add(coreLabel);
}
return coreLabels;
} | java | {
"resource": ""
} |
q13805 | StanfordParser.tagPOS | train | public void tagPOS(List<CoreLabel> tokens) {
if (posTagger == null) {
if (POS_TAGGER_MODEL_PATH == null) {
LOG.warn("Default POS Tagger model");
POS_TAGGER_MODEL_PATH = StanfordConst.STANFORD_DEFAULT_POS_EN_MODEL;
}
posTagger = new MaxentTagger(POS_TAGGER_MODEL_PATH);
}
List<TaggedWord> posList = posTagger.tagSentence(tokens);
for (int i = 0; i < tokens.size(); i++) {
String pos = posList.get(i).tag();
tokens.get(i).setTag(pos);
}
} | java | {
"resource": ""
} |
q13806 | StanfordParser.tagLemma | train | public static void tagLemma(List<CoreLabel> tokens) {
// Not sure if this can be static.
Morphology morpha = new Morphology();
for (CoreLabel token : tokens) {
String lemma;
String pos = token.tag();
if (pos.equals(LangLib.POS_NNPS)) {
pos = LangLib.POS_NNS;
}
if (pos.length() > 0) {
String phrasalVerb = phrasalVerb(morpha, token.word(), pos);
if (phrasalVerb == null) {
lemma = morpha.lemma(token.word(), pos);
} else {
lemma = phrasalVerb;
}
} else {
lemma = morpha.stem(token.word());
}
// LGLibEn.convertUnI only accept cap I.
if (lemma.equals("i")) {
lemma = "I";
}
token.setLemma(lemma);
}
} | java | {
"resource": ""
} |
q13807 | StanfordParser.tagNamedEntity | train | public synchronized void tagNamedEntity(List<CoreLabel> tokens) {
boolean isPOSTagged = tokens.parallelStream().filter(x -> x.tag() == null).count() == 0;
if (!isPOSTagged) {
throw new RuntimeException("Please Run POS Tagger before Named Entity tagger.");
}
if (ners != null) {
try {
ners.stream().forEach(ner -> ner.classify(tokens));
} catch (Exception e) {
/* edu.stanford.nlp.util.RuntimeInterruptedException: java.lang.InterruptedException
at edu.stanford.nlp.util.HashIndex.addToIndex(HashIndex.java:173) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ling.tokensregex.SequenceMatcher$BranchStates.newBid(SequenceMatcher.java:902) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ling.tokensregex.SequenceMatcher$MatchedStates.<init>(SequenceMatcher.java:1288) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.getStartStates(SequenceMatcher.java:709) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findMatchStartBacktracking(SequenceMatcher.java:488) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findMatchStart(SequenceMatcher.java:449) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.find(SequenceMatcher.java:341) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.findNextNonOverlapping(SequenceMatcher.java:365) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ling.tokensregex.SequenceMatcher.find(SequenceMatcher.java:437) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ie.NumberNormalizer.findNumbers(NumberNormalizer.java:452) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ie.NumberNormalizer.findAndMergeNumbers(NumberNormalizer.java:721) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressions(TimeExpressionExtractorImpl.java:184) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressions(TimeExpressionExtractorImpl.java:178) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressionCoreMaps(TimeExpressionExtractorImpl.java:116) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.time.TimeExpressionExtractorImpl.extractTimeExpressionCoreMaps(TimeExpressionExtractorImpl.java:104) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.runSUTime(NumberSequenceClassifier.java:340) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.classifyWithSUTime(NumberSequenceClassifier.java:138) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ie.regexp.NumberSequenceClassifier.classifyWithGlobalInformation(NumberSequenceClassifier.java:101) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ie.NERClassifierCombiner.recognizeNumberSequences(NERClassifierCombiner.java:267) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ie.NERClassifierCombiner.classifyWithGlobalInformation(NERClassifierCombiner.java:231) ~[stanford-corenlp-3.5.2.jar:3.5.2]
at edu.stanford.nlp.ie.NERClassifierCombiner.classify(NERClassifierCombiner.java:218) ~[stanford-corenlp-3.5.2.jar:3.5.2]
*/
LOG.warn("NER Classifier err for: " + tokens.stream().map(CoreLabel::word).collect(Collectors.joining(StringUtils.SPACE)));
}
}
} | java | {
"resource": ""
} |
q13808 | ResourceReaderImpl.getOverrideEntry | train | private Tuple<String,String> getOverrideEntry( final String key )
{
for ( String prefix : _overrides )
{
String override = prefix + "." + key;
String value = getPropertyValue( override );
if ( value != null )
{
return new Tuple<String,String>( override, value );
}
}
return null;
} | java | {
"resource": ""
} |
q13809 | ResourceReaderImpl.getEntry | train | private Tuple<String,String> getEntry( final String key )
{
Tuple<String,String> override = getOverrideEntry( key );
if ( override == null )
{
String value = getPropertyValue( key );
if ( value != null )
{
return new Tuple<String,String>( key, value );
}
}
return override;
} | java | {
"resource": ""
} |
q13810 | ResourceReaderImpl.getEntry | train | private Tuple<String,String> getEntry( final String key,
final Collection<String> prefixes )
{
if ( CollectionUtils.isEmpty( prefixes ) )
{
return getEntry( key );
}
for( String prefix : prefixes )
{
String prefixedKey = prefix + "." + key;
Tuple<String,String> override = getOverrideEntry( prefixedKey );
if ( override != null )
{
return override;
}
//
// Above we were checking overrides of the override. Here,
// just check for the first override. If that doesn't work,
// then we need to just pass it on and ignore the specified override.
//
String value = getPropertyValue( prefixedKey );
if ( value != null )
{
return new Tuple<String,String>( prefixedKey, value );
}
}
//
// No prefixed overrides were found, so drop back to using
// the standard, non-prefixed version
//
return getEntry( key );
} | java | {
"resource": ""
} |
q13811 | H2DbConfig.entityManagerFactory | train | @Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.H2);
jpaVendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setPackagesToScan(this.getClass().getPackage().getName());
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
entityManagerFactory.setDataSource(dataSource());
return entityManagerFactory;
} | java | {
"resource": ""
} |
q13812 | H2DbConfig.h2servletRegistration | train | @Bean
public ServletRegistrationBean h2servletRegistration() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new WebServlet());
servletRegistrationBean.addUrlMappings("/h2/*");
return servletRegistrationBean;
} | java | {
"resource": ""
} |
q13813 | PropertyUtils.setAttribute | train | public static void setAttribute(PageContext pageContext, String scope, String name, Object value) throws JspTagException {
pageContext.setAttribute(name, value, Scope.getScopeId(scope));
} | java | {
"resource": ""
} |
q13814 | PropertyUtils.findObject | train | public static Object findObject(PageContext pageContext, String scope, String name, String property, boolean beanRequired, boolean valueRequired) throws JspTagException {
try {
// Check the name
if(name==null) throw new AttributeRequiredException("name");
// Find the bean
Object bean;
if(scope==null) bean = pageContext.findAttribute(name);
else bean = pageContext.getAttribute(name, Scope.getScopeId(scope));
// Check required
if(bean==null) {
if(beanRequired) {
// null and required
if(scope==null) throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.bean.required.nullScope", name);
else throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.bean.required.scope", name, scope);
} else {
// null and not required
return null;
}
} else {
if(property==null) {
// No property lookup, use the bean directly
return bean;
} else {
// Find the property
Object value = org.apache.commons.beanutils.PropertyUtils.getProperty(bean, property);
if(valueRequired && value==null) {
// null and required
if(scope==null) throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.value.required.nullScope", property, name);
else throw new LocalizedJspTagException(ApplicationResources.accessor, "PropertyUtils.value.required.scope", property, name, scope);
}
return value;
}
}
} catch(IllegalAccessException | InvocationTargetException | NoSuchMethodException err) {
throw new JspTagException(err);
}
} | java | {
"resource": ""
} |
q13815 | Scope.getScopeId | train | public static int getScopeId(String scope) throws JspTagException {
if(scope==null || PAGE.equals(scope)) return PageContext.PAGE_SCOPE;
else if(REQUEST.equals(scope)) return PageContext.REQUEST_SCOPE;
else if(SESSION.equals(scope)) return PageContext.SESSION_SCOPE;
else if(APPLICATION.equals(scope)) return PageContext.APPLICATION_SCOPE;
else throw new LocalizedJspTagException(ApplicationResources.accessor, "Scope.scope.invalid", scope);
} | java | {
"resource": ""
} |
q13816 | ResourceBundleUtils.bundleToStringMap | train | public static Map<String,String> bundleToStringMap( final ResourceBundle bundle,
final String suffix )
{
if ( bundle == null )
{
return Collections.<String,String>emptyMap();
}
String theSuffix;
if ( StringUtils.isEmpty( suffix ) )
{
theSuffix = "";
}
else
{
theSuffix = suffix + ".";
}
Map<String,String> map = new LinkedHashMap<String,String>();
Enumeration<String> keys = bundle.getKeys();
while( keys.hasMoreElements() )
{
String key = keys.nextElement();
Object value = bundle.getObject( key );
String strValue = ( value != null ) ? value.toString() : null;
map.put( theSuffix + key, strValue );
}
return map;
} | java | {
"resource": ""
} |
q13817 | KNNClassifier.predict | train | @Override
public Map<String, Double> predict(Tuple predict) {
KNNEngine engine = new KNNEngine(predict, trainingData, k);
if (mode == 1) {
engine.getDistance(engine.chebyshevDistance);
} else if (mode == 2) {
engine.getDistance(engine.manhattanDistance);
} else {
engine.getDistance(engine.euclideanDistance);
}
predict.label = engine.getResult();
Map<String, Double> outputMap = new ConcurrentHashMap<>();
trainingData.parallelStream().forEach(x -> outputMap.put(String.valueOf(x.id), (Double) x.getExtra().get(DISTANCE)));
return outputMap;
} | java | {
"resource": ""
} |
q13818 | WeakHashSet.purge | train | public void purge()
{
WeakElement<?> element;
while( ( element = (WeakElement<?>) _queue.poll() ) != null )
{
_set.remove( element );
}
} | java | {
"resource": ""
} |
q13819 | CRFClassifier.train | train | @Override
public ISeqClassifier train(List<SequenceTuple> trainingData) {
if (trainingData == null || trainingData.size() == 0) {
LOG.warn("Training data is empty.");
return this;
}
if (modelPath == null) {
try {
modelPath = Files.createTempDirectory("crfsuite").toAbsolutePath().toString();
} catch (IOException e) {
LOG.error("Create temp directory failed.", e);
e.printStackTrace();
}
}
Pair<List<ItemSequence>, List<StringList>> crfCompatibleTrainingData = loadTrainingData(trainingData);
Trainer trainer = new Trainer();
String algorithm = (String) props.getOrDefault("algorithm", DEFAULT_ALGORITHM);
props.remove("algorithm");
String graphicalModelType = (String) props.getOrDefault("graphicalModelType", DEFAULT_GRAPHICAL_MODEL_TYPE);
props.remove("graphicalModelType");
trainer.select(algorithm, graphicalModelType);
// Set parameters
props.entrySet().forEach(pair -> trainer.set((String) pair.getKey(), (String) pair.getValue()));
// Add training data into the trainer
for (int i = 0; i < trainingData.size(); i++) {
// Use group id = 0 but the API doesn't say what it is used for :(
trainer.append(crfCompatibleTrainingData.getLeft().get(i), crfCompatibleTrainingData.getRight().get(i), 0);
}
// Start training without hold-outs. trainer.message()
// will be called to report the training process
trainer.train(modelPath, -1);
return this;
} | java | {
"resource": ""
} |
q13820 | OAuthUtils.getSignatureBaseString | train | public static String getSignatureBaseString(String requestMethod, String requestUrl,
Map<String, String> protocolParameters) throws AuthException {
StringBuilder sb = new StringBuilder();
sb.append(requestMethod.toUpperCase()).append("&")
.append(AuthUtils.percentEncode(normalizeUrl(requestUrl))).append("&")
.append(AuthUtils.percentEncode(normalizeParameters(requestUrl, protocolParameters)));
return sb.toString();
} | java | {
"resource": ""
} |
q13821 | TrainingDataUtils.createBalancedTrainingData | train | public static List<Tuple> createBalancedTrainingData(final List<Tuple> trainingData) {
Map<String, Long> tagCount = trainingData.parallelStream()
.map(x -> new AbstractMap.SimpleImmutableEntry<>(x.label, 1))
.collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.counting()));
Map.Entry<String, Long> minCountEntry = tagCount.entrySet().stream()
.min(Comparator.comparing(Map.Entry::getValue))
.orElse(null);
tagCount.clear();
List<Tuple> newData = new ArrayList<>();
for (Tuple t : trainingData) {
String label = t.label;
if (!tagCount.containsKey(label)) {
tagCount.put(t.label, 0L);
}
if (tagCount.get(label) < minCountEntry.getValue()) {
tagCount.put(label, tagCount.get(label) + 1);
newData.add(t);
}
}
return newData;
} | java | {
"resource": ""
} |
q13822 | TrainingDataUtils.splitData | train | public static Pair<List<Tuple>, List<Tuple>> splitData(final List<Tuple> trainingData, double proportion) {
if (proportion < 0 || proportion > 1) {
throw new RuntimeException("Proportion should between 0.0 - 1.0");
}
if (proportion > 0.5) {
proportion = 1 - proportion;
}
List<Tuple> smallList = new ArrayList<>();
List<Tuple> largeList = new ArrayList<>();
int smallListSize = (int) Math.floor(proportion * trainingData.size());
int ct = 0;
Set<Integer> indices = new HashSet<>();
while (ct < smallListSize && trainingData.size() > indices.size()) {
int index = (int) (Math.random() * (trainingData.size() - 1));
while (indices.contains(index)) {
index = (int) (Math.random() * (trainingData.size() - 1));
}
indices.add(index);
ct++;
}
smallList.addAll(indices.stream().map(trainingData::get).collect(Collectors.toList()));
IntStream.range(0, trainingData.size())
.filter(x -> !indices.contains(x))
.forEach(i -> largeList.add(trainingData.get(i)));
return new ImmutablePair<>(smallList, largeList);
} | java | {
"resource": ""
} |
q13823 | NBTrainingEngine.calculateLabelPrior | train | public void calculateLabelPrior() {
double prior = 1D / model.labelIndexer.getLabelSize();
model.labelIndexer.getIndexSet().forEach(labelIndex -> model.labelPrior.put(labelIndex, prior));
} | java | {
"resource": ""
} |
q13824 | MarkupUtils.writeWithMarkup | train | public static void writeWithMarkup(Object value, MarkupType markupType, MediaEncoder encoder, Writer out) throws IOException {
if(encoder==null) {
writeWithMarkup(value, markupType, out);
} else {
if(value!=null) {
if(
value instanceof Writable
&& !((Writable)value).isFastToString()
) {
// Avoid intermediate String from Writable
Coercion.write(value, encoder, out);
} else {
String str = Coercion.toString(value);
BundleLookupMarkup lookupMarkup;
BundleLookupThreadContext threadContext = BundleLookupThreadContext.getThreadContext(false);
if(threadContext!=null) {
lookupMarkup = threadContext.getLookupMarkup(str);
} else {
lookupMarkup = null;
}
if(lookupMarkup!=null) lookupMarkup.appendPrefixTo(markupType, encoder, out);
encoder.write(str, out);
if(lookupMarkup!=null) lookupMarkup.appendSuffixTo(markupType, encoder, out);
}
}
}
} | java | {
"resource": ""
} |
q13825 | SingleWordCorrection.buildModel | train | public void buildModel(String wordFileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(new File(wordFileName)));
String str;
while ((str = br.readLine()) != null) {
List<String> tokens = StanfordParser.stanfordTokenize(str).stream().map(CoreLabel::originalText).collect(Collectors.toList());
for (String word : tokens) {
double count = model.wordProbability.containsKey(word) ? model.wordProbability.get(word) : 0;
count++;
model.wordProbability.put(word, count);
}
}
br.close();
// Remove Empty prob.
model.wordProbability.remove(StringUtils.EMPTY);
model.normalizeWordProbability();
} | java | {
"resource": ""
} |
q13826 | NetUtils.ipv4ToInt | train | public static int ipv4ToInt( final Inet4Address addr )
{
int value = 0;
for( byte chunk : addr.getAddress() )
{
value <<= 8;
value |= chunk & 0xff;
}
return value;
} | java | {
"resource": ""
} |
q13827 | Lists.empty | train | public static <E> List<E> empty(List<E> list) {
return Optional.ofNullable(list).orElse(newArrayList());
} | java | {
"resource": ""
} |
q13828 | Lists.clean | train | public static <E> List<E> clean(List<E> list) {
if (iterable(list)) {
return list.stream().filter(e -> {
if (Objects.isNull(e)) {
return false;
}
if (e instanceof Nullable) {
return !((Nullable) e).isNull();
}
return true;
}).collect(Collectors.toList());
}
return list;
} | java | {
"resource": ""
} |
q13829 | ChainWriter.encodeJavaScriptStringInXmlAttribute | train | public ChainWriter encodeJavaScriptStringInXmlAttribute(Object value) throws IOException {
// Two stage encoding:
// 1) Text -> JavaScript (with quotes added)
// 2) JavaScript -> XML Attribute
if(
value instanceof Writable
&& !((Writable)value).isFastToString()
) {
// Avoid unnecessary toString calls
textInJavaScriptEncoder.writePrefixTo(javaScriptInXhtmlAttributeWriter);
Coercion.write(value, textInJavaScriptEncoder, javaScriptInXhtmlAttributeWriter);
textInJavaScriptEncoder.writeSuffixTo(javaScriptInXhtmlAttributeWriter);
} else {
String str = Coercion.toString(value);
BundleLookupMarkup lookupMarkup;
BundleLookupThreadContext threadContext = BundleLookupThreadContext.getThreadContext(false);
if(threadContext!=null) {
lookupMarkup = threadContext.getLookupMarkup(str);
} else {
lookupMarkup = null;
}
if(lookupMarkup!=null) lookupMarkup.appendPrefixTo(MarkupType.JAVASCRIPT, javaScriptInXhtmlAttributeWriter);
textInJavaScriptEncoder.writePrefixTo(javaScriptInXhtmlAttributeWriter);
textInJavaScriptEncoder.write(str, javaScriptInXhtmlAttributeWriter);
textInJavaScriptEncoder.writeSuffixTo(javaScriptInXhtmlAttributeWriter);
if(lookupMarkup!=null) lookupMarkup.appendSuffixTo(MarkupType.JAVASCRIPT, javaScriptInXhtmlAttributeWriter);
}
return this;
} | java | {
"resource": ""
} |
q13830 | ChainWriter.printEU | train | @Deprecated
public ChainWriter printEU(String value) {
int len = value.length();
for (int c = 0; c < len; c++) {
char ch = value.charAt(c);
if (ch == ' ') out.print('+');
else {
if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) out.print(ch);
else {
out.print('%');
out.print(getHex(ch >>> 4));
out.print(getHex(ch));
}
}
}
return this;
} | java | {
"resource": ""
} |
q13831 | ChainWriter.writeHtmlImagePreloadJavaScript | train | public static void writeHtmlImagePreloadJavaScript(String url, Appendable out) throws IOException {
out.append("<script type='text/javascript'>\n"
+ " var img=new Image();\n"
+ " img.src=\"");
// Escape for javascript
StringBuilder javascript = new StringBuilder(url.length());
encodeTextInJavaScript(url, javascript);
// Encode for XML attribute
encodeJavaScriptInXhtmlAttribute(javascript, out);
out.append("\";\n"
+ "</script>");
} | java | {
"resource": ""
} |
q13832 | Splitter.split | train | public Map<String, String> split(final CharSequence source) {
java.util.Objects.requireNonNull(source, "source");
Map<String, String> parameters = new HashMap<>();
Iterator<String> i = new StringIterator(source, pairSeparator);
while (i.hasNext()) {
String keyValue = i.next();
int keyValueSeparatorPosition = keyValueSeparatorStart(keyValue);
if (keyValueSeparatorPosition == 0 || keyValue.length() == 0) {
continue;
}
if (keyValueSeparatorPosition < 0) {
parameters.put(keyValue, null);
continue;
}
int keyStart = 0;
int keyEnd = keyValueSeparatorPosition;
while (keyStart < keyEnd && keyTrimMatcher.matches(keyValue.charAt(keyStart))) {
keyStart++;
}
while (keyStart < keyEnd && keyTrimMatcher.matches(keyValue.charAt(keyEnd - 1))) {
keyEnd--;
}
int valueStart = keyValueSeparatorPosition + keyValueSeparator.length();
int valueEnd = keyValue.length();
while (valueStart < valueEnd && valueTrimMatcher.matches(keyValue.charAt(valueStart))) {
valueStart++;
}
while (valueStart < valueEnd && valueTrimMatcher.matches(keyValue.charAt(valueEnd - 1))) {
valueEnd--;
}
String key = keyValue.substring(keyStart, keyEnd);
String value = keyValue.substring(valueStart, valueEnd);
parameters.put(key, value);
}
return parameters;
} | java | {
"resource": ""
} |
q13833 | Splitter.trim | train | public Splitter trim(char c) {
Matcher matcher = new CharMatcher(c);
return new Splitter(pairSeparator, keyValueSeparator, matcher, matcher);
} | java | {
"resource": ""
} |
q13834 | Splitter.trim | train | public Splitter trim(char[] chars) {
Matcher matcher = new CharsMatcher(chars);
return new Splitter(pairSeparator, keyValueSeparator, matcher, matcher);
} | java | {
"resource": ""
} |
q13835 | PersistentCache.close | train | public void close() {
super.clear();
if (indexMap != null){
indexMap.clear();
indexMap = null;
}
if (this.indexStore != null){
getIndexStore().close();
this.indexStore = null ;
}
if (this.cacheStore != null){
getCacheStore().close();
this.cacheStore = null ;
}
} | java | {
"resource": ""
} |
q13836 | GISTrainer.gaussianUpdate | train | private double gaussianUpdate(int predicate, int oid, double correctionConstant) {
double param = params[predicate].getParameters()[oid];
double x0 = 0.0;
double modelValue = modelExpects[0][predicate].getParameters()[oid];
double observedValue = observedExpects[predicate].getParameters()[oid];
for (int i = 0; i < 50; i++) {
double tmp = modelValue * Math.exp(correctionConstant * x0);
double f = tmp + (param + x0) / sigma - observedValue;
double fp = tmp * correctionConstant + 1 / sigma;
if (fp == 0) {
break;
}
double x = x0 - f / fp;
if (Math.abs(x - x0) < 0.000001) {
x0 = x;
break;
}
x0 = x;
}
return x0;
} | java | {
"resource": ""
} |
q13837 | BufferedEncoder.writeSuffixTo | train | @Override
final public void writeSuffixTo(Appendable out) throws IOException {
writeSuffix(buffer, out);
buffer.setLength(0);
} | java | {
"resource": ""
} |
q13838 | Coercion.nullIfEmpty | train | public static <T> T nullIfEmpty(T value) throws IOException {
return isEmpty(value) ? null : value;
} | java | {
"resource": ""
} |
q13839 | StringUtilities.toCapCase | train | public static String toCapCase( final String string )
{
if ( string == null )
{
return null;
}
if( string.length() == 1 )
{
return string.toUpperCase();
}
return Character.toUpperCase( string.charAt( 0 ) ) + string.substring( 1 ).toLowerCase();
} | java | {
"resource": ""
} |
q13840 | StringUtilities.appendToBuffer | train | public static void appendToBuffer( final StringBuffer buffer,
final String string,
final String delimiter )
{
if ( string == null )
{
return;
}
//
// Only append the delimiter in front if the buffer isn't empty.
//
if ( buffer.length() == 0 || delimiter == null )
{
buffer.append( string );
}
else
{
buffer.append( delimiter ).append( string );
}
} | java | {
"resource": ""
} |
q13841 | StringUtilities.coalesce | train | @SafeVarargs
public static <T> T coalesce( final T ... things )
{
if( things == null || things.length == 0 )
{
return null;
}
for( T thing : things )
{
if( thing != null )
{
return thing;
}
}
return null;
} | java | {
"resource": ""
} |
q13842 | StringUtilities.coalesceNonEmpty | train | @SafeVarargs
public static <T> T coalesceNonEmpty( final T ... things )
{
if( things == null || things.length == 0 )
{
return null;
}
for( T thing : things )
{
if( thing instanceof CharSequence )
{
if( ! StringUtils.isBlank( (CharSequence) thing ) )
{
return thing;
}
}
else if( thing != null )
{
return thing;
}
}
return null;
} | java | {
"resource": ""
} |
q13843 | InputTagBeanInfo.getAdditionalBeanInfo | train | @Override
public BeanInfo[] getAdditionalBeanInfo() {
try {
return new BeanInfo[] {
Introspector.getBeanInfo(InputTag.class.getSuperclass())
};
} catch(IntrospectionException err) {
throw new AssertionError(err);
}
} | java | {
"resource": ""
} |
q13844 | OsUtils.fileNameFromString | train | public static String fileNameFromString( final String text )
{
String value = text.replace( ' ', '_' );
if ( value.length() < 48 )
{
return value;
}
return value.substring( 0, 47 );
} | java | {
"resource": ""
} |
q13845 | OsUtils.executeToFile | train | public static int executeToFile( final String[] command,
final File file )
throws
IOException,
InterruptedException
{
return executeToFile( command, file, System.err );
} | java | {
"resource": ""
} |
q13846 | OsUtils.executeToFile | train | public static int executeToFile( final String[] command,
final File file,
final OutputStream stderr )
throws
IOException,
InterruptedException
{
return executeToStreams( command, new FileOutputStream( file ), stderr );
} | java | {
"resource": ""
} |
q13847 | OsUtils.makeSecurityCheck | train | public static void makeSecurityCheck( final File file,
final File base )
{
if( ! file.getAbsolutePath().startsWith( base.getAbsolutePath() ) )
{
throw new IllegalArgumentException( "Illegal file path [" + file + "]" );
}
} | java | {
"resource": ""
} |
q13848 | LinkTag.setLink | train | public void setLink(Link link) {
setHref(link.getHref());
setHrefAbsolute(link.getHrefAbsolute());
HttpParameters linkParams = link.getParams();
if(linkParams != null) {
for(Map.Entry<String,List<String>> entry : linkParams.getParameterMap().entrySet()) {
String paramName = entry.getKey();
for(String paramValue : entry.getValue()) {
addParam(paramName, paramValue);
}
}
}
this.addLastModified = link.getAddLastModified();
setHreflang(link.getHreflang());
setRel(link.getRel());
setType(link.getType());
setMedia(link.getMedia());
setTitle(link.getTitle());
} | java | {
"resource": ""
} |
q13849 | OnePassRealValueDataIndexer.update | train | protected static void update(String[] ec, Set<String> predicateSet, Map<String, Integer> counter, int cutoff) {
for (String s : ec) {
Integer val = counter.get(s);
val = val == null ? 1 : val + 1;
counter.put(s, val);
if (!predicateSet.contains(s) && counter.get(s) >= cutoff) {
predicateSet.add(s);
}
}
} | java | {
"resource": ""
} |
q13850 | StanfordNNDepParser.tagDependencies | train | private GrammaticalStructure tagDependencies(List<? extends HasWord> taggedWords) {
GrammaticalStructure gs = nndepParser.predict(taggedWords);
return gs;
} | java | {
"resource": ""
} |
q13851 | FeatureIndexer.getFeatNames | train | public String[] getFeatNames() {
String[] namesArray = new String[nameIndexMap.size()];
for (Map.Entry<String, Integer> entry : nameIndexMap.entrySet()) {
namesArray[entry.getValue()] = entry.getKey();
}
return namesArray;
} | java | {
"resource": ""
} |
q13852 | StanfordPCFGParser.tagPOS | train | public void tagPOS(List<CoreLabel> tokens, Tree tree) {
try {
List<TaggedWord> posList = tree.getChild(0).taggedYield();
for (int i = 0; i < tokens.size(); i++) {
String pos = posList.get(i).tag();
tokens.get(i).setTag(pos);
}
} catch (Exception e) {
tagPOS(tokens); // At least gives you something.
LOG.warn("POS Failed:\n" + tree.pennString());
}
} | java | {
"resource": ""
} |
q13853 | StanfordPCFGParser.parseForCoref | train | public Pair<CoreMap, GrammaticalStructure> parseForCoref(String sentence) {
List<CoreLabel> tokens = stanfordTokenize(sentence);
Tree tree = parser.parse(tokens);
GrammaticalStructure gs = tagDependencies(tree, true);
tagPOS(tokens);
tagLemma(tokens);
tagNamedEntity(tokens);
CoreMap result = new ArrayCoreMap();
result.set(CoreAnnotations.TokensAnnotation.class, tokens);
result.set(TreeCoreAnnotations.TreeAnnotation.class, tree);
GrammaticalStructure.Extras extras = GrammaticalStructure.Extras.NONE;
SemanticGraph deps = SemanticGraphFactory.generateCollapsedDependencies(gs, extras);
SemanticGraph uncollapsedDeps = SemanticGraphFactory.generateUncollapsedDependencies(gs, extras);
SemanticGraph ccDeps = SemanticGraphFactory.generateCCProcessedDependencies(gs, extras);
result.set(SemanticGraphCoreAnnotations.CollapsedDependenciesAnnotation.class, deps);
result.set(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class, uncollapsedDeps);
result.set(SemanticGraphCoreAnnotations.CollapsedCCProcessedDependenciesAnnotation.class, ccDeps);
return new ImmutablePair<>(result, gs);
} | java | {
"resource": ""
} |
q13854 | ExceptionUtils.causedBy | train | public static boolean causedBy( final Throwable ex,
final Class<? extends Throwable> exceptionClass )
{
Throwable cause = ex;
while( cause != null && ! exceptionClass.isInstance( cause ) )
{
cause = cause.getCause();
}
return ( cause == null ) ? false : true;
} | java | {
"resource": ""
} |
q13855 | ExceptionUtils.getCause | train | public static <T extends Throwable> T getCause( final Throwable ex,
final Class<T> exceptionClass )
{
Throwable cause = ex;
while( cause != null && ! exceptionClass.isInstance( cause ) )
{
cause = cause.getCause();
}
return ( cause == null ) ? null : exceptionClass.cast( cause );
} | java | {
"resource": ""
} |
q13856 | ExceptionUtils.getMessage | train | public static String getMessage( final Throwable ex )
{
String message = ex.getMessage();
//
// It *appears* as though the SQLException hasn't been
// converted to nest? It seems like it has it's own
// method of nesting, not sure why. I don't know
// why Sun wouldn't have converted it. Maybe they
// did, but just left these getNextException methods
// on for compatibility? In my java source code, they
// aren't deprecated, though.
//
if ( ex instanceof SQLException )
{
String sqlMessage = getSqlExceptionMessage( (SQLException) ex );
if ( ! StringUtils.isBlank( sqlMessage ) )
{
if ( ! StringUtils.isBlank( message ) )
{
message += "\n" + sqlMessage;
}
else
{
message = sqlMessage;
}
}
}
Throwable cause = ex.getCause();
if ( ex instanceof SamSixException
&& ((SamSixException) ex).isShowThisCauseOnly() )
{
return message;
}
if ( cause != null )
{
String causeMessage = ExceptionUtils.getMessage( cause );
if ( ! StringUtils.isBlank( causeMessage ) )
{
if ( ! StringUtils.isBlank( message ) )
{
//
// ALWAYS use "broadest first" when showing error messages.
// Otherwise, error messages end up with some non-human readable thing at the top,
// confusing users with deeply technical details. This is especially important for user errors.
//
// broadest/non-broadest should be used for stack traces only.
//
message = message + "\n" + causeMessage;
}
else
{
message = causeMessage;
}
}
}
if ( ! StringUtils.isBlank( message ) )
{
return message;
}
return ex.getClass().getName() + ": An error has been detected.";
} | java | {
"resource": ""
} |
q13857 | MacAuthUtils.getNonce | train | public static String getNonce(long issueTime) {
long currentTime = new Date().getTime();
return TimeUnit.MILLISECONDS.toSeconds(currentTime - issueTime) + ":" + Long.toString(System.nanoTime());
} | java | {
"resource": ""
} |
q13858 | SimpleMethodInvoker.invoke | train | public static Object invoke( final Object obj,
final String methodName,
final Object param )
throws
UtilException
{
//
// This time we have a parameter passed in.
//
// We can therefore work out it's class (type) and pass
// that through to our invokeOneArgMethod 'wrapper' method.
//
return invokeOneArgMethod( obj,
methodName,
param,
param.getClass() );
} | java | {
"resource": ""
} |
q13859 | SimpleMethodInvoker.invoke | train | public static Object invoke( final Object obj,
final String methodName,
final Object param,
final Class<?> parameterType )
throws
UtilException
{
//
// For this call, we have all the information passed in to
// this method for us to use.
//
// It may turn out to have the wrong contents etc. but the
// final method to actually invoke the 'methodName' stated
// here on the 'obj'(ect) stated here, will deal with that.
//
return invokeOneArgMethod( obj,
methodName,
param,
parameterType );
} | java | {
"resource": ""
} |
q13860 | SimpleMethodInvoker.invokeStaticMethod | train | public static Object invokeStaticMethod( final Class<?> objClass,
final String methodName,
final Object param )
throws
UtilException
{
//
// This time we have a parameter passed in.
//
// We can therefore work out it's class (type) and pass
// that through to our invokeOneArgStaticMethod 'wrapper' method.
//
return invokeOneArgStaticMethod( objClass,
methodName,
param,
param.getClass() );
} | java | {
"resource": ""
} |
q13861 | CommandLineRunner.runCommandLine | train | public int runCommandLine() throws IOException, InterruptedException
{
logRunnerConfiguration();
ProcessBuilder processBuilder = new ProcessBuilder( getCommandLineArguments() );
processBuilder.directory( workingDirectory );
processBuilder.environment().putAll( environmentVars );
Process commandLineProc = processBuilder.start();
final StreamPumper stdoutPumper = new StreamPumper( commandLineProc.getInputStream(), outputConsumer );
final StreamPumper stderrPumper = new StreamPumper( commandLineProc.getErrorStream(), errorConsumer );
stdoutPumper.start();
stderrPumper.start();
if ( standardInputString != null )
{
OutputStream outputStream = commandLineProc.getOutputStream();
outputStream.write( standardInputString.getBytes() );
outputStream.close();
}
int exitCode = commandLineProc.waitFor();
stdoutPumper.waitUntilDone();
stderrPumper.waitUntilDone();
if ( exitCode == 0 )
{
LOGGER.fine( processName + " returned zero exit code" );
}
else
{
LOGGER.severe( processName + " returned non-zero exit code (" + exitCode + ")" );
}
return exitCode;
} | java | {
"resource": ""
} |
q13862 | VCProjectParser.getDefaultOutputDirectory | train | private File getDefaultOutputDirectory()
{
//The default output directory is the configuration name
String childOutputDirectory = getConfiguration();
//However, for platforms others than Win32, the default output directory becomes platform/configuration
if ( ! getPlatform().equals( "Win32" ) )
{
childOutputDirectory = new File( getPlatform(), childOutputDirectory ).getPath();
}
//Place the default output directory within the appropriate base directory
return new File( getBaseDirectory(), childOutputDirectory );
} | java | {
"resource": ""
} |
q13863 | VCProjectParser.getBaseDirectory | train | private File getBaseDirectory()
{
File referenceFile = ( solutionFile != null ? solutionFile : getInputFile() );
return referenceFile.getParentFile().getAbsoluteFile();
} | java | {
"resource": ""
} |
q13864 | PropertyDoesNotExistCriterion.toSqlString | train | public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String[] columns;
try
{
columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName);
}
catch (QueryException e)
{
columns = new String[0];
}
// if there are columns that map the given property.. the property exists, so we don't need to add anything to the sql
return columns.length > 0 ? "FALSE" : "TRUE";
} | java | {
"resource": ""
} |
q13865 | DatabaseMapping.getIdProperty | train | public String getIdProperty(TableRef tableRef) {
TableMapping tableMapping = mappedClasses.get(tableRef);
if (tableMapping == null) {
return null;
}
ColumnMetaData identifierColumn = tableMapping.getIdentifierColumn();
return tableMapping.getColumnMapping(identifierColumn).getPropertyName();
} | java | {
"resource": ""
} |
q13866 | DatabaseMapping.getGeometryProperty | train | public String getGeometryProperty(TableRef tableRef) {
TableMapping tableMapping = mappedClasses.get(tableRef);
if (tableMapping == null) {
return null;
}
for (ColumnMetaData columnMetaData : tableMapping.getMappedColumns()) {
if (columnMetaData.isGeometry()) {
ColumnMapping cm = tableMapping.getColumnMapping(columnMetaData);
return cm.getPropertyName();
}
}
return null;
} | java | {
"resource": ""
} |
q13867 | Filter.run | train | public void run(String cmd, CommandFilter f) {
CommandWords commandWord = null;
if ( cmd.contains(" ") ) {
try {
commandWord = CommandWords.valueOf(cmd.substring(1, cmd.indexOf(" ")));
} catch (IllegalArgumentException e) {
commandWord = CommandWords.INVALID_COMMAND_WORD;
}
} else {
commandWord = CommandWords.INVALID_COMMAND_WORD;
}
switch (commandWord) {
case change_player_type:
f.changePlayerTypeCommand(cmd.substring(20, cmd.length() - 1));
break;
case error:
f.errorCommand(cmd.substring(7, cmd.length() - 1));
break;
case hear:
f.hearCommand(cmd.substring(6, cmd.length() - 1));
break;
case init:
f.initCommand(cmd.substring(6, cmd.length() - 1));
break;
case ok:
f.okCommand(cmd.substring(4, cmd.length() - 1));
break;
case player_param:
f.playerParamCommand(cmd.substring(14, cmd.length() - 1));
break;
case player_type:
f.playerTypeCommand(cmd.substring(13, cmd.length() - 1));
break;
case see:
f.seeCommand(cmd.substring(5, cmd.length() - 1));
break;
case see_global:
f.seeCommand(cmd.substring(12, cmd.length() - 1));
break;
case sense_body:
f.senseBodyCommand(cmd.substring(12, cmd.length() - 1));
break;
case server_param:
f.serverParamCommand(cmd.substring(14, cmd.length() - 1));
break;
case warning :
f.warningCommand(cmd.substring(9, cmd.length() - 1));
break;
case INVALID_COMMAND_WORD :
default :
throw new Error("Invalid command received: \"" + cmd + "\"");
}
} | java | {
"resource": ""
} |
q13868 | VersionInfoMojo.addProjectProperties | train | private void addProjectProperties() throws MojoExecutionException
{
Properties projectProps = mavenProject.getProperties();
projectProps.setProperty( PROPERTY_NAME_COMPANY, versionInfo.getCompanyName() );
projectProps.setProperty( PROPERTY_NAME_COPYRIGHT, versionInfo.getCopyright() );
projectProps.setProperty( PROPERTY_NAME_VERSION_MAJOR, "0" );
projectProps.setProperty( PROPERTY_NAME_VERSION_MINOR, "0" );
projectProps.setProperty( PROPERTY_NAME_VERSION_INCREMENTAL, "0" );
projectProps.setProperty( PROPERTY_NAME_VERSION_BUILD, "0" );
String version = mavenProject.getVersion();
if ( version != null && version.length() > 0 )
{
ArtifactVersion artifactVersion = new DefaultArtifactVersion( version );
if ( version.equals( artifactVersion.getQualifier() ) )
{
String msg = "Unable to parse the version string, please use standard maven version format.";
getLog().error( msg );
throw new MojoExecutionException( msg );
}
projectProps.setProperty( PROPERTY_NAME_VERSION_MAJOR,
String.valueOf( artifactVersion.getMajorVersion() ) );
projectProps.setProperty( PROPERTY_NAME_VERSION_MINOR,
String.valueOf( artifactVersion.getMinorVersion() ) );
projectProps.setProperty( PROPERTY_NAME_VERSION_INCREMENTAL,
String.valueOf( artifactVersion.getIncrementalVersion() ) );
projectProps.setProperty( PROPERTY_NAME_VERSION_BUILD,
String.valueOf( artifactVersion.getBuildNumber() ) );
}
else
{
getLog().warn( "Missing version for project. Version parts will be set to 0" );
}
} | java | {
"resource": ""
} |
q13869 | VersionInfoMojo.writeVersionInfoTemplateToTempFile | train | private File writeVersionInfoTemplateToTempFile() throws MojoExecutionException
{
try
{
final File versionInfoSrc = File.createTempFile( "msbuild-maven-plugin_" + MOJO_NAME, null );
InputStream is = getClass().getResourceAsStream( DEFAULT_VERSION_INFO_TEMPLATE );
FileOutputStream dest = new FileOutputStream( versionInfoSrc );
byte[] buffer = new byte[1024];
int read = -1;
while ( ( read = is.read( buffer ) ) != -1 )
{
dest.write( buffer, 0, read );
}
dest.close();
return versionInfoSrc;
}
catch ( IOException ioe )
{
String msg = "Failed to create temporary version file";
getLog().error( msg, ioe );
throw new MojoExecutionException( msg, ioe );
}
} | java | {
"resource": ""
} |
q13870 | VariablesMap.applyParser | train | private void applyParser()
{
this.snapshot.clear();
Map<String, String> originals = new HashMap<String, String>(this.resolvers.size());
for ( Entry<String, VariableValue> resolver : this.resolvers.entrySet() )
{
originals.put(resolver.getKey(), resolver.getValue().getOriginal());
}
putAll(originals);
} | java | {
"resource": ""
} |
q13871 | ConfigurationModule.bindProperty | train | protected PropertyValueBindingBuilder bindProperty( final String name )
{
checkNotNull( name, "Property name cannot be null." );
return new PropertyValueBindingBuilder()
{
public void toValue( final String value )
{
checkNotNull( value, "Null value not admitted for property '%s's", name );
bindConstant().annotatedWith( named( name ) ).to( value );
}
};
} | java | {
"resource": ""
} |
q13872 | Tree.addLeaf | train | public Tree<T> addLeaf( T child )
{
Tree<T> leaf = new Tree<T>( child );
leaf.parent = this;
children.add( leaf );
return leaf;
} | java | {
"resource": ""
} |
q13873 | Tree.removeSubtree | train | public void removeSubtree( Tree<T> subtree )
{
if ( children.remove( subtree ) )
{
subtree.parent = null;
}
} | java | {
"resource": ""
} |
q13874 | Tree.addSubtree | train | public Tree<T> addSubtree( Tree<T> subtree )
{
Tree<T> copy = addLeaf( subtree.data );
copy.children = new ArrayList<Tree<T>>( subtree.children );
return copy;
} | java | {
"resource": ""
} |
q13875 | Guards.checkIsSetLocal | train | public static void checkIsSetLocal(final DelegateExecution execution, final String variableName) {
Preconditions.checkArgument(variableName != null, VARIABLE_NAME_MUST_BE_NOT_NULL);
final Object variableLocal = execution.getVariableLocal(variableName);
Preconditions.checkState(variableLocal != null,
String.format("Condition of task '%s' is violated: Local variable '%s' is not set.", new Object[] { execution.getCurrentActivityId(), variableName }));
} | java | {
"resource": ""
} |
q13876 | Guards.checkIsSetGlobal | train | public static void checkIsSetGlobal(final DelegateExecution execution, final String variableName) {
Preconditions.checkArgument(variableName != null, VARIABLE_SKIP_GUARDS);
final Object variable = execution.getVariable(variableName);
Preconditions.checkState(variable != null,
String.format("Condition of task '%s' is violated: Global variable '%s' is not set.", new Object[] { execution.getCurrentActivityId(), variableName }));
} | java | {
"resource": ""
} |
q13877 | CppCheckMojo.getRelativeIncludeDirectories | train | private List<File> getRelativeIncludeDirectories( VCProject vcProject ) throws MojoExecutionException
{
final List<File> relativeIncludeDirectories = new ArrayList<File>();
for ( File includeDir : vcProject.getIncludeDirectories() )
{
if ( includeDir.isAbsolute() )
{
relativeIncludeDirectories.add( includeDir );
}
else
{
try
{
File absoluteIncludeDir = new File ( vcProject.getFile().getParentFile(), includeDir.getPath() );
relativeIncludeDirectories.add( getRelativeFile( vcProject.getBaseDirectory(),
absoluteIncludeDir.getCanonicalFile() ) );
}
catch ( IOException ioe )
{
throw new MojoExecutionException( "Failed to compute relative path for directroy " + includeDir,
ioe );
}
}
}
return relativeIncludeDirectories;
} | java | {
"resource": ""
} |
q13878 | CamundaSteps.cleanUp | train | @AfterStory(uponGivenStory = false)
public void cleanUp() {
LOG.debug("Cleaning up after story run.");
Mocks.reset();
support.undeploy();
support.resetClock();
ProcessEngineAssertions.reset();
} | java | {
"resource": ""
} |
q13879 | CamundaSteps.stepIsReached | train | @Then("the step $activityId is reached")
@When("the step $activityId is reached")
public void stepIsReached(final String activityId) {
assertThat(support.getProcessInstance()).isWaitingAt(activityId);
LOG.debug("Step {} reached.", activityId);
} | java | {
"resource": ""
} |
q13880 | MSBuildPackaging.isValid | train | public static boolean isValid( String packaging )
{
return MSBUILD_SOLUTION.equals( packaging )
|| EXE.equals( packaging )
|| DLL.equals( packaging )
|| LIB.equals( packaging );
} | java | {
"resource": ""
} |
q13881 | MSBuildPackaging.validPackaging | train | public static final String validPackaging()
{
return new StringBuilder()
.append( MSBUILD_SOLUTION ).append( ", " )
.append( EXE ).append( ", " )
.append( DLL ).append( ", " )
.append( LIB ).toString();
} | java | {
"resource": ""
} |
q13882 | ByteBuffer.setString | train | public void setString(String str) throws IOException {
Reader r = new StringReader(str);
int c;
reset();
while (((c = r.read()) != 0) && (c != -1)) {
write(c);
}
} | java | {
"resource": ""
} |
q13883 | ByteBuffer.getString | train | public String getString() throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(buf);
int c;
StringWriter w = new StringWriter();
while (((c = in.read()) != 0) && (c != -1)) {
w.write((char) c);
}
return w.getBuffer().toString();
} | java | {
"resource": ""
} |
q13884 | BuildPlatform.identifyPrimaryConfiguration | train | public void identifyPrimaryConfiguration() throws MojoExecutionException
{
Set<String> configurationNames = new HashSet<String>();
for ( BuildConfiguration configuration : configurations )
{
if ( configurationNames.contains( configuration.getName() ) )
{
throw new MojoExecutionException( "Duplicate configuration '" + configuration.getName()
+ "' for '" + getName() + "', configuration names must be unique" );
}
configurationNames.add( configuration.getName() );
configuration.setPrimary( false );
}
if ( configurations.contains( RELEASE_CONFIGURATION ) )
{
configurations.get( configurations.indexOf( RELEASE_CONFIGURATION ) ).setPrimary( true );
}
else if ( configurations.contains( DEBUG_CONFIGURATION ) )
{
configurations.get( configurations.indexOf( DEBUG_CONFIGURATION ) ).setPrimary( true );
}
else
{
configurations.get( 0 ).setPrimary( true );
}
} | java | {
"resource": ""
} |
q13885 | VersionInfoConfiguration.getCopyright | train | public final String getCopyright()
{
if ( copyright == null )
{
StringBuilder sb = new StringBuilder();
sb.append( COPYRIGHT_PREAMBLE )
.append( " " )
.append( Calendar.getInstance().get( Calendar.YEAR ) )
.append( " " )
.append( companyName );
copyright = sb.toString();
}
return copyright;
} | java | {
"resource": ""
} |
q13886 | AbstractTeam.createNewPlayers | train | public void createNewPlayers() {
for (int i = 0; i < size(); i++) {
players[i] = new SServerPlayer(teamName, getNewControllerPlayer(i), playerPort, hostname);
}
} | java | {
"resource": ""
} |
q13887 | AbstractTeam.connectAll | train | public void connectAll() {
for (int i = 0; i < size(); i++) {
if (i == 0) {
players[i].connect(true);
} else if (i >= 1) {
try {
players[i].connect(false);
} catch (Exception ex) {
players[i].handleError(ex.getMessage());
}
}
pause(500);
}
if (hasCoach) {
try {
coach.connect();
} catch (Exception ex) {
coach.handleError(ex.getMessage());
}
pause(500);
}
} | java | {
"resource": ""
} |
q13888 | AbstractTeam.connect | train | public void connect(int index) {
try {
if (index == 0) {
players[index].connect(true);
} else {
players[index].connect(false);
}
} catch (Exception ex) {
players[index].handleError(ex.getMessage());
}
pause(500);
} | java | {
"resource": ""
} |
q13889 | AbstractMSBuildPluginMojo.findProperty | train | private String findProperty( String prop )
{
String result = System.getProperty( prop );
if ( result == null )
{
result = mavenProject.getProperties().getProperty( prop );
}
return result;
} | java | {
"resource": ""
} |
q13890 | AbstractMSBuildPluginMojo.validateProjectFile | train | protected void validateProjectFile()
throws MojoExecutionException
{
if ( projectFile != null
&& projectFile.exists()
&& projectFile.isFile() )
{
getLog().debug( "Project file validated at " + projectFile );
boolean solutionFile = projectFile.getName().toLowerCase().endsWith( "." + SOLUTION_EXTENSION );
if ( ( MSBuildPackaging.isSolution( mavenProject.getPackaging() ) && ! solutionFile )
|| ( ! MSBuildPackaging.isSolution( mavenProject.getPackaging() ) && solutionFile ) )
{
// Solution packaging defined but the projectFile is not a .sln
String msg = "Packaging doesn't match project file type. "
+ "If you specify a solution file then packaging must be " + MSBuildPackaging.MSBUILD_SOLUTION;
getLog().error( msg );
throw new MojoExecutionException( msg );
}
return;
}
String prefix = "Missing projectFile";
if ( projectFile != null )
{
prefix = ". The specified projectFile '" + projectFile
+ "' is not valid";
}
throw new MojoExecutionException( prefix
+ ", please check your configuration" );
} | java | {
"resource": ""
} |
q13891 | AbstractMSBuildPluginMojo.getProjectSources | train | protected List<File> getProjectSources( VCProject vcProject, boolean includeHeaders, List<String> excludes )
throws MojoExecutionException
{
final DirectoryScanner directoryScanner = new DirectoryScanner();
List<String> sourceFilePatterns = new ArrayList<String>();
String relProjectDir = calculateProjectRelativeDirectory( vcProject );
sourceFilePatterns.add( relProjectDir + "**\\*.c" );
sourceFilePatterns.add( relProjectDir + "**\\*.cpp" );
if ( includeHeaders )
{
sourceFilePatterns.add( relProjectDir + "**\\*.h" );
sourceFilePatterns.add( relProjectDir + "**\\*.hpp" );
}
//Make sure we use case-insensitive matches as this plugin runs on a Windows platform
directoryScanner.setCaseSensitive( false );
directoryScanner.setIncludes( sourceFilePatterns.toArray( new String[0] ) );
directoryScanner.setExcludes( excludes.toArray( new String[excludes.size()] ) );
directoryScanner.setBasedir( vcProject.getBaseDirectory() );
directoryScanner.scan();
List<File> sourceFiles = new ArrayList<File>();
for ( String fileName : directoryScanner.getIncludedFiles() )
{
sourceFiles.add( new File( vcProject.getBaseDirectory(), fileName ) );
}
return sourceFiles;
} | java | {
"resource": ""
} |
q13892 | AbstractMSBuildPluginMojo.getParsedProjects | train | protected List<VCProject> getParsedProjects( BuildPlatform platform, BuildConfiguration configuration )
throws MojoExecutionException
{
Map<String, String> envVariables = new HashMap<String, String>();
if ( isCxxTestEnabled( null, true ) )
{
envVariables.put( CxxTestConfiguration.HOME_ENVVAR, cxxTest.getCxxTestHome().getPath() );
}
VCProjectHolder vcProjectHolder = VCProjectHolder.getVCProjectHolder( projectFile,
MSBuildPackaging.isSolution( mavenProject.getPackaging() ), envVariables );
try
{
return vcProjectHolder.getParsedProjects( platform.getName(), configuration.getName() );
}
catch ( FileNotFoundException fnfe )
{
throw new MojoExecutionException( "Could not find file " + projectFile, fnfe );
}
catch ( IOException ioe )
{
throw new MojoExecutionException( "I/O error while parsing file " + projectFile, ioe );
}
catch ( SAXException se )
{
throw new MojoExecutionException( "Syntax error while parsing file " + projectFile, se );
}
catch ( ParserConfigurationException pce )
{
throw new MojoExecutionException( "XML parser configuration exception ", pce );
}
catch ( ParseException pe )
{
throw new MojoExecutionException( "Syntax error while parsing solution file " + projectFile, pe );
}
} | java | {
"resource": ""
} |
q13893 | AbstractMSBuildPluginMojo.getParsedProjects | train | protected List<VCProject> getParsedProjects( BuildPlatform platform, BuildConfiguration configuration,
String filterRegex ) throws MojoExecutionException
{
Pattern filterPattern = null;
List<VCProject> filteredList = new ArrayList<VCProject>();
if ( filterRegex != null )
{
filterPattern = Pattern.compile( filterRegex );
}
for ( VCProject vcProject : getParsedProjects( platform, configuration ) )
{
if ( filterPattern == null )
{
filteredList.add( vcProject );
}
else
{
Matcher prjExcludeMatcher = filterPattern.matcher( vcProject.getName() );
if ( ! prjExcludeMatcher.matches() )
{
filteredList.add( vcProject );
}
}
}
return filteredList;
} | java | {
"resource": ""
} |
q13894 | AbstractMSBuildPluginMojo.getOutputDirectories | train | protected List<File> getOutputDirectories( BuildPlatform p, BuildConfiguration c )
throws MojoExecutionException
{
List<File> result = new ArrayList<File>();
// If there is a configured value use it
File configured = c.getOutputDirectory();
if ( configured != null )
{
result.add( configured );
}
else
{
List<VCProject> projects = getParsedProjects( p, c );
if ( projects.size() == 1 )
{
// probably a standalone project
result.add( projects.get( 0 ).getOutputDirectory() );
}
else
{
// a solution
for ( VCProject project : projects )
{
boolean addResult = false;
if ( targets == null )
{
// building all targets, add all outputs
addResult = true;
}
else
{
// building select targets, only add ones we were asked for
if ( targets.contains( project.getTargetName() ) )
{
addResult = true;
}
}
if ( addResult && ! result.contains( project.getOutputDirectory() ) )
{
result.add( project.getOutputDirectory() );
}
}
}
}
if ( result.size() < 1 )
{
String exceptionMessage = "Could not identify any output directories, configuration error?";
getLog().error( exceptionMessage );
throw new MojoExecutionException( exceptionMessage );
}
for ( File toTest: result )
{
// result will be populated, now check if it was created
if ( ! toTest.exists() && ! toTest.isDirectory() )
{
String exceptionMessage = "Expected output directory was not created, configuration error?";
getLog().error( exceptionMessage );
getLog().error( "Looking for build output at " + toTest.getAbsolutePath() );
throw new MojoExecutionException( exceptionMessage );
}
}
return result;
} | java | {
"resource": ""
} |
q13895 | AbstractMSBuildPluginMojo.isCppCheckEnabled | train | protected boolean isCppCheckEnabled( boolean quiet )
{
if ( cppCheck.getSkip() )
{
if ( ! quiet )
{
getLog().info( CppCheckConfiguration.SKIP_MESSAGE
+ ", 'skip' set to true in the " + CppCheckConfiguration.TOOL_NAME + " configuration" );
}
return false;
}
if ( cppCheck.getCppCheckPath() == null )
{
if ( ! quiet )
{
getLog().info( CppCheckConfiguration.SKIP_MESSAGE
+ ", path to " + CppCheckConfiguration.TOOL_NAME + " not set" );
}
return false;
}
return true;
} | java | {
"resource": ""
} |
q13896 | AbstractMSBuildPluginMojo.isVeraEnabled | train | protected boolean isVeraEnabled( boolean quiet )
{
if ( vera.getSkip() )
{
if ( ! quiet )
{
getLog().info( VeraConfiguration.SKIP_MESSAGE
+ ", 'skip' set to true in the " + VeraConfiguration.TOOL_NAME + " configuration" );
}
return false;
}
if ( vera.getVeraHome() == null )
{
if ( ! quiet )
{
getLog().info( VeraConfiguration.SKIP_MESSAGE
+ ", path to " + VeraConfiguration.TOOL_NAME + " home directory not set" );
}
return false;
}
return true;
} | java | {
"resource": ""
} |
q13897 | AbstractUDPClient.send | train | public void send(String message) throws IOException {
buf.setString(message);
DatagramPacket packet = new DatagramPacket(buf.getByteArray(), buf.length(), host, port);
socket.send(packet);
} | java | {
"resource": ""
} |
q13898 | AbstractUDPClient.toStateString | train | public String toStateString() {
StringBuffer buff = new StringBuffer();
buff.append("Host: ");
buff.append(this.hostname);
buff.append(':');
buff.append(this.port);
buff.append("\n");
return buff.toString();
} | java | {
"resource": ""
} |
q13899 | UrlSchemeRegistry.register | train | public static void register(final String scheme, Class<? extends URLStreamHandler> handlerType)
{
if (!registeredSchemes.add(scheme)) {
throw new IllegalStateException("a scheme has already been registered for " + scheme);
}
registerPackage("org.skife.url.generated");
Enhancer e = new Enhancer();
e.setNamingPolicy(new NamingPolicy()
{
@Override
public String getClassName(String prefix, String source, Object key, Predicate names)
{
return "org.skife.url.generated." + scheme + ".Handler";
}
});
e.setSuperclass(handlerType);
e.setCallbackType(NoOp.class);
e.createClass();
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.