idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
5,300
public BeanId getFirstReference ( final String propertyName ) { List < BeanId > refrences = getReference ( propertyName ) ; if ( refrences == null || refrences . size ( ) < 1 ) { return null ; } return refrences . get ( 0 ) ; }
A helper method for getting the value of single referenced property . Returns null if the refrences does not exist .
5,301
public static Optional < CacheManager > lookup ( ) { CacheManager manager = lookup . lookup ( CacheManager . class ) ; if ( manager != null ) { return Optional . of ( manager ) ; } else { return Optional . absent ( ) ; } }
Lookup the most suitable CacheManager available .
5,302
public static String percentEncode ( String source ) throws AuthException { try { return URLEncoder . encode ( source , "UTF-8" ) . replace ( "+" , "%20" ) . replace ( "*" , "%2A" ) . replace ( "%7E" , "~" ) ; } catch ( UnsupportedEncodingException ex ) { throw new AuthException ( "cannot encode value '" + source + "'"...
Returns an encoded string .
5,303
public static String percentDecode ( String source ) throws AuthException { try { return URLDecoder . decode ( source , "UTF-8" ) ; } catch ( java . io . UnsupportedEncodingException ex ) { throw new AuthException ( "cannot decode value '" + source + "'" , ex ) ; } }
Returns a decoded string .
5,304
public static < T > T wrapTempFileList ( T original , com . aoindustries . io . TempFileList tempFileList , Wrapper < T > wrapper ) { if ( tempFileList != null ) { return wrapper . call ( original , tempFileList ) ; } else { synchronized ( tempFileWarningLock ) { if ( ! tempFileWarned ) { if ( logger . isLoggable ( Lev...
If the TempFileContext is enabled wraps the original object . When the context is inactive the original object is returned unaltered . This is logged as a warning the first time not wrapped .
5,305
public List < Method > listMethods ( final Class < ? > classObj , final String methodName ) { Method [ ] methods = classObj . getMethods ( ) ; List < Method > methodSignatures = new ArrayList < Method > ( ) ; for ( int ii = 0 ; ii < methods . length ; ++ ii ) { if ( methods [ ii ] . getName ( ) . equals ( methodName ) ...
Given an object and a method name list the methods that match the method name on the class ..
5,306
private Map < Integer , Double > predict ( final double [ ] x ) { Map < Integer , Double > result = new HashMap < > ( ) ; for ( int i = 0 ; i < model . weights . length ; i ++ ) { double y = VectorUtils . dotProduct ( x , model . weights [ i ] ) ; y += model . bias [ i ] ; result . put ( i , y ) ; } return result ; }
Key is LabelIndex .
5,307
public void onlineTrain ( final double [ ] x , final int labelIndex ) { Map < Integer , Double > result = predict ( x ) ; Map . Entry < Integer , Double > maxResult = result . entrySet ( ) . stream ( ) . max ( ( e1 , e2 ) -> e1 . getValue ( ) . compareTo ( e2 . getValue ( ) ) ) . orElse ( null ) ; if ( maxResult . getK...
public use for doing one training sample .
5,308
public Map < String , Double > predict ( Tuple predict ) { Map < Integer , Double > indexResult = predict ( predict . vector . getVector ( ) ) ; return indexResult . entrySet ( ) . stream ( ) . map ( e -> new ImmutablePair < > ( model . labelIndexer . getLabel ( e . getKey ( ) ) , VectorUtils . sigmoid . apply ( e . ge...
Do a prediction .
5,309
private boolean isTrimEnabled ( ) { String contentType = response . getContentType ( ) ; if ( contentType != isTrimEnabledCacheContentType ) { isTrimEnabledCacheResult = contentType == null || contentType . equals ( "application/xhtml+xml" ) || contentType . startsWith ( "application/xhtml+xml;" ) || contentType . equa...
Determines if trimming is enabled based on the output content type .
5,310
private boolean processChar ( char c ) { if ( inTextArea ) { if ( c == TrimFilterWriter . textarea_close [ readCharMatchCount ] || c == TrimFilterWriter . TEXTAREA_CLOSE [ readCharMatchCount ] ) { readCharMatchCount ++ ; if ( readCharMatchCount >= TrimFilterWriter . textarea_close . length ) { inTextArea = false ; read...
Processes one character and returns true if the character should be outputted .
5,311
public int set ( final int flags ) { for ( ; ; ) { int current = _flags . get ( ) ; int newValue = current | flags ; if ( _flags . compareAndSet ( current , newValue ) ) { return current ; } } }
Atomically add the given flags to the current set
5,312
public int unset ( final int flags ) { for ( ; ; ) { int current = _flags . get ( ) ; int newValue = current & ~ flags ; if ( _flags . compareAndSet ( current , newValue ) ) { return current ; } } }
Atomically remove the given flags from the current set
5,313
public int change ( final int add , final int remove ) { for ( ; ; ) { int current = _flags . get ( ) ; int newValue = ( current | add ) & ~ remove ; if ( _flags . compareAndSet ( current , newValue ) ) { return current ; } } }
Atomically add and remove the given flags from the current set
5,314
public static < E > String message ( Response < E > response ) { return Optional . ofNullable ( response ) . map ( Response :: getMessage ) . orElse ( StringUtils . EMPTY ) ; }
get response message
5,315
public static DTree convertTreeBankToCoNLLX ( final String constituentTree ) { Tree tree = Tree . valueOf ( constituentTree ) ; SemanticHeadFinder headFinder = new SemanticHeadFinder ( false ) ; Collection < TypedDependency > dependencies = new EnglishGrammaticalStructure ( tree , string -> true , headFinder ) . typedD...
Parser for tag Lemma
5,316
private String addLocale ( Locale locale , String url , String encodedParamName , String encoding ) { int poundPos = url . lastIndexOf ( '#' ) ; String beforeAnchor ; String anchor ; if ( poundPos == - 1 ) { beforeAnchor = url ; anchor = null ; } else { anchor = url . substring ( poundPos ) ; beforeAnchor = url . subst...
Adds the current locale as a parameter to the URL .
5,317
public static Map < String , Locale > getEnabledLocales ( ServletRequest request ) { @ SuppressWarnings ( "unchecked" ) Map < String , Locale > enabledLocales = ( Map < String , Locale > ) request . getAttribute ( ENABLED_LOCALES_REQUEST_ATTRIBUTE_KEY ) ; if ( enabledLocales == null ) throw new IllegalStateException ( ...
Gets the set of enabled locales for the provided request . This must be called from a request that has already been filtered through LocaleFilter . When container s default locale is used will return an empty map .
5,318
protected boolean isLocalizedPath ( String url ) { int questionPos = url . lastIndexOf ( '?' ) ; String lowerPath = ( questionPos == - 1 ? url : url . substring ( 0 , questionPos ) ) . toLowerCase ( Locale . ROOT ) ; return ! lowerPath . endsWith ( ".bmp" ) && ! lowerPath . endsWith ( ".css" ) && ! lowerPath . endsWith...
Checks if the locale parameter should be added to the given URL .
5,319
protected String toLocaleString ( Locale locale ) { String language = locale . getLanguage ( ) ; if ( language . isEmpty ( ) ) return "" ; String country = locale . getCountry ( ) ; if ( country . isEmpty ( ) ) return language ; String variant = locale . getVariant ( ) ; if ( variant . isEmpty ( ) ) { return language +...
Gets a string representation of the given locale . This default implementation only supports language country and variant . Country will only be added when language present . Variant will only be added when both language and country are present .
5,320
public void loadModel ( InputStream modelIs ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; try { IOUtils . copy ( modelIs , baos ) ; } catch ( IOException e ) { LOG . error ( "Load model err." , e ) ; } InputStream isForSVMLoad = new ByteArrayInputStream ( baos . toByteArray ( ) ) ; try ( ZipInputStre...
We load twice because svm . svm_load_model will close the stream after load . so the next guy will have Steam closed exception .
5,321
static String getJavaScriptUnicodeEscapeString ( char ch ) { int chInt = ( int ) ch ; if ( chInt >= ENCODE_RANGE_1_START && chInt < ENCODE_RANGE_1_END ) { return javaScriptUnicodeEscapeStrings1 [ chInt - ENCODE_RANGE_1_START ] ; } if ( chInt >= ENCODE_RANGE_2_START && chInt < ENCODE_RANGE_2_END ) { return javaScriptUni...
Gets the unicode escape for a JavaScript character or null if may be passed - through without escape .
5,322
public Map < String , Double > predict ( Tuple predict ) { Map < Integer , Double > labelProb = new HashMap < > ( ) ; for ( Integer labelIndex : model . labelIndexer . getIndexSet ( ) ) { double likelihood = 1.0D ; for ( int i = 0 ; i < predict . vector . getVector ( ) . length ; i ++ ) { double fi = predict . vector ....
Integer is label s Index from labelIndexer
5,323
public static void splitData ( final String originalTrainingDataFile ) { List < Tuple > trainingData = NaiveBayesClassifier . readTrainingData ( originalTrainingDataFile , "\\s" ) ; List < Tuple > wrongData = new ArrayList < > ( ) ; int lastTrainingDataSize ; int iterCount = 0 ; do { System . out . println ( "Iteration...
Split the data between trainable and wrong .
5,324
public void addFilePart ( final String fieldName , final InputStream stream , final String contentType ) throws IOException { addFilePart ( fieldName , stream , null , contentType ) ; }
Adds a upload file section to the request by stream
5,325
public void addFilePart ( final String fieldName , final URL urlToUploadFile ) throws IOException { addFilePart ( fieldName , urlToUploadFile . openStream ( ) , null , URLConnection . guessContentTypeFromName ( urlToUploadFile . toString ( ) ) ) ; }
Adds a upload file section to the request by url stream
5,326
public void addHeaderField ( final String name , final String value ) { writer . append ( name + ": " + value ) . append ( LINE_FEED ) ; writer . flush ( ) ; }
Adds a header field to the request .
5,327
public HttpResponse finish ( ) throws IOException { writer . append ( "--" + boundary + "--" ) . append ( LINE_FEED ) ; writer . flush ( ) ; try { return doFinish ( ) ; } finally { writer . close ( ) ; } }
Completes the request and receives response from the server .
5,328
public double update ( final double units ) { final double speed ; lock . lock ( ) ; try { final long currentTime = System . nanoTime ( ) ; final long timeDifference = ( currentTime - lastUpdateTime ) / C1 ; if ( timeDifference >= averagingPeriod ) { speed = units / averagingPeriod ; cachedSpeed = speed ; lastUpdateTim...
Updates speed value .
5,329
public static < T > Optional < T > toBean ( String json , Class < T > clazz ) { if ( StringUtils . isBlank ( json ) ) { log . warn ( "json is blank. " ) ; return Optional . empty ( ) ; } try { OBJECT_MAPPER . configure ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES , false ) ; return Optional . of ( OBJECT_MAPPE...
json to object
5,330
public static < T > String toJson ( T t ) { if ( Objects . isNull ( t ) ) { log . warn ( "t is blank. " ) ; return "" ; } try { return OBJECT_MAPPER . writeValueAsString ( t ) ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; return "" ; } }
object to json
5,331
@ RequestMapping ( produces = MediaType . APPLICATION_JSON_VALUE , value = "/parse" , method = RequestMethod . GET ) public String parse ( @ RequestParam ( "sentence" ) String sentence , HttpServletRequest request ) { if ( sentence == null || sentence . trim ( ) . isEmpty ( ) ) { return StringUtils . EMPTY ; } sentence...
Parse sentence .
5,332
public static < T > T resolveValue ( ValueExpression expression , Class < T > type , ELContext elContext ) { if ( expression == null ) { return null ; } else { return type . cast ( expression . getValue ( elContext ) ) ; } }
Evaluates an expression then casts to the provided type .
5,333
public static < T > T resolveValue ( Object value , Class < T > type , ELContext elContext ) { if ( value == null ) { return null ; } else if ( value instanceof ValueExpression ) { return resolveValue ( ( ValueExpression ) value , type , elContext ) ; } else { return type . cast ( value ) ; } }
Casts or evaluates an expression then casts to the provided type .
5,334
public static MediaValidator getMediaValidator ( MediaType contentType , Writer out ) throws MediaException { if ( out instanceof MediaValidator ) { MediaValidator inputValidator = ( MediaValidator ) out ; if ( inputValidator . isValidatingMediaInputType ( contentType ) ) return inputValidator ; } switch ( contentType ...
Gets the media validator for the given type . If the given writer is already validator for the requested type will return the provided writer .
5,335
public boolean getAllowRobots ( ServletContext servletContext , HttpServletRequest request , HttpServletResponse response , Page page ) { return false ; }
No robots for transient Git status .
5,336
public Map < String , Double > convertMapKey ( Map < Integer , Double > probs ) { Map < String , Double > stringKeyProb = new HashMap < > ( ) ; probs . entrySet ( ) . forEach ( e -> stringKeyProb . put ( getLabel ( e . getKey ( ) ) , e . getValue ( ) ) ) ; return stringKeyProb ; }
Convert Index to actual string .
5,337
public static List < ValidationMessage > validateMediaType ( TagData data , List < ValidationMessage > messages ) { Object o = data . getAttribute ( "type" ) ; if ( o != null && o != TagData . REQUEST_TIME_VALUE && ! ( o instanceof MediaType ) ) { String type = Coercion . toString ( o ) ; try { MediaType mediaType = Me...
Checks that a type is a valid MediaType .
5,338
public static List < ValidationMessage > validateScope ( TagData data , List < ValidationMessage > messages ) { Object o = data . getAttribute ( "scope" ) ; if ( o != null && o != TagData . REQUEST_TIME_VALUE ) { String scope = Coercion . toString ( o ) ; try { Scope . getScopeId ( scope ) ; } catch ( JspTagException e...
Checks that a scope is a valid .
5,339
public static double distanceKms ( BigDecimal lat1 , BigDecimal lng1 , BigDecimal lat2 , BigDecimal lng2 ) { return new GeoCoordinate ( lat1 , lng1 ) . distanceTo ( new GeoCoordinate ( lat2 , lng2 ) ) ; }
Equitorial Radius of Earth .
5,340
public static < K , V > MapBuilder < K , V > map ( Map < K , V > instance ) { return new MapBuilder < > ( instance ) ; }
Creates a MapBuilder around the passed instance
5,341
public void run ( final List < Tuple > data ) { List < Tuple > dataCopy = new ArrayList < > ( data ) ; this . labels = data . parallelStream ( ) . map ( x -> x . label ) . collect ( Collectors . toSet ( ) ) ; if ( shuffleData ) { Collections . shuffle ( dataCopy ) ; } int chunkSize = data . size ( ) / nfold ; int remin...
Cross validation .
5,342
private void eval ( List < Tuple > training , List < Tuple > testing , int nfold ) { classifier . train ( training ) ; for ( Tuple tuple : testing ) { String actual = classifier . predict ( tuple ) . entrySet ( ) . stream ( ) . max ( ( e1 , e2 ) -> e1 . getValue ( ) . compareTo ( e2 . getValue ( ) ) ) . map ( Map . Ent...
This is for one fold .
5,343
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 ) ) { if ( pos < len ) { char ch2 = s . charAt ( pos ++ ) ; if ( Character . isLowSurr...
Filters invalid XML characters .
5,344
protected void doTag ( Writer out ) throws JspException , IOException { JspFragment body = getJspBody ( ) ; if ( body != null ) { body . invoke ( ( out instanceof JspWriter ) ? null : out ) ; } }
Once the out JspWriter has been replaced to output the proper content type this version of invoke is called .
5,345
private static BinRelation extractPolar ( DTree tree ) { DNode rootVerb = tree . getRoots ( ) . get ( 0 ) ; BinRelation binRelation = new BinRelation ( ) ; return binRelation ; }
POLAR doesnt have wildcard .
5,346
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+" ) ; float [ ] values = RealValueFileEventStrea...
away pdiff = 9 . 6875 ptwins = 0 . 5 lose
5,347
public static List < CoreLabel > stanfordTokenize ( String str ) { TokenizerFactory < ? extends HasWord > tf = PTBTokenizer . coreLabelFactory ( ) ; Tokenizer < ? extends HasWord > originalWordTokenizer = tf . getTokenizer ( new StringReader ( str ) , "ptb3Escaping=false" ) ; Tokenizer < ? extends HasWord > tokenizer =...
1 . Tokenize
5,348
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 > posLis...
2 . POS Tagger
5,349
public static void tagLemma ( List < CoreLabel > tokens ) { 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 ( ...
3 . Lemma Tagger
5,350
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 { ner...
NER not thread safe ...
5,351
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 ; }
Looks for each instance of key in all of the overrides in order . Does not look for a non - overridden version .
5,352
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 ; }
Searches for a property of key using all overrides
5,353
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 ( prefix...
Searches for a property of key with all overrides using the specified prefixes
5,354
public LocalContainerEntityManagerFactoryBean entityManagerFactory ( ) { HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter ( ) ; jpaVendorAdapter . setDatabase ( Database . H2 ) ; jpaVendorAdapter . setGenerateDdl ( true ) ; LocalContainerEntityManagerFactoryBean entityManagerFactory = new Loca...
Entity manager factory .
5,355
public ServletRegistrationBean h2servletRegistration ( ) { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean ( new WebServlet ( ) ) ; servletRegistrationBean . addUrlMappings ( "/h2/*" ) ; return servletRegistrationBean ; }
H2 console .
5,356
public static void setAttribute ( PageContext pageContext , String scope , String name , Object value ) throws JspTagException { pageContext . setAttribute ( name , value , Scope . getScopeId ( scope ) ) ; }
Sets an attribute in the provided textual scope .
5,357
public static Object findObject ( PageContext pageContext , String scope , String name , String property , boolean beanRequired , boolean valueRequired ) throws JspTagException { try { if ( name == null ) throw new AttributeRequiredException ( "name" ) ; Object bean ; if ( scope == null ) bean = pageContext . findAttri...
Gets the object given its scope name and optional property .
5,358
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 ( APPLI...
Gets the PageContext scope value for the textual scope name .
5,359
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 < Stri...
Converts a resource bundle to a map after prepending suffix + . to each property
5,360
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 . e...
Return the predict to every other train vector s distance .
5,361
public void purge ( ) { WeakElement < ? > element ; while ( ( element = ( WeakElement < ? > ) _queue . poll ( ) ) != null ) { _set . remove ( element ) ; } }
Removes all garbage - collected elements from this set
5,362
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 ( ) ; } c...
Train CRF Suite with annotated item sequences .
5,363
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 ( r...
Returns a signature base string . The signature base string is a consistent reproducible concatenation of several of the HTTP request elements into a single string .
5,364
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 . counti...
Regardless of the label just consider isPosExample and !isPosExample
5,365
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 > smallLi...
Shuffle the data and split by proportion
5,366
public void calculateLabelPrior ( ) { double prior = 1D / model . labelIndexer . getLabelSize ( ) ; model . labelIndexer . getIndexSet ( ) . forEach ( labelIndex -> model . labelPrior . put ( labelIndex , prior ) ) ; }
Assume labels have equal probability . Not depends on the training data size .
5,367
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 ( ) ) {...
Writes a value with markup enabled using the provided encoder .
5,368
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 :: ...
Parser here is just for tokenize .
5,369
public static int ipv4ToInt ( final Inet4Address addr ) { int value = 0 ; for ( byte chunk : addr . getAddress ( ) ) { value <<= 8 ; value |= chunk & 0xff ; } return value ; }
Turns an Inet4Address into a 32 - bit integer representation
5,370
public static < E > List < E > empty ( List < E > list ) { return Optional . ofNullable ( list ) . orElse ( newArrayList ( ) ) ; }
null to empty list
5,371
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...
clean null element
5,372
public ChainWriter encodeJavaScriptStringInXmlAttribute ( Object value ) throws IOException { if ( value instanceof Writable && ! ( ( Writable ) value ) . isFastToString ( ) ) { textInJavaScriptEncoder . writePrefixTo ( javaScriptInXhtmlAttributeWriter ) ; Coercion . write ( value , textInJavaScriptEncoder , javaScript...
Encodes a javascript string for use in an XML attribute context . Quotes are added around the string . Also if the string is translated comments will be added giving the translation lookup id to aid in translation of server - translated values in JavaScript .
5,373
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 ....
Prints a value that may be placed in a URL .
5,374
public static void writeHtmlImagePreloadJavaScript ( String url , Appendable out ) throws IOException { out . append ( "<script type='text/javascript'>\n" + " var img=new Image();\n" + " img.src=\"" ) ; StringBuilder javascript = new StringBuilder ( url . length ( ) ) ; encodeTextInJavaScript ( url , javascript ) ; e...
Prints a JavaScript script that will preload the image at the provided URL .
5,375
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 ( ...
Splits the CharSequence passed in parameter .
5,376
public Splitter trim ( char c ) { Matcher matcher = new CharMatcher ( c ) ; return new Splitter ( pairSeparator , keyValueSeparator , matcher , matcher ) ; }
Returns a splitter that removes all leading or trailing characters matching the given character from each returned key and value .
5,377
public Splitter trim ( char [ ] chars ) { Matcher matcher = new CharsMatcher ( chars ) ; return new Splitter ( pairSeparator , keyValueSeparator , matcher , matcher ) ; }
Returns a splitter that removes all leading or trailing characters matching the given characters from each returned key and value .
5,378
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 ; } }
Ensure closing without opening should notbe an issue .
5,379
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 ] . getParamet...
modeled on implementation in Zhang Le s maxent kit
5,380
final public void writeSuffixTo ( Appendable out ) throws IOException { writeSuffix ( buffer , out ) ; buffer . setLength ( 0 ) ; }
Writes the suffix and clears the buffer for reuse .
5,381
public static < T > T nullIfEmpty ( T value ) throws IOException { return isEmpty ( value ) ? null : value ; }
Returns the provided value or null if the value is empty .
5,382
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 ( ) ; }
Takes the first letter and capitalizes it .
5,383
public static void appendToBuffer ( final StringBuffer buffer , final String string , final String delimiter ) { if ( string == null ) { return ; } if ( buffer . length ( ) == 0 || delimiter == null ) { buffer . append ( string ) ; } else { buffer . append ( delimiter ) . append ( string ) ; } }
Appends a string to a buffer prepending with a delimiter string . For instance this may be used to create a string of comma - delimited values . This does not ignore empty strings .
5,384
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 ; }
Similar to SQL coalesce returns the first non - null argument
5,385
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 ; } } ...
Similar to SQL coalesce returns the first non - EMPTY argument
5,386
public BeanInfo [ ] getAdditionalBeanInfo ( ) { try { return new BeanInfo [ ] { Introspector . getBeanInfo ( InputTag . class . getSuperclass ( ) ) } ; } catch ( IntrospectionException err ) { throw new AssertionError ( err ) ; } }
Include base class .
5,387
public static String fileNameFromString ( final String text ) { String value = text . replace ( ' ' , '_' ) ; if ( value . length ( ) < 48 ) { return value ; } return value . substring ( 0 , 47 ) ; }
This method takes a string and converts it into a filename by replacing any spaces with underscores and then also truncating it if it is over a certain length . At the time of the writing of this comment that was 48 characters which was chosen by pulling a number out of my brain .
5,388
public static int executeToFile ( final String [ ] command , final File file ) throws IOException , InterruptedException { return executeToFile ( command , file , System . err ) ; }
Executes the given command redirecting stdout to the given file and stderr to actual stderr
5,389
public static int executeToFile ( final String [ ] command , final File file , final OutputStream stderr ) throws IOException , InterruptedException { return executeToStreams ( command , new FileOutputStream ( file ) , stderr ) ; }
Executes the given command redirecting stdout to the given file and stderr to the given stream
5,390
public static void makeSecurityCheck ( final File file , final File base ) { if ( ! file . getAbsolutePath ( ) . startsWith ( base . getAbsolutePath ( ) ) ) { throw new IllegalArgumentException ( "Illegal file path [" + file + "]" ) ; } }
Check to make sure the user has not put .. anywhere in the path to allow overwriting of system files . Throws IllegalArgumentException if it fails the check .
5,391
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...
Copies all values from the provided link .
5,392
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 )...
Updates the set of predicated and counter with the specified event contexts and cutoff .
5,393
private GrammaticalStructure tagDependencies ( List < ? extends HasWord > taggedWords ) { GrammaticalStructure gs = nndepParser . predict ( taggedWords ) ; return gs ; }
4 . Dependency Label
5,394
public String [ ] getFeatNames ( ) { String [ ] namesArray = new String [ nameIndexMap . size ( ) ] ; for ( Map . Entry < String , Integer > entry : nameIndexMap . entrySet ( ) ) { namesArray [ entry . getValue ( ) ] = entry . getKey ( ) ; } return namesArray ; }
This method should only be used for print or debug purpose .
5,395
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 )...
This is for the backward compatibility
5,396
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...
This is for coref using .
5,397
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 ; }
Checks to see if this exception or any of its causes is an instance of the given throwable class
5,398
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 ) ; }
Checks to see if an exception or any of its causes are of a certain type . Returns the first type in the chain if it exists or null if no causes are of this type .
5,399
public static String getMessage ( final Throwable ex ) { String message = ex . getMessage ( ) ; if ( ex instanceof SQLException ) { String sqlMessage = getSqlExceptionMessage ( ( SQLException ) ex ) ; if ( ! StringUtils . isBlank ( sqlMessage ) ) { if ( ! StringUtils . isBlank ( message ) ) { message += "\n" + sqlMessa...
Static method to recursively get the message text from the entire stack . Messages are concatenated with the linefeed character . This allows for a more informational message to be displayed to the user .