idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
8,900
private ProtoNetwork stage1 ( final File [ ] networks ) { beginStage ( PHASE2_STAGE1_HDR , "1" , NUM_PHASES ) ; final int netct = networks . length ; final StringBuilder bldr = new StringBuilder ( ) ; bldr . append ( "Merging " ) ; bldr . append ( netct ) ; bldr . append ( " network" ) ; if ( netct > 1 ) { bldr . append ( "s" ) ; } stageOutput ( bldr . toString ( ) ) ; long t1 = currentTimeMillis ( ) ; Collection < ProtoNetworkDescriptor > nds = sizedArrayList ( netct ) ; for ( final File network : networks ) { final String root = network . getAbsolutePath ( ) ; final String netPath = asPath ( root , PROTO_NETWORK_FILENAME ) ; final File networkBin = new File ( netPath ) ; nds . add ( new BinaryProtoNetworkDescriptor ( networkBin ) ) ; } ProtoNetwork ret = p2 . stage1Merger ( nds ) ; new File ( artifactPath . getAbsolutePath ( ) + "/merged" ) . mkdirs ( ) ; p2 . stage4WriteEquivalentProtoNetwork ( ret , artifactPath . getAbsolutePath ( ) + "/merged" ) ; if ( withDebug ( ) ) { try { TextProtoNetworkExternalizer textExternalizer = new TextProtoNetworkExternalizer ( ) ; textExternalizer . writeProtoNetwork ( ret , artifactPath . getAbsolutePath ( ) + "/merged" ) ; } catch ( ProtoNetworkError e ) { error ( "Could not write out equivalenced proto network." ) ; } } long t2 = currentTimeMillis ( ) ; bldr . setLength ( 0 ) ; markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return ret ; }
Stage one merger of networks returning the merged proto - network .
8,901
private Set < EquivalenceDataIndex > stage2 ( ) { beginStage ( PHASE2_STAGE2_HDR , "2" , NUM_PHASES ) ; Set < EquivalenceDataIndex > ret = new HashSet < EquivalenceDataIndex > ( ) ; final StringBuilder bldr = new StringBuilder ( ) ; bldr . append ( "Loading namespace equivalences from resource index" ) ; stageOutput ( bldr . toString ( ) ) ; long t1 = currentTimeMillis ( ) ; try { ret . addAll ( p2 . stage2LoadNamespaceEquivalences ( ) ) ; } catch ( EquivalenceMapResolutionFailure e ) { warning ( e . getUserFacingMessage ( ) ) ; } for ( final EquivalenceDataIndex edi : ret ) { final String nsLocation = edi . getNamespaceResourceLocation ( ) ; bldr . setLength ( 0 ) ; bldr . append ( "Equivalence for " ) ; bldr . append ( nsLocation ) ; stageOutput ( bldr . toString ( ) ) ; } long t2 = currentTimeMillis ( ) ; bldr . setLength ( 0 ) ; markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return ret ; }
Stage two equivalence loading returning a set of data indices .
8,902
private void stage3Term ( final ProtoNetwork network , int pct ) { stageOutput ( "Equivalencing terms" ) ; int tct = p2 . stage3EquivalenceTerms ( network ) ; stageOutput ( "(" + tct + " equivalences)" ) ; }
Stage three term equivalencing .
8,903
private void stage3Statement ( final ProtoNetwork network , int pct ) { stageOutput ( "Equivalencing statements" ) ; int sct = p2 . stage3EquivalenceStatements ( network ) ; stageOutput ( "(" + sct + " equivalences)" ) ; }
Stage three statement equivalencing .
8,904
private ProtoNetworkDescriptor stage4 ( final ProtoNetwork eqNetwork ) { beginStage ( PHASE2_STAGE4_HDR , "4" , NUM_PHASES ) ; final StringBuilder bldr = new StringBuilder ( ) ; bldr . append ( "Saving network" ) ; stageOutput ( bldr . toString ( ) ) ; long t1 = currentTimeMillis ( ) ; ProtoNetworkDescriptor ret = p2 . stage4WriteEquivalentProtoNetwork ( eqNetwork , artifactPath . getAbsolutePath ( ) ) ; if ( withDebug ( ) ) { try { TextProtoNetworkExternalizer textExternalizer = new TextProtoNetworkExternalizer ( ) ; textExternalizer . writeProtoNetwork ( eqNetwork , artifactPath . getAbsolutePath ( ) ) ; } catch ( ProtoNetworkError e ) { error ( "Could not write out equivalenced proto network." ) ; } } bldr . setLength ( 0 ) ; long t2 = currentTimeMillis ( ) ; markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return ret ; }
Stage four saving
8,905
public String getApplicationDescription ( ) { final StringBuilder bldr = new StringBuilder ( ) ; bldr . append ( "Merges proto-networks into a composite network and " ) ; bldr . append ( "equivalences term references across namespaces." ) ; return bldr . toString ( ) ; }
Returns the application s description .
8,906
public static WebElement loopFindOrRefresh ( int maxRefreshes , By locator , WebDriver driver ) { for ( int i = 0 ; i < maxRefreshes ; i ++ ) { WebElement element ; try { element = driver . findElement ( locator ) ; return element ; } catch ( NoSuchElementException e ) { logger . info ( "after implicit wait, element " + locator + " is still not present: refreshing page and trying again" ) ; Navigation . refreshPage ( driver ) ; } } return null ; }
Implicitly wait for an element . Then if the element cannot be found refresh the page . Try finding the element again reiterating for maxRefreshes times or until the element is found . Finally return the element .
8,907
public static void hitKeys ( WebDriver driver , CharSequence keys ) { new Actions ( driver ) . sendKeys ( keys ) . perform ( ) ; }
Typical use is to simulate hitting ESCAPE or ENTER .
8,908
public List < Parameter > getAllParameters ( ) { List < Parameter > ret = new ArrayList < Parameter > ( ) ; if ( parameters != null ) ret . addAll ( parameters ) ; if ( terms != null ) { for ( final Term t : terms ) { ret . addAll ( t . getAllParameters ( ) ) ; } } return ret ; }
Returns a list of all parameters contained by both this term and any nested terms .
8,909
public List < Term > getAllTerms ( ) { List < Term > ret = new ArrayList < Term > ( ) ; if ( terms != null ) { ret . addAll ( terms ) ; for ( final Term term : terms ) { ret . addAll ( term . getAllTerms ( ) ) ; } } return ret ; }
Returns a list of all terms contained by and within this term .
8,910
private void setFunctionArgs ( final List < BELObject > args ) { if ( args != null ) { this . functionArgs = args ; this . terms = new ArrayList < Term > ( ) ; this . parameters = new ArrayList < Parameter > ( ) ; for ( final BELObject arg : functionArgs ) { if ( arg instanceof Term ) { terms . add ( ( Term ) arg ) ; } else if ( arg instanceof Parameter ) { parameters . add ( ( Parameter ) arg ) ; } else { String err = arg . getClass ( ) . getName ( ) ; err = err . concat ( " is not a valid function argument" ) ; throw new UnsupportedOperationException ( err ) ; } } } else { this . functionArgs = null ; this . terms = null ; this . parameters = null ; } }
Sets the function arguments terms and parameters . A null argument will result in null function arguments terms and parameters .
8,911
public URI getAuthorizeBrowserUrl ( ) { OAuth2AppInfo appInfo = sessionManager . getAppInfo ( ) ; state = PcsUtils . randomString ( 30 ) ; URI uri = new URIBuilder ( URI . create ( sessionManager . getAuthorizeUrl ( ) ) ) . addParameter ( OAuth2 . CLIENT_ID , appInfo . getAppId ( ) ) . addParameter ( OAuth2 . STATE , state ) . addParameter ( OAuth2 . RESPONSE_TYPE , "code" ) . addParameter ( OAuth2 . REDIRECT_URI , appInfo . getRedirectUrl ( ) ) . addParameter ( OAuth2 . SCOPE , sessionManager . getScopeForAuthorization ( ) ) . build ( ) ; return uri ; }
Builds the authorize URI that must be loaded in a browser to allow the application to use the API
8,912
public void getUserCredentials ( String codeOrUrl ) throws IOException { if ( state == null ) { throw new IllegalStateException ( "No anti CSRF state defined" ) ; } String code ; if ( codeOrUrl . startsWith ( "http://" ) || codeOrUrl . startsWith ( "https://" ) ) { String url = codeOrUrl ; LOGGER . debug ( "redirect URL: {}" , url ) ; URI uri = URI . create ( url ) ; String error = URIUtil . getQueryParameter ( uri , "error" ) ; String errorDescription = URIUtil . getQueryParameter ( uri , "error_description" ) ; if ( error != null ) { String msg = "User authorization failed : " + error ; if ( errorDescription != null ) { msg += " (" + errorDescription + ")" ; } throw new CStorageException ( msg ) ; } String stateToTest = URIUtil . getQueryParameter ( uri , "state" ) ; if ( ! state . equals ( stateToTest ) ) { throw new CStorageException ( "State received (" + stateToTest + ") is not state expected (" + state + ")" ) ; } code = URIUtil . getQueryParameter ( uri , "code" ) ; if ( code == null ) { throw new CStorageException ( "Can't find code in redirected URL: " + url ) ; } } else { code = codeOrUrl ; } UserCredentials userCredentials = sessionManager . fetchUserCredentials ( code ) ; String userId = storageProvider . getUserId ( ) ; LOGGER . debug ( "User identifier retrieved: {}" , userId ) ; userCredentials . setUserId ( userId ) ; sessionManager . getUserCredentialsRepository ( ) . save ( userCredentials ) ; }
Gets users Credentials
8,913
public static boolean isNetworkConnected ( Context context ) { ConnectivityManager manager = ( ConnectivityManager ) context . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; NetworkInfo info = manager . getActiveNetworkInfo ( ) ; return info != null && info . isConnected ( ) ; }
Checks if the network is connected or not .
8,914
public static boolean isNetworkAvailable ( Context context ) { ConnectivityManager manager = ( ConnectivityManager ) context . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; NetworkInfo info = manager . getActiveNetworkInfo ( ) ; return info != null && info . isAvailable ( ) ; }
Checks if the network is available or not . This is not guarantee that the network is connected and can communicate through the network .
8,915
private void initJedisPool ( Properties props ) { JedisPoolConfig config = new JedisPoolConfig ( ) ; config . setTestOnBorrow ( true ) ; Integer maxIdle = Integer . parseInt ( props . getProperty ( "session.redis.pool.max.idle" , "2" ) ) ; config . setMaxIdle ( maxIdle ) ; Integer maxTotal = Integer . parseInt ( props . getProperty ( "session.redis.pool.max.total" , "5" ) ) ; config . setMaxTotal ( maxTotal ) ; final String mode = props . getProperty ( "session.redis.mode" ) ; if ( Objects . equal ( mode , SENTINEL_MODE ) ) { this . executor = new RedisExecutor ( config , true , props ) ; } else { this . executor = new RedisExecutor ( config , false , props ) ; } }
init jedis pool with properties
8,916
public Boolean persist ( final String id , final Map < String , Object > snapshot , final int maxInactiveInterval ) { final String sid = sessionPrefix + ":" + id ; try { this . executor . execute ( new RedisCallback < Void > ( ) { public Void execute ( Jedis jedis ) { if ( snapshot . isEmpty ( ) ) { jedis . del ( sid ) ; } else { jedis . setex ( sid , maxInactiveInterval , serializer . serialize ( snapshot ) ) ; } return null ; } } ) ; return Boolean . TRUE ; } catch ( Exception e ) { log . error ( "failed to persist session(id={}, snapshot={}), cause:{}" , sid , snapshot , Throwables . getStackTraceAsString ( e ) ) ; return Boolean . FALSE ; } }
persist session to session store
8,917
public Map < String , Object > loadById ( String id ) { final String sid = sessionPrefix + ":" + id ; try { return this . executor . execute ( new RedisCallback < Map < String , Object > > ( ) { public Map < String , Object > execute ( Jedis jedis ) { String session = jedis . get ( sid ) ; if ( ! Strings . isNullOrEmpty ( session ) ) { return serializer . deserialize ( session ) ; } return Collections . emptyMap ( ) ; } } ) ; } catch ( Exception e ) { log . error ( "failed to load session(key={}), cause:{}" , sid , Throwables . getStackTraceAsString ( e ) ) ; throw new SessionException ( "load session failed" , e ) ; } }
load session by id
8,918
public void deleteById ( String id ) { final String sid = sessionPrefix + ":" + id ; try { this . executor . execute ( new RedisCallback < Void > ( ) { public Void execute ( Jedis jedis ) { jedis . del ( sid ) ; return null ; } } ) ; } catch ( Exception e ) { log . error ( "failed to delete session(key={}) in redis,cause:{}" , sid , Throwables . getStackTraceAsString ( e ) ) ; } }
delete session physically
8,919
public Bbox getWidgetViewBbox ( ) { return new Bbox ( textBox . getAbsoluteLeft ( ) , textBox . getAbsoluteTop ( ) , textBox . getOffsetWidth ( ) , textBox . getOffsetHeight ( ) ) ; }
Return the bbox of the textbox element . These bounds will be used to position the alternative locations view .
8,920
public static List < ? extends Element > getEnclosedElementsDeclarationOrder ( TypeElement type ) { List < ? extends Element > result = null ; try { Object binding = field ( type , "_binding" ) ; Class < ? > sourceTypeBinding = null ; { Class < ? > c = binding . getClass ( ) ; do { if ( c . getCanonicalName ( ) . equals ( "org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding" ) ) { sourceTypeBinding = c ; break ; } } while ( ( c = c . getSuperclass ( ) ) != null ) ; } final List < Object > declarationOrder ; if ( sourceTypeBinding != null ) { declarationOrder = findSourceOrder ( binding ) ; List < Element > enclosedElements = new ArrayList < Element > ( type . getEnclosedElements ( ) ) ; Collections . sort ( enclosedElements , new Comparator < Element > ( ) { public int compare ( Element o1 , Element o2 ) { try { Object o1Binding = field ( o1 , "_binding" ) ; Object o2Binding = field ( o2 , "_binding" ) ; int i1 = declarationOrder . indexOf ( o1Binding ) ; int i2 = declarationOrder . indexOf ( o2Binding ) ; return i1 - i2 ; } catch ( Exception e ) { return 0 ; } } } ) ; result = enclosedElements ; } } catch ( Exception e ) { } return ( result != null ) ? result : type . getEnclosedElements ( ) ; }
If given TypeElement is SourceTypeBinding the order of results are corrected .
8,921
public String getProperty ( String key ) { for ( PropertyLoader loader : loaders ) { String value = loader . getProperty ( key ) ; if ( value != null ) return value ; } return null ; }
Loop over the components and return the first not null value found .
8,922
public JsonNode evaluate ( JsonNode node ) { if ( innerExpression == null ) { return getValue ( node , property ) ; } else { return getValue ( innerExpression . evaluate ( node ) , property ) ; } }
Evaluates the expression on passed JSONNode
8,923
protected JsonNode getValue ( JsonNode node , String property ) { if ( node == null ) { throw new MissingNodeException ( property + " is missing" ) ; } if ( property == null ) { return node ; } JsonNode value = node . at ( formatPropertyName ( property ) ) ; if ( value . isMissingNode ( ) ) { throw new MissingNodeException ( property + " is missing" ) ; } return value ; }
Fetches the value for a property from the passed JsonNode . Throws MissingNodeException if the property doesn t exist
8,924
private static String mapGermanCoNLL09TagSetToNAF ( final String postag ) { if ( postag . startsWith ( "ADV" ) ) { return "A" ; } else if ( postag . startsWith ( "KO" ) ) { return "C" ; } else if ( postag . equalsIgnoreCase ( "ART" ) ) { return "D" ; } else if ( postag . startsWith ( "ADJ" ) ) { return "G" ; } else if ( postag . equalsIgnoreCase ( "NN" ) ) { return "N" ; } else if ( postag . startsWith ( "NE" ) ) { return "R" ; } else if ( postag . startsWith ( "AP" ) ) { return "P" ; } else if ( postag . startsWith ( "PD" ) || postag . startsWith ( "PI" ) || postag . startsWith ( "PP" ) || postag . startsWith ( "PR" ) || postag . startsWith ( "PW" ) || postag . startsWith ( "PA" ) ) { return "Q" ; } else if ( postag . startsWith ( "V" ) ) { return "V" ; } else { return "O" ; } }
Mapping between CoNLL 2009 German tagset and NAF tagset . Based on the Stuttgart - Tuebingen tagset .
8,925
private static String mapEnglishPennTagSetToNAF ( final String postag ) { if ( postag . startsWith ( "RB" ) ) { return "A" ; } else if ( postag . equalsIgnoreCase ( "CC" ) ) { return "C" ; } else if ( postag . startsWith ( "D" ) || postag . equalsIgnoreCase ( "PDT" ) ) { return "D" ; } else if ( postag . startsWith ( "J" ) ) { return "G" ; } else if ( postag . equalsIgnoreCase ( "NN" ) || postag . equalsIgnoreCase ( "NNS" ) ) { return "N" ; } else if ( postag . startsWith ( "NNP" ) ) { return "R" ; } else if ( postag . equalsIgnoreCase ( "TO" ) || postag . equalsIgnoreCase ( "IN" ) ) { return "P" ; } else if ( postag . startsWith ( "PRP" ) || postag . startsWith ( "WP" ) ) { return "Q" ; } else if ( postag . startsWith ( "V" ) ) { return "V" ; } else { return "O" ; } }
Mapping between Penn Treebank tagset and NAF tagset .
8,926
private static String mapSpanishAncoraTagSetToNAF ( final String postag ) { if ( postag . equalsIgnoreCase ( "RG" ) || postag . equalsIgnoreCase ( "RN" ) ) { return "A" ; } else if ( postag . equalsIgnoreCase ( "CC" ) || postag . equalsIgnoreCase ( "CS" ) ) { return "C" ; } else if ( postag . startsWith ( "D" ) ) { return "D" ; } else if ( postag . startsWith ( "A" ) ) { return "G" ; } else if ( postag . startsWith ( "NC" ) ) { return "N" ; } else if ( postag . startsWith ( "NP" ) ) { return "R" ; } else if ( postag . startsWith ( "SP" ) ) { return "P" ; } else if ( postag . startsWith ( "P" ) ) { return "Q" ; } else if ( postag . startsWith ( "V" ) ) { return "V" ; } else { return "O" ; } }
Mapping between EAGLES PAROLE Ancora tagset and NAF .
8,927
public void redraw ( ) { shapes . clear ( ) ; if ( container != null ) { container . setTranslation ( 0 , 0 ) ; container . clear ( ) ; try { tentativeMoveLine = new Path ( - 5 , - 5 ) ; tentativeMoveLine . lineTo ( - 5 , - 5 ) ; ShapeStyle style = styleProvider . getEdgeTentativeMoveStyle ( ) ; GeomajasImpl . getInstance ( ) . getGfxUtil ( ) . applyStyle ( tentativeMoveLine , style ) ; container . add ( tentativeMoveLine ) ; draw ( ) ; } catch ( GeometryIndexNotFoundException e ) { } } }
Clear everything and completely redraw the edited geometry .
8,928
public void onGeometryEditStart ( GeometryEditStartEvent event ) { if ( container != null ) { mapPresenter . getContainerManager ( ) . removeVectorContainer ( container ) ; } container = mapPresenter . getContainerManager ( ) . addScreenContainer ( ) ; redraw ( ) ; }
Clean up the previous state create a container to draw in and then draw the geometry .
8,929
public void onGeometryEditStop ( GeometryEditStopEvent event ) { mapPresenter . getContainerManager ( ) . removeVectorContainer ( container ) ; container = null ; shapes . clear ( ) ; }
Clean up all rendering .
8,930
public void onChangeEditingState ( GeometryEditChangeStateEvent event ) { switch ( event . getEditingState ( ) ) { case DRAGGING : mapPresenter . setCursor ( "move" ) ; break ; case IDLE : default : mapPresenter . setCursor ( "default" ) ; redraw ( ) ; } }
Change the cursor while dragging .
8,931
public void onGeometryEditMove ( GeometryEditMoveEvent event ) { Map < GeometryIndex , Boolean > indicesToUpdate = new HashMap < GeometryIndex , Boolean > ( ) ; for ( GeometryIndex index : event . getIndices ( ) ) { if ( ! indicesToUpdate . containsKey ( index ) ) { indicesToUpdate . put ( index , false ) ; if ( ! Geometry . POINT . equals ( editService . getGeometry ( ) . getGeometryType ( ) ) && ! Geometry . MULTI_POINT . equals ( editService . getGeometry ( ) . getGeometryType ( ) ) ) { try { List < GeometryIndex > neighbors ; switch ( editService . getIndexService ( ) . getType ( index ) ) { case TYPE_VERTEX : indicesToUpdate . put ( index , true ) ; neighbors = editService . getIndexService ( ) . getAdjacentEdges ( event . getGeometry ( ) , index ) ; if ( neighbors != null ) { for ( GeometryIndex neighborIndex : neighbors ) { if ( ! indicesToUpdate . containsKey ( neighborIndex ) ) { indicesToUpdate . put ( neighborIndex , false ) ; } } } neighbors = editService . getIndexService ( ) . getAdjacentVertices ( event . getGeometry ( ) , index ) ; if ( neighbors != null ) { for ( GeometryIndex neighborIndex : neighbors ) { if ( ! indicesToUpdate . containsKey ( neighborIndex ) ) { indicesToUpdate . put ( neighborIndex , false ) ; } } } break ; case TYPE_EDGE : neighbors = editService . getIndexService ( ) . getAdjacentVertices ( event . getGeometry ( ) , index ) ; if ( neighbors != null ) { for ( GeometryIndex neighborIndex : neighbors ) { if ( ! indicesToUpdate . containsKey ( neighborIndex ) ) { indicesToUpdate . put ( neighborIndex , false ) ; } } } break ; default : } } catch ( GeometryIndexNotFoundException e ) { throw new IllegalStateException ( e ) ; } } } } if ( styleProvider . getBackgroundStyle ( ) != null && styleProvider . getBackgroundStyle ( ) . getFillOpacity ( ) > 0 ) { if ( event . getGeometry ( ) . getGeometryType ( ) . equals ( Geometry . POLYGON ) ) { update ( null , false ) ; } else if ( event . getGeometry ( ) . getGeometryType ( ) . equals ( Geometry . MULTI_POLYGON ) && event . getGeometry ( ) . getGeometries ( ) != null ) { for ( int i = 0 ; i < event . getGeometry ( ) . getGeometries ( ) . length ; i ++ ) { GeometryIndex index = editService . getIndexService ( ) . create ( GeometryIndexType . TYPE_GEOMETRY , i ) ; indicesToUpdate . put ( index , false ) ; } } } for ( GeometryIndex index : indicesToUpdate . keySet ( ) ) { update ( index , indicesToUpdate . get ( index ) ) ; } }
Figure out what s being moved and update only adjacent objects . This is far more performing than simply redrawing everything .
8,932
public void onTentativeMove ( GeometryEditTentativeMoveEvent event ) { try { Coordinate [ ] vertices = editService . getIndexService ( ) . getSiblingVertices ( editService . getGeometry ( ) , editService . getInsertIndex ( ) ) ; String geometryType = editService . getIndexService ( ) . getGeometryType ( editService . getGeometry ( ) , editService . getInsertIndex ( ) ) ; if ( vertices != null && ( Geometry . LINE_STRING . equals ( geometryType ) || Geometry . LINEAR_RING . equals ( geometryType ) ) ) { Coordinate temp1 = event . getOrigin ( ) ; Coordinate temp2 = event . getCurrentPosition ( ) ; Coordinate c1 = mapPresenter . getViewPort ( ) . getTransformationService ( ) . transform ( temp1 , RenderSpace . WORLD , RenderSpace . SCREEN ) ; Coordinate c2 = mapPresenter . getViewPort ( ) . getTransformationService ( ) . transform ( temp2 , RenderSpace . WORLD , RenderSpace . SCREEN ) ; tentativeMoveLine . setStep ( 0 , new MoveTo ( false , c1 . getX ( ) , c1 . getY ( ) ) ) ; tentativeMoveLine . setStep ( 1 , new LineTo ( false , c2 . getX ( ) , c2 . getY ( ) ) ) ; } else if ( vertices != null && Geometry . LINEAR_RING . equals ( geometryType ) ) { } } catch ( GeometryIndexNotFoundException e ) { throw new IllegalStateException ( e ) ; } }
Renders a line from the last inserted point to the current mouse position indicating what the new situation would look like if a vertex where to be inserted at the mouse location .
8,933
public void onMouseUp ( MouseUpEvent event ) { super . onMouseUp ( event ) ; Coordinate worldLocation = getLocation ( event , RenderSpace . WORLD ) ; for ( FeatureInfoSupported layer : layers ) { GetFeatureInfoFormat f = GetFeatureInfoFormat . fromFormat ( format ) ; if ( f != null ) { switch ( f ) { case GML2 : case GML3 : case JSON : if ( featureCallback == null ) { throw new IllegalStateException ( "No callback has been set on the WmsGetFeatureInfoController" ) ; } layer . getFeatureInfo ( worldLocation , format , featureCallback ) ; break ; case HTML : case TEXT : default : if ( htmlCallback == null ) { throw new IllegalStateException ( "No callback has been set on the WmsGetFeatureInfoController" ) ; } htmlCallback . onSuccess ( layer . getFeatureInfoUrl ( worldLocation , format ) ) ; break ; } } } }
Execute a GetFeatureInfo on mouse up .
8,934
public boolean is ( ComparisonExpression expr ) { try { if ( expr != null ) { return expr . evaluate ( node ) ; } } catch ( MissingNodeException e ) { return false ; } return false ; }
Verifies if the passed expression is true for the JsonNode
8,935
public boolean isExist ( String property ) { try { new ValueExpression ( property ) . evaluate ( node ) ; } catch ( MissingNodeException e ) { return false ; } return true ; }
Checks if property exist in the JsonNode
8,936
public ArrayNode filter ( ComparisonExpression expression ) { ArrayNode result = new ObjectMapper ( ) . createArrayNode ( ) ; if ( node . isArray ( ) ) { Iterator < JsonNode > iterator = node . iterator ( ) ; int validObjectsCount = 0 ; int topCount = 0 ; while ( iterator . hasNext ( ) ) { JsonNode curNode = iterator . next ( ) ; if ( expression == null || ( expression != null && new Query ( curNode ) . is ( expression ) ) ) { validObjectsCount ++ ; if ( this . skip != null && this . skip . intValue ( ) > 0 && this . skip . intValue ( ) >= validObjectsCount ) { continue ; } if ( this . top != null && topCount >= this . top . intValue ( ) ) { break ; } result . add ( curNode ) ; topCount ++ ; } } } else { throw new UnsupportedExprException ( "Filters are only supported on ArrayNode objects" ) ; } return result ; }
Allows filtering values in a ArrayNode as per passed ComparisonExpression
8,937
public ArrayNode filter ( String property , ComparisonExpression expression ) { JsonNode propValueNode = this . value ( property ) ; return Query . q ( propValueNode ) . top ( this . getTop ( ) ) . skip ( this . getSkip ( ) ) . filter ( expression ) ; }
Allows applying filter on a property value which is ArrayNode as per passed ComparisonExpression
8,938
public static void slideUpAndDown ( final Component component , final AjaxRequestTarget target , int slideUpDuration , int slideDownDuration ) { component . add ( new DisplayNoneBehavior ( ) ) ; target . prependJavaScript ( "notify|jQuery('#" + component . getMarkupId ( ) + "').slideUp(" + slideUpDuration + ", notify);" ) ; target . add ( component ) ; target . appendJavaScript ( "jQuery('#" + component . getMarkupId ( ) + "').slideDown(" + slideDownDuration + ");" ) ; }
Replace the given component with animation .
8,939
public static boolean isDebuggable ( Application app ) { ApplicationInfo info = app . getApplicationInfo ( ) ; return ( info . flags & ApplicationInfo . FLAG_DEBUGGABLE ) != 0 ; }
Checks if the application is running as debug mode or not .
8,940
public static boolean isInstalledOnSDCard ( Application app ) { try { String packageName = app . getPackageName ( ) ; PackageInfo info = app . getPackageManager ( ) . getPackageInfo ( packageName , 0 ) ; String dir = info . applicationInfo . sourceDir ; for ( String path : INTERNAL_PATH ) { if ( path . equals ( dir . substring ( 0 , path . length ( ) ) ) ) return false ; } } catch ( PackageManager . NameNotFoundException exp ) { throw new IllegalArgumentException ( exp ) ; } return true ; }
Checks if the application is installed on external storage in most case on the SD card .
8,941
public void removeAttributeBuilder ( AttributeWidgetBuilder < ? > builder ) { Iterator < AttributeWidgetBuilder < ? > > iterator = builders . values ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { AttributeWidgetBuilder < ? > widgetBuilder = iterator . next ( ) ; if ( widgetBuilder . equals ( builder ) ) { iterator . remove ( ) ; } } }
Remove an attribute widget builder from the collection .
8,942
public Map < String , Object > snapshot ( ) { Map < String , Object > snap = Maps . newHashMap ( ) ; snap . putAll ( sessionStore ) ; snap . putAll ( newAttributes ) ; for ( String name : deleteAttribute ) { snap . remove ( name ) ; } return snap ; }
get session attributes snapshot
8,943
private void processInputDirectories ( ) { String [ ] inputdirs = getOptionValues ( SHORT_OPT_IN_PATH ) ; final List < File > files = new ArrayList < File > ( ) ; final XBELFileFilter xbelFileFilter = new XBELFileFilter ( ) ; final BELFileFilter belFileFilter = new BELFileFilter ( ) ; for ( String inputdir : inputdirs ) { final File workingPath = new File ( inputdir ) ; if ( ! workingPath . canRead ( ) ) { error ( BAD_INPUT_PATH + inputdir ) ; failUsage ( ) ; } final File [ ] xbels = workingPath . listFiles ( xbelFileFilter ) ; if ( xbels != null && xbels . length != 0 ) { files . addAll ( asList ( xbels ) ) ; } final File [ ] bels = workingPath . listFiles ( belFileFilter ) ; if ( bels != null && bels . length != 0 ) { files . addAll ( asList ( bels ) ) ; } } if ( files . size ( ) == 0 ) { error ( NO_DOCUMENT_FILES ) ; failUsage ( ) ; } artifactPath = createDirectoryArtifact ( outputDirectory , DIR_ARTIFACT ) ; processFiles ( files . toArray ( new File [ 0 ] ) ) ; }
Process documents in the input directories .
8,944
private void processFiles ( ) { String [ ] fileArgs = getOptionValues ( INFILE_SHORT_OPT ) ; final List < File > files = new ArrayList < File > ( fileArgs . length ) ; for ( final String fileArg : fileArgs ) { File file = new File ( fileArg ) ; if ( ! file . canRead ( ) ) { error ( INPUT_FILE_UNREADABLE + file ) ; } else { files . add ( file ) ; } } if ( files . size ( ) == 0 ) { error ( NO_DOCUMENT_FILES ) ; failUsage ( ) ; } artifactPath = createDirectoryArtifact ( outputDirectory , DIR_ARTIFACT ) ; processFiles ( files . toArray ( new File [ 0 ] ) ) ; }
Process file arguments .
8,945
private void runCommonStages ( boolean pedantic , Document document ) { if ( ! stage2 ( document ) ) { if ( pedantic ) { bail ( NAMESPACE_RESOLUTION_FAILURE ) ; } } if ( ! stage3 ( document ) ) { if ( pedantic ) { bail ( SYMBOL_VERIFICATION_FAILURE ) ; } } if ( ! stage4 ( document ) ) { if ( pedantic ) { bail ( SEMANTIC_VERIFICATION_FAILURE ) ; } } ProtoNetwork pn = stage5 ( document ) ; if ( ! stage6 ( document , pn ) ) { if ( pedantic ) { bail ( STATEMENT_EXPANSION_FAILURE ) ; } } if ( ! stage7 ( pn , document ) ) { if ( pedantic ) { bail ( PROTO_NETWORK_SAVE_FAILURE ) ; } } }
Runs stages 2 - 7 which remain static regardless of the BEL document input .
8,946
private boolean stage2 ( final Document document ) { beginStage ( PHASE1_STAGE2_HDR , "2" , NUM_PHASES ) ; final StringBuilder bldr = new StringBuilder ( ) ; Collection < Namespace > namespaces = document . getNamespaceMap ( ) . values ( ) ; final int docNSCount = namespaces . size ( ) ; bldr . append ( "Compiling " ) ; bldr . append ( docNSCount ) ; bldr . append ( " namespace" ) ; if ( docNSCount > 1 ) { bldr . append ( "s" ) ; } bldr . append ( " for " ) ; bldr . append ( document . getName ( ) ) ; stageOutput ( bldr . toString ( ) ) ; boolean success = true ; long t1 = currentTimeMillis ( ) ; try { p1 . stage2NamespaceCompilation ( document ) ; } catch ( ResourceDownloadError e ) { success = false ; stageError ( e . getUserFacingMessage ( ) ) ; } catch ( IndexingFailure e ) { success = false ; stageError ( e . getUserFacingMessage ( ) ) ; } long t2 = currentTimeMillis ( ) ; bldr . setLength ( 0 ) ; markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return success ; }
Stage two resolution of document namespaces .
8,947
private boolean stage3 ( final Document document ) { beginStage ( PHASE1_STAGE3_HDR , "3" , NUM_PHASES ) ; final StringBuilder bldr = new StringBuilder ( ) ; if ( hasOption ( NO_SYNTAX_CHECK ) ) { bldr . append ( SYMBOL_CHECKS_DISABLED ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return true ; } bldr . append ( "Verifying symbols in " ) ; bldr . append ( document . getName ( ) ) ; stageOutput ( bldr . toString ( ) ) ; boolean warnings = false ; long t1 = currentTimeMillis ( ) ; try { p1 . stage3SymbolVerification ( document ) ; } catch ( SymbolWarning e ) { warnings = true ; String resname = e . getName ( ) ; if ( resname == null ) { e . setName ( document . getName ( ) ) ; } else { e . setName ( resname + " (" + document . getName ( ) + ")" ) ; } stageWarning ( e . getUserFacingMessage ( ) ) ; } catch ( IndexingFailure e ) { stageError ( "Failed to open namespace index file for symbol " + "verification." ) ; } catch ( ResourceDownloadError e ) { stageError ( "Failed to resolve namespace during symbol " + "verification." ) ; } long t2 = currentTimeMillis ( ) ; bldr . setLength ( 0 ) ; if ( warnings ) { bldr . append ( "Symbol verification resulted in warnings in " ) ; bldr . append ( document . getName ( ) ) ; bldr . append ( "\n" ) ; } markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; if ( warnings ) { return false ; } return true ; }
Stage three symbol verification of the document .
8,948
private boolean stage4 ( final Document document ) { beginStage ( PHASE1_STAGE4_HDR , "4" , NUM_PHASES ) ; final StringBuilder bldr = new StringBuilder ( ) ; if ( hasOption ( NO_SEMANTIC_CHECK ) ) { bldr . append ( SEMANTIC_CHECKS_DISABLED ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return true ; } bldr . append ( "Verifying semantics in " ) ; bldr . append ( document . getName ( ) ) ; stageOutput ( bldr . toString ( ) ) ; boolean warnings = false ; long t1 = currentTimeMillis ( ) ; try { p1 . stage4SemanticVerification ( document ) ; } catch ( SemanticFailure sf ) { warnings = true ; String resname = sf . getName ( ) ; if ( resname == null ) { sf . setName ( document . getName ( ) ) ; } else { sf . setName ( resname + " (" + document . getName ( ) + ")" ) ; } stageWarning ( sf . getUserFacingMessage ( ) ) ; } catch ( IndexingFailure e ) { stageError ( "Failed to process namespace index files for semantic" + " verification." ) ; } long t2 = currentTimeMillis ( ) ; bldr . setLength ( 0 ) ; if ( warnings ) { bldr . append ( "Semantic verification resulted in warnings in " ) ; bldr . append ( document . getName ( ) ) ; bldr . append ( "\n" ) ; } markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; if ( warnings ) { return false ; } return true ; }
Stage four semantic verification of the document .
8,949
private ProtoNetwork stage5 ( final Document document ) { beginStage ( PHASE1_STAGE5_HDR , "5" , NUM_PHASES ) ; final StringBuilder bldr = new StringBuilder ( ) ; bldr . append ( "Building proto-network for " ) ; bldr . append ( document . getName ( ) ) ; stageOutput ( bldr . toString ( ) ) ; long t1 = currentTimeMillis ( ) ; ProtoNetwork ret = p1 . stage5Building ( document ) ; long t2 = currentTimeMillis ( ) ; bldr . setLength ( 0 ) ; markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return ret ; }
Stage five build of proto - network .
8,950
public boolean stage6 ( final Document doc , final ProtoNetwork pn ) { beginStage ( PHASE1_STAGE6_HDR , "6" , NUM_PHASES ) ; final StringBuilder bldr = new StringBuilder ( ) ; boolean stmtSuccess = false , termSuccess = false ; bldr . append ( "Expanding statements and terms" ) ; stageOutput ( bldr . toString ( ) ) ; long t1 = currentTimeMillis ( ) ; boolean stmtExpand = ! hasOption ( NO_NS_LONG_OPT ) ; p1 . stage6Expansion ( doc , pn , stmtExpand ) ; termSuccess = true ; stmtSuccess = true ; long t2 = currentTimeMillis ( ) ; bldr . setLength ( 0 ) ; markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return stmtSuccess && termSuccess ; }
Stage six expansion of the document .
8,951
private boolean stage7 ( final ProtoNetwork pn , final Document doc ) { beginStage ( PHASE1_STAGE7_HDR , "7" , NUM_PHASES ) ; final StringBuilder bldr = new StringBuilder ( ) ; bldr . append ( "Saving proto-network for " ) ; bldr . append ( doc . getName ( ) ) ; stageOutput ( bldr . toString ( ) ) ; long t1 = currentTimeMillis ( ) ; String dir = artifactPath . getAbsolutePath ( ) ; final String path = asPath ( dir , nextUniqueFolderName ( ) ) ; File pnpathname = new File ( path ) ; boolean success = true ; try { p1 . stage7Saving ( pn , pnpathname ) ; if ( withDebug ( ) ) { TextProtoNetworkExternalizer textExternalizer = new TextProtoNetworkExternalizer ( ) ; textExternalizer . writeProtoNetwork ( pn , pnpathname . getAbsolutePath ( ) ) ; } } catch ( ProtoNetworkError e ) { success = false ; error ( "failed to save proto-network" ) ; e . printStackTrace ( ) ; } long t2 = currentTimeMillis ( ) ; bldr . setLength ( 0 ) ; markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return success ; }
Stage seven saving of proto - network .
8,952
public static List < File > getClusterLexiconFiles ( final String clusterPath ) { final List < File > clusterLexicons = new ArrayList < File > ( ) ; final String [ ] clusterPaths = clusterPath . split ( "," ) ; for ( final String clusterName : clusterPaths ) { clusterLexicons . add ( new File ( clusterName ) ) ; } return clusterLexicons ; }
Get a parameter in trainParams . prop file consisting of a list of clustering lexicons separated by comma and return a list of files one for each lexicon .
8,953
public static boolean isPOSBaselineFeatures ( final TrainingParameters params ) { final String posFeatures = getPOSBaselineFeatures ( params ) ; return ! posFeatures . equalsIgnoreCase ( Flags . DEFAULT_FEATURE_FLAG ) ; }
Check if POS Baseline features are active .
8,954
public static boolean isSuperSenseFeatures ( final TrainingParameters params ) { final String mfsFeatures = getSuperSenseFeatures ( params ) ; return ! mfsFeatures . equalsIgnoreCase ( Flags . DEFAULT_FEATURE_FLAG ) ; }
Check if supersense tagger features are active .
8,955
public static boolean isMFSFeatures ( final TrainingParameters params ) { final String mfsFeatures = getMFSFeatures ( params ) ; return ! mfsFeatures . equalsIgnoreCase ( Flags . DEFAULT_FEATURE_FLAG ) ; }
Check if mfs features are active .
8,956
private < T > T getService ( final Class < T > serviceType , final long timeoutInMillis ) throws NoSuchServiceException { LOG . info ( "Look up service [" + serviceType . getName ( ) + "], timeout in " + timeoutInMillis + " millis" ) ; final ServiceReference ref = m_bundleContext . getServiceReference ( serviceType . getName ( ) ) ; if ( ref != null ) { final Object service = m_bundleContext . getService ( ref ) ; if ( service == null ) { throw new NoSuchServiceException ( serviceType ) ; } return ( T ) service ; } else { throw new NoSuchServiceException ( serviceType ) ; } }
Lookup a service in the service registry .
8,957
private void startBundle ( final Bundle bundle ) throws BundleException { int bundleState = bundle . getState ( ) ; if ( bundleState == Bundle . ACTIVE ) { return ; } Dictionary bundleHeaders = bundle . getHeaders ( ) ; if ( bundleHeaders . get ( Constants . FRAGMENT_HOST ) != null ) { return ; } bundle . start ( ) ; bundleState = bundle . getState ( ) ; if ( bundleState != Bundle . ACTIVE ) { long bundleId = bundle . getBundleId ( ) ; String bundleName = bundle . getSymbolicName ( ) ; String bundleStateStr = bundleStateToString ( bundleState ) ; throw new BundleException ( "Bundle (" + bundleId + ", " + bundleName + ") not started (still " + bundleStateStr + ")" ) ; } }
Starts a bundle .
8,958
public Span trim ( final CharSequence text ) { int newStartOffset = getStart ( ) ; for ( int i = getStart ( ) ; i < getEnd ( ) && StringUtil . isWhitespace ( text . charAt ( i ) ) ; i ++ ) { newStartOffset ++ ; } int newEndOffset = getEnd ( ) ; for ( int i = getEnd ( ) ; i > getStart ( ) && StringUtil . isWhitespace ( text . charAt ( i - 1 ) ) ; i -- ) { newEndOffset -- ; } if ( newStartOffset == getStart ( ) && newEndOffset == getEnd ( ) ) { return this ; } else if ( newStartOffset > newEndOffset ) { return new Span ( getStart ( ) , getStart ( ) , getType ( ) ) ; } else { return new Span ( newStartOffset , newEndOffset , getType ( ) ) ; } }
Return a copy of this span with leading and trailing white spaces removed .
8,959
public static String [ ] getTypesFromSpans ( final Span [ ] spans , final String [ ] tokens ) { final List < String > tagsList = new ArrayList < String > ( ) ; for ( final Span span : spans ) { tagsList . add ( span . getType ( ) ) ; } return tagsList . toArray ( new String [ tagsList . size ( ) ] ) ; }
Get an array of Spans and their associated tokens and obtains an array of Strings containing the type for each Span .
8,960
public static final void postProcessDuplicatedSpans ( final List < Span > preList , final Span [ ] postList ) { final List < Span > duplicatedSpans = new ArrayList < Span > ( ) ; for ( final Span span1 : preList ) { for ( final Span span2 : postList ) { if ( span1 . contains ( span2 ) ) { duplicatedSpans . add ( span1 ) ; } else if ( span2 . contains ( span1 ) ) { duplicatedSpans . add ( span1 ) ; } } } preList . removeAll ( duplicatedSpans ) ; }
Removes spans from the preList if the span is contained in the postList .
8,961
public static final void concatenateSpans ( final List < Span > allSpans , final Span [ ] neSpans ) { for ( final Span span : neSpans ) { allSpans . add ( span ) ; } }
Concatenates two span lists adding the spans of the second parameter to the list in first parameter .
8,962
public WebPage run ( WebPage initialPage ) { if ( getUser ( ) == null ) throw new IllegalStateException ( "the user set is null" ) ; WebPage currentPage = initialPage ; for ( WebTask task : this ) { logger . info ( "BEGIN subtask " + task . getClass ( ) . getSimpleName ( ) ) ; task . setUser ( getUser ( ) ) ; currentPage = task . run ( currentPage ) ; logger . info ( "END subtask " + task . getClass ( ) . getSimpleName ( ) ) ; } return currentPage ; }
Runs each subtask in order and finally return the page that the last task was visiting . Each subtask will run with the same user as the composite .
8,963
public Map < String , Double > scoreMap ( String [ ] text ) { Map < String , Double > probDist = new HashMap < > ( ) ; double [ ] categorize = classifyProb ( text ) ; int catSize = getNumberOfLabels ( ) ; for ( int i = 0 ; i < catSize ; i ++ ) { String category = getLabel ( i ) ; probDist . put ( category , categorize [ getIndex ( category ) ] ) ; } return probDist ; }
Returns a map in which the key is the label name and the value is the score .
8,964
public SortedMap < Double , Set < String > > sortedScoreMap ( String [ ] text ) { SortedMap < Double , Set < String > > descendingMap = new TreeMap < > ( ) ; double [ ] categorize = classifyProb ( text ) ; int catSize = getNumberOfLabels ( ) ; for ( int i = 0 ; i < catSize ; i ++ ) { String category = getLabel ( i ) ; double score = categorize [ getIndex ( category ) ] ; if ( descendingMap . containsKey ( score ) ) { descendingMap . get ( score ) . add ( category ) ; } else { Set < String > newset = new HashSet < > ( ) ; newset . add ( category ) ; descendingMap . put ( score , newset ) ; } } return descendingMap ; }
Returns a map with the score as a key in ascending order . The value is a Set of categories with the score . Many labels can have the same score hence the Set as value .
8,965
protected Parse [ ] advanceTags ( final Parse p ) { final Parse [ ] children = p . getChildren ( ) ; final String [ ] words = new String [ children . length ] ; final double [ ] probs = new double [ words . length ] ; for ( int i = 0 , il = children . length ; i < il ; i ++ ) { words [ i ] = children [ i ] . getCoveredText ( ) ; } final Sequence [ ] ts = this . tagger . topKSequences ( words ) ; if ( ts . length == 0 ) { System . err . println ( "no tag sequence" ) ; } final Parse [ ] newParses = new Parse [ ts . length ] ; for ( int i = 0 ; i < ts . length ; i ++ ) { final String [ ] tags = ts [ i ] . getOutcomes ( ) . toArray ( new String [ words . length ] ) ; ts [ i ] . getProbs ( probs ) ; newParses [ i ] = ( Parse ) p . clone ( ) ; if ( this . createDerivationString ) { newParses [ i ] . getDerivation ( ) . append ( i ) . append ( "." ) ; } for ( int j = 0 ; j < words . length ; j ++ ) { final Parse word = children [ j ] ; final double prob = probs [ j ] ; newParses [ i ] . insert ( new Parse ( word . getText ( ) , word . getSpan ( ) , tags [ j ] . replaceAll ( "-" + BioCodec . START , "" ) , prob , j ) ) ; newParses [ i ] . addProb ( Math . log ( prob ) ) ; } } return newParses ; }
Advances the parse by assigning it POS tags and returns multiple tag sequences .
8,966
public static void removeReservedNullVaules ( JsonObject jsonObject ) { Set < Map . Entry < String , JsonElement > > entries = jsonObject . entrySet ( ) ; for ( Map . Entry < String , JsonElement > entry : entries ) { if ( entry . getValue ( ) . isJsonNull ( ) ) { jsonObject . remove ( entry . getKey ( ) ) ; } } }
Removes keys from json object if they have null values . Won t touch fields as users may want to explicitly set them to null
8,967
public Model findOrCreateTemplate ( String name , InputStream modelJson ) throws IOException { try { Model m = getTemplateByName ( name ) ; return m ; } catch ( IllegalArgumentException ignore ) { } String modelStr = IOUtils . toString ( modelJson , "UTF-8" ) ; return modelService . createModel ( new TypedString ( modelStr ) ) ; }
Tries to lookup the model by name and returns it if it s found . If not it is created from the provided JSON input stream .
8,968
protected SigninPanel < T > newSigninPanel ( final String id , final IModel < T > model ) { return new SigninPanel < > ( id , model ) ; }
Factory method for creating the SigninPanel that contains the TextField for the email and password . This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a Component that contains the TextField for the email and password .
8,969
protected Component newUsernameTextField ( final String id , final IModel < T > model ) { final IModel < String > labelModel = ResourceModelFactory . newResourceModel ( "global.username.label" , this ) ; final IModel < String > placeholderModel = ResourceModelFactory . newResourceModel ( "global.enter.your.username.label" , this ) ; final LabeledTextFieldPanel < String , T > nameTextField = new LabeledTextFieldPanel < String , T > ( id , model , labelModel ) { private static final long serialVersionUID = 1L ; @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) protected TextField newTextField ( final String id , final IModel < T > modelSuper ) { final TextField < String > textField = new TextField < String > ( id , new PropertyModel < > ( model , "username" ) ) ; textField . setOutputMarkupId ( true ) ; textField . setRequired ( true ) ; if ( placeholderModel != null ) { textField . add ( new AttributeAppender ( "placeholder" , placeholderModel ) ) ; } return textField ; } } ; return nameTextField ; }
Factory method for creating the TextField for the username . This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a TextField for the username .
8,970
public static String getPackageNameFromPid ( Context context , int pid ) { ActivityManager am = ( ActivityManager ) context . getSystemService ( Context . ACTIVITY_SERVICE ) ; List < RunningAppProcessInfo > processes = am . getRunningAppProcesses ( ) ; for ( RunningAppProcessInfo info : processes ) { if ( info . pid == pid ) { String [ ] packages = info . pkgList ; if ( packages . length > 0 ) { return packages [ 0 ] ; } break ; } } return null ; }
Get package name of the process id .
8,971
public FeatureCollection createCollection ( JSONObject jsonObject , FeaturesSupported layer ) { FeatureCollection dto = new FeatureCollection ( layer ) ; String type = JsonService . getStringValue ( jsonObject , "type" ) ; if ( "FeatureCollection" . equals ( type ) ) { JSONArray features = JsonService . getChildArray ( jsonObject , "features" ) ; for ( int i = 0 ; i < features . size ( ) ; i ++ ) { dto . getFeatures ( ) . add ( createFeature ( ( JSONObject ) features . get ( i ) , layer ) ) ; } } else if ( "Feature" . equals ( type ) ) { dto . getFeatures ( ) . add ( createFeature ( jsonObject , layer ) ) ; } return dto ; }
Create a feature collection for this layer .
8,972
private String doFindEquivalence ( final String sourceNamespace , final String destinationNamespace , final String sourceValue ) { JDBMEquivalenceLookup sourceLookup = openEquivalences . get ( sourceNamespace ) ; if ( sourceLookup == null ) { return null ; } final SkinnyUUID sourceUUID = sourceLookup . lookup ( sourceValue ) ; if ( sourceUUID == null ) { return null ; } return doFindEquivalence ( destinationNamespace , sourceUUID ) ; }
Obtain the destinationNamespace equivalent value of sourceValue in sourceNamespace
8,973
private String doFindEquivalence ( final String destinationNamespace , final SkinnyUUID sourceUUID ) { JDBMEquivalenceLookup destinationLookup = openEquivalences . get ( destinationNamespace ) ; return destinationLookup . reverseLookup ( sourceUUID ) ; }
Obtain the destinationNamespace equivalent value of the sourceUUID .
8,974
private void initAttrs ( FilterConfig config ) { String param = config . getInitParameter ( SESSION_COOKIE_NAME ) ; sessionCookieName = Strings . isNullOrEmpty ( param ) ? DEFAULT_SESSION_COOKIE_NAME : param ; param = config . getInitParameter ( MAX_INACTIVE_INTERVAL ) ; maxInactiveInterval = Strings . isNullOrEmpty ( param ) ? DEFAULT_MAX_INACTIVE_INTERVAL : Integer . parseInt ( param ) ; cookieDomain = config . getInitParameter ( COOKIE_DOMAIN ) ; param = config . getInitParameter ( COOKIE_CONTEXT_PATH ) ; cookieContextPath = Strings . isNullOrEmpty ( param ) ? DEFAULT_COOKIE_CONTEXT_PATH : param ; param = config . getInitParameter ( COOKIE_MAX_AGE ) ; cookieMaxAge = Strings . isNullOrEmpty ( param ) ? DEFAULT_COOKIE_MAX_AGE : Integer . parseInt ( param ) ; log . info ( "SessionFilter (sessionCookieName={},maxInactiveInterval={},cookieDomain={})" , sessionCookieName , maxInactiveInterval , cookieDomain ) ; }
init basic attribute
8,975
public List < String > tagClitics ( String word , String posTag , String lemma , MorfologikLemmatizer lemmatizer ) throws IOException { List < String > newCliticElems = new ArrayList < String > ( ) ; Clitic match = cliticMatcher ( word , posTag ) ; if ( match != null ) { addCliticComponents ( word , posTag , lemmatizer , match , newCliticElems ) ; } return newCliticElems ; }
Takes word posTag and lemma as input and finds if any clitic pronouns are in verbs .
8,976
private void failIndex ( PhaseThreeOptions phasecfg , String errorMessage ) { stageError ( errorMessage ) ; final StringBuilder bldr = new StringBuilder ( ) ; bldr . append ( "Could not find resource index file." ) ; bldr . append ( "Expansion of protein families, named complexes, " ) ; bldr . append ( "gene scaffolding, and orthology will not occur." ) ; stageError ( bldr . toString ( ) ) ; ResourceIndex . INSTANCE . loadIndex ( ) ; phasecfg . setInjectProteinFamilies ( false ) ; phasecfg . setInjectNamedComplexes ( false ) ; phasecfg . setInjectGeneScaffolding ( false ) ; phasecfg . setInjectOrthology ( false ) ; }
Logic to recover from a missing resource index .
8,977
private void processNetwork ( final ProtoNetwork pn ) { ProtoNetwork pfamMerged = stage1 ( pn ) ; ProtoNetwork ncMerged = stage2 ( pfamMerged ) ; ProtoNetwork geneMerged = stage3 ( ncMerged ) ; ProtoNetwork orthoMerged = stage4 ( geneMerged ) ; ProtoNetwork equived = stage5 ( orthoMerged ) ; stage6 ( equived ) ; }
Runs the phase three stages over the input proto - network .
8,978
private ProtoNetwork failProteinFamilies ( final ProtoNetwork pn , final StringBuilder bldr , String pfLocation , String errorMessage ) { bldr . append ( "PROTEIN FAMILY RESOLUTION FAILURE in " ) ; bldr . append ( pfLocation ) ; bldr . append ( "\n\treason: " ) ; bldr . append ( errorMessage ) ; stageWarning ( bldr . toString ( ) ) ; return pn ; }
Logic to recover from a failed protein family document .
8,979
private ProtoNetwork failNamedComplexes ( final ProtoNetwork pn , final StringBuilder bldr , String ncLocation , String errorMessage ) { bldr . append ( "NAMED COMPLEXES RESOLUTION FAILURE in " ) ; bldr . append ( ncLocation ) ; bldr . append ( "\n\treason: " ) ; bldr . append ( errorMessage ) ; stageWarning ( bldr . toString ( ) ) ; return pn ; }
Logic to recover from a failure to resolve a named complexes resource .
8,980
private ProtoNetwork failGeneScaffolding ( final ProtoNetwork pn , final StringBuilder bldr , String gsLocation , String errorMessage ) { bldr . append ( "GENE SCAFFOLDING RESOURCE RESOLUTION FAILURE in " ) ; bldr . append ( gsLocation ) ; bldr . append ( "\n\treason: " ) ; bldr . append ( errorMessage ) ; stageWarning ( bldr . toString ( ) ) ; return pn ; }
Logic to recover from a failure to resolve the gene scaffolding resource .
8,981
private ProtoNetwork stage4 ( final ProtoNetwork pn ) { beginStage ( PHASE3_STAGE4_HDR , "4" , NUM_PHASES ) ; if ( ! getPhaseConfiguration ( ) . getInjectOrthology ( ) ) { final StringBuilder bldr = new StringBuilder ( ) ; bldr . append ( ORTHO_INJECTION_DISABLED ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return pn ; } artifactPath = createDirectoryArtifact ( outputDirectory , DIR_ARTIFACT ) ; final Index index = ResourceIndex . INSTANCE . getIndex ( ) ; final Set < ResourceLocation > resources = index . getOrthologyResources ( ) ; if ( noItems ( resources ) ) { final StringBuilder bldr = new StringBuilder ( ) ; bldr . append ( "No orthology documents included." ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return pn ; } Set < EquivalenceDataIndex > equivs ; try { equivs = p2 . stage2LoadNamespaceEquivalences ( ) ; } catch ( EquivalenceMapResolutionFailure e ) { stageError ( e . getUserFacingMessage ( ) ) ; equivs = emptySet ( ) ; } try { p2 . stage3EquivalenceParameters ( pn , equivs ) ; } catch ( IOException e ) { } final Iterator < ResourceLocation > it = resources . iterator ( ) ; final ResourceLocation first = it . next ( ) ; final ProtoNetwork orthoMerge = pruneResource ( pn , first ) ; while ( it . hasNext ( ) ) { final ResourceLocation resource = it . next ( ) ; final ProtoNetwork opn = pruneResource ( pn , resource ) ; try { p3 . merge ( orthoMerge , opn ) ; } catch ( ProtoNetworkError e ) { e . printStackTrace ( ) ; } } try { runPhaseThree ( orthoMerge ) ; } catch ( ProtoNetworkError e ) { stageError ( e . getUserFacingMessage ( ) ) ; bail ( ExitCode . GENERAL_FAILURE ) ; } try { p3 . merge ( pn , orthoMerge ) ; } catch ( ProtoNetworkError e ) { stageError ( e . getUserFacingMessage ( ) ) ; bail ( ExitCode . GENERAL_FAILURE ) ; } return pn ; }
Runs stage four injecting of homology knowledge .
8,982
private ProtoNetwork stage5 ( ProtoNetwork pn ) { beginStage ( PHASE3_STAGE5_HDR , "5" , NUM_PHASES ) ; final StringBuilder bldr = new StringBuilder ( ) ; if ( ! withGeneScaffoldingInjection ( ) && ! withNamedComplexInjection ( ) && ! withProteinFamilyInjection ( ) ) { bldr . append ( INJECTIONS_DISABLED ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return pn ; } Set < EquivalenceDataIndex > equivs ; try { equivs = p2 . stage2LoadNamespaceEquivalences ( ) ; } catch ( EquivalenceMapResolutionFailure e ) { stageError ( e . getUserFacingMessage ( ) ) ; equivs = emptySet ( ) ; } long t1 = currentTimeMillis ( ) ; int pct = stage5Parameter ( pn , equivs , bldr ) ; stage5Term ( pn , pct ) ; stage5Statement ( pn , pct ) ; long t2 = currentTimeMillis ( ) ; final int paramct = pn . getParameterTable ( ) . getTableParameters ( ) . size ( ) ; final int termct = pn . getTermTable ( ) . getTermValues ( ) . size ( ) ; final int stmtct = pn . getStatementTable ( ) . getStatements ( ) . size ( ) ; bldr . setLength ( 0 ) ; bldr . append ( stmtct ) ; bldr . append ( " statements, " ) ; bldr . append ( termct ) ; bldr . append ( " terms, " ) ; bldr . append ( paramct ) ; bldr . append ( " parameters" ) ; stageOutput ( bldr . toString ( ) ) ; bldr . setLength ( 0 ) ; markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; return pn ; }
Runs stage five equivalencing of the proto - network .
8,983
private int stage5Parameter ( final ProtoNetwork network , Set < EquivalenceDataIndex > equivalences , final StringBuilder bldr ) { bldr . append ( "Equivalencing parameters" ) ; stageOutput ( bldr . toString ( ) ) ; ProtoNetwork ret = network ; int ct = 0 ; try { ct = p2 . stage3EquivalenceParameters ( ret , equivalences ) ; stageOutput ( "(" + ct + " equivalences)" ) ; } catch ( IOException ioex ) { final String err = ioex . getMessage ( ) ; fatal ( err ) ; } return ct ; }
Stage five parameter equivalencing .
8,984
private void stage5Term ( final ProtoNetwork network , int pct ) { if ( pct > 0 ) { stageOutput ( "Equivalencing terms" ) ; int tct = p2 . stage3EquivalenceTerms ( network ) ; stageOutput ( "(" + tct + " equivalences)" ) ; } else { stageOutput ( "Skipping term equivalencing" ) ; } }
Stage five term equivalencing .
8,985
private void stage5Statement ( final ProtoNetwork network , int pct ) { if ( pct > 0 ) { stageOutput ( "Equivalencing statements" ) ; int sct = p2 . stage3EquivalenceStatements ( network ) ; stageOutput ( "(" + sct + " equivalences)" ) ; } else { stageOutput ( "Skipping statement equivalencing" ) ; } }
Stage five statement equivalencing .
8,986
private void stage6 ( ProtoNetwork pn ) { beginStage ( PHASE3_STAGE6_HDR , "6" , NUM_PHASES ) ; stageOutput ( "Saving augmented network" ) ; final String rootpath = artifactPath . getAbsolutePath ( ) ; long t1 = currentTimeMillis ( ) ; try { p3 . write ( rootpath , pn ) ; if ( withDebug ( ) ) { try { TextProtoNetworkExternalizer textExternalizer = new TextProtoNetworkExternalizer ( ) ; textExternalizer . writeProtoNetwork ( pn , rootpath ) ; } catch ( ProtoNetworkError e ) { error ( "Could not write out equivalenced proto network." ) ; } } } catch ( ProtoNetworkError e ) { stageError ( e . getUserFacingMessage ( ) ) ; bail ( NO_PROTO_NETWORKS_SAVED ) ; } long t2 = currentTimeMillis ( ) ; final StringBuilder bldr = new StringBuilder ( ) ; markTime ( bldr , t1 , t2 ) ; markEndStage ( bldr ) ; stageOutput ( bldr . toString ( ) ) ; }
Runs stage six network saving .
8,987
public void addContentAndShow ( List < Label > content , int left , int top , boolean showCloseButton ) { if ( showCloseButton ) { Label closeButtonLabel = new Label ( " X " ) ; closeButtonLabel . addStyleName ( ToolTipResource . INSTANCE . css ( ) . toolTipCloseButton ( ) ) ; contentPanel . add ( closeButtonLabel ) ; closeButtonLabel . addClickHandler ( new ClickHandler ( ) { public void onClick ( ClickEvent event ) { hide ( ) ; } } ) ; } for ( Label l : content ) { l . addStyleName ( ToolTipResource . INSTANCE . css ( ) . toolTipLine ( ) ) ; contentPanel . add ( l ) ; } toolTip . setPopupPosition ( left , top ) ; toolTip . show ( ) ; }
Add content to the tooltip and show it with the given parameters .
8,988
public void setFeature ( Feature feature ) { for ( HasFeature action : actions ) { action . setFeature ( feature ) ; } presenter . setFeature ( feature ) ; }
Set the feature to display .
8,989
public void addHasFeature ( HasFeature action ) { actions . add ( action ) ; action . setFeature ( presenter . getFeature ( ) ) ; }
Add an object for this feature to the widget . When the displayed feature changes the feature associated with the object is automatically updated .
8,990
public static String byteToHex ( byte [ ] data ) { if ( data == null ) { return null ; } final StringBuilder builder = new StringBuilder ( ) ; for ( final byte b : data ) { builder . append ( String . format ( "%02X" , b ) ) ; } return builder . toString ( ) ; }
Convert byte data to hex code string .
8,991
public ProtoNetwork readProtoNetwork ( ProtoNetworkDescriptor protoNetworkDescriptor ) throws ProtoNetworkError { if ( ! BinaryProtoNetworkDescriptor . class . isAssignableFrom ( protoNetworkDescriptor . getClass ( ) ) ) { String err = "protoNetworkDescriptor cannot be of type " ; err = err . concat ( protoNetworkDescriptor . getClass ( ) . getName ( ) ) ; err = err . concat ( ", need type " ) ; err = err . concat ( BinaryProtoNetworkDescriptor . class . getName ( ) ) ; throw new InvalidArgument ( err ) ; } BinaryProtoNetworkDescriptor binaryProtoNetworkDescriptor = ( BinaryProtoNetworkDescriptor ) protoNetworkDescriptor ; File pn = binaryProtoNetworkDescriptor . getProtoNetwork ( ) ; ObjectInputStream ois = null ; try { ois = new ObjectInputStream ( new FileInputStream ( pn ) ) ; ProtoNetwork network = new ProtoNetwork ( ) ; network . readExternal ( ois ) ; return network ; } catch ( FileNotFoundException e ) { final String msg = "Cannot find binary proto-network for path" ; throw new ProtoNetworkError ( pn . getAbsolutePath ( ) , msg , e ) ; } catch ( IOException e ) { final String msg = "Cannot read binary proto-network for path" ; throw new ProtoNetworkError ( pn . getAbsolutePath ( ) , msg , e ) ; } catch ( ClassNotFoundException e ) { final String msg = "Cannot read proto-network for path" ; throw new ProtoNetworkError ( pn . getAbsolutePath ( ) , msg , e ) ; } finally { IOUtils . closeQuietly ( ois ) ; } }
Reads a proto network from a descriptor representing a binary file .
8,992
public ProtoNetworkDescriptor writeProtoNetwork ( ProtoNetwork protoNetwork , String protoNetworkRootPath ) throws ProtoNetworkError { final String filename = PROTO_NETWORK_FILENAME ; final File file = new File ( asPath ( protoNetworkRootPath , filename ) ) ; ObjectOutputStream oos = null ; try { oos = new ObjectOutputStream ( new FileOutputStream ( file ) ) ; protoNetwork . writeExternal ( oos ) ; return new BinaryProtoNetworkDescriptor ( file ) ; } catch ( IOException e ) { final String name = file . getAbsolutePath ( ) ; final String msg = "Cannot create temporary binary file for proto-network" ; throw new ProtoNetworkError ( name , msg , e ) ; } finally { IOUtils . closeQuietly ( oos ) ; } }
Writes a binary - based proto network and produces a descriptor including the binary file .
8,993
public AjaxCloseableTabbedPanel < T > setSelectedTab ( final int index ) { if ( ( index < 0 ) || ( index >= tabs . size ( ) ) ) { throw new IndexOutOfBoundsException ( ) ; } setDefaultModelObject ( index ) ; currentTab = - 1 ; setCurrentTab ( index ) ; return this ; }
sets the selected tab
8,994
public Headers getHttpHeaders ( ) { Headers headers = new Headers ( ) ; if ( byteRange != null ) { StringBuilder rangeBuilder = new StringBuilder ( "bytes=" ) ; long start ; if ( byteRange . offset >= 0 ) { rangeBuilder . append ( byteRange . offset ) ; start = byteRange . offset ; } else { start = 1 ; } rangeBuilder . append ( "-" ) ; if ( byteRange . length > 0 ) { rangeBuilder . append ( start + byteRange . length - 1 ) ; } Header rangeHeader = new BasicHeader ( "Range" , rangeBuilder . toString ( ) ) ; headers . addHeader ( rangeHeader ) ; } return headers ; }
Get the HTTP headers to be used for download request .
8,995
public ByteSink getByteSink ( ) { ByteSink bs = byteSink ; if ( progressListener != null ) { bs = new ProgressByteSink ( bs , progressListener ) ; } return bs ; }
If no progress listener has been set return the byte sink defined in constructor otherwise decorate it .
8,996
public static void hide ( Context context , View v ) { InputMethodManager manager = ( InputMethodManager ) context . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; manager . hideSoftInputFromWindow ( v . getWindowToken ( ) , 0 ) ; }
Hide the software input window .
8,997
public boolean hasExpired ( ) { if ( expiresAt == null ) { LOGGER . debug ( "hasExpired - token is not expirable" ) ; return false ; } long now = System . currentTimeMillis ( ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "hasExpired? - now: {} expiredAt: {} " , new Date ( now ) , expiresAt ) ; } return now > expiresAt . getTime ( ) ; }
Indicates if the access token has expired
8,998
public void update ( JSONObject json ) { accessToken = json . getString ( ACCESS_TOKEN ) ; tokenType = json . getString ( TOKEN_TYPE ) ; expiresAt = calculateExpiresAt ( json ) ; if ( json . has ( OAuth2 . REFRESH_TOKEN ) ) { refreshToken = json . getString ( OAuth2 . REFRESH_TOKEN ) ; } }
Update the credentials from a JSON request response .
8,999
private static Date calculateExpiresAt ( JSONObject jsonObj ) { long expiresAt_s = jsonObj . optLong ( OAuth2Credentials . EXPIRES_AT , - 1 ) ; if ( expiresAt_s < 0 && jsonObj . has ( OAuth2Credentials . EXPIRES_IN ) ) { long expiresIn_s = jsonObj . getLong ( OAuth2Credentials . EXPIRES_IN ) ; if ( expiresIn_s > 6 * 60 ) { expiresIn_s -= 5 * 60 ; } expiresAt_s = System . currentTimeMillis ( ) / 1000 + expiresIn_s ; } if ( expiresAt_s < 0 ) { return null ; } return new Date ( expiresAt_s * 1000 ) ; }
Calculate expiration timestamp if not defined .