idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
137,700 | public Set < SourceFile > getDependencies ( ) { Set < SourceFile > sourceFiles = new TreeSet < SourceFile > ( ) ; // Include all of the standard dependencies. for ( Template t : dependencies . values ( ) ) { sourceFiles . add ( t . sourceFile ) ; } // Add the files that were looked-up but not found as well as the files // included via the file_contents() function. sourceFiles . addAll ( otherDependencies ) ; return Collections . unmodifiableSet ( sourceFiles ) ; } | Returns an unmodifiable copy of the dependencies . | 116 | 10 |
137,701 | public Template globalLoad ( String name , boolean lookupOnly ) { // If this context was created without a Compiler object specified, then // no global lookups can be done. Just return null indicating that the // requested template can't be found. if ( compiler == null ) { return null ; } // Use the full lookup to find the correct template file. This must // always be done on a global load because the actual template file on // disk may be different for different object templates. The raw // (unduplicated) value of LOADPATH can be used because it will not be // changed by the code below. SourceRepository repository = compiler . getSourceRepository ( ) ; SourceFile source = repository . retrievePanSource ( name , relativeLoadpaths ) ; if ( source . isAbsent ( ) ) { if ( lookupOnly ) { // Files that were searched for but not found are still // dependencies. Keep track of these so that they can be // included in the dependency file and checked when trying to // see if profiles are up-to-date. otherDependencies . add ( source ) ; return null ; } else { // The lookupOnly flag was not set, so it is an error if the // template has not been found. throw EvaluationException . create ( ( SourceRange ) null , ( BuildContext ) this , MSG_CANNOT_LOCATE_TEMPLATE , name ) ; } } // Now actually retrieve the other object's root, waiting if the // result isn't yet available. CompileCache ccache = compiler . getCompileCache ( ) ; CompileResult cresult = ccache . waitForResult ( source . getPath ( ) . getAbsolutePath ( ) ) ; Template template = null ; try { // Extract the compiled template and ensure that the name is // correct. The template must not be null if no exception is thrown. template = cresult . template ; template . templateNameVerification ( name ) ; // Found the template. Put this into the dependencies only if we're // really going to use it. I.e. if the lookupOnly flag is false. if ( ! lookupOnly ) { dependencies . put ( name , template ) ; if ( template . type == TemplateType . OBJECT ) { objectDependencies . add ( template . name ) ; } } } catch ( SyntaxException se ) { // This can happen if there is a syntax error while including // the given template. If this isn't just a lookup, then convert // this into an evaluation exception // and throw it. if ( ! lookupOnly ) { throw new EvaluationException ( se . getMessage ( ) ) ; } else { template = null ; } } catch ( EvaluationException ee ) { // Eat the exception if we're only doing a lookup; otherwise, // rethrow it. if ( ! lookupOnly ) { throw ee ; } else { template = null ; } } return template ; } | A method to load a template from the global cache . This may trigger the global cache to compile the template . | 613 | 22 |
137,702 | public void setBinding ( Path path , FullType fullType , Template template , SourceRange sourceRange ) { assert ( path != null ) ; assert ( path . isAbsolute ( ) ) ; assert ( fullType != null ) ; // Must make sure that all of the subtypes for the given type are // defined before adding the binding. try { fullType . verifySubtypesDefined ( types ) ; } catch ( EvaluationException ee ) { throw ee . addExceptionInfo ( sourceRange , template . source , this . getTraceback ( sourceRange ) ) ; } // Retrieve or create the list of bindings for this path. List < FullType > list = bindings . get ( path ) ; if ( list == null ) { list = new LinkedList < FullType > ( ) ; bindings . put ( path , list ) ; } // Add the binding. assert ( list != null ) ; list . add ( fullType ) ; } | This method associates a type definition to a path . These bindings are checked as part of the validation process . Note that there can be more than one binding per path . | 200 | 33 |
137,703 | public void setGlobalVariable ( String name , Element value ) { assert ( name != null ) ; GlobalVariable gvar = globalVariables . get ( name ) ; gvar . setValue ( value ) ; } | Set the variable to the given value preserving the status of the final flag . This will unconditionally set the value without checking if the value is final ; be careful . The value must already exist . | 44 | 39 |
137,704 | public void setGlobalVariable ( String name , GlobalVariable variable ) { assert ( name != null ) ; if ( variable != null ) { globalVariables . put ( name , variable ) ; } else { globalVariables . remove ( name ) ; } } | Set the variable to the given GlobalVariable . If variable is null then the global variable definition is removed . | 53 | 21 |
137,705 | public GlobalVariable replaceGlobalVariable ( String name , Element value , boolean finalFlag ) { assert ( name != null ) ; GlobalVariable oldVariable = globalVariables . get ( name ) ; GlobalVariable newVariable = new GlobalVariable ( finalFlag , value ) ; globalVariables . put ( name , newVariable ) ; return oldVariable ; } | Replaces the given global variable with the given value . The flag indicates whether or not the variable should be marked as final . Note however that this routine does not respect the final flag and replaces the value unconditionally . The function returns the old value of the variable or null if it didn t exist . | 71 | 60 |
137,706 | public void setGlobalVariable ( String name , Element value , boolean finalFlag ) { assert ( name != null ) ; // Either modify an existing value (with appropriate checks) or add a // new one. if ( globalVariables . containsKey ( name ) ) { GlobalVariable gvar = globalVariables . get ( name ) ; gvar . setValue ( value ) ; gvar . setFinalFlag ( finalFlag ) ; } else if ( value != null ) { GlobalVariable gvar = new GlobalVariable ( finalFlag , value ) ; globalVariables . put ( name , gvar ) ; } } | Set the variable to the given value . If the value is null then the variable will be removed from the context . | 127 | 23 |
137,707 | public Element getGlobalVariable ( String name ) { GlobalVariable gvar = globalVariables . get ( name ) ; return ( gvar != null ) ? gvar . getValue ( ) : null ; } | Return the Element which corresponds to the given variable name without duplicating the value . This is useful when dealing with SELF or with variables in a context where it is known that the value won t be modified . | 43 | 42 |
137,708 | public Element getElement ( Path path , boolean errorIfNotFound ) throws EvaluationException { // Set the initial node to use. Element node = null ; // The initial element to use depends on the type of path. Define the // correct root element. switch ( path . getType ( ) ) { case ABSOLUTE : // Typical, very easy case. All absolute paths refer to this object. node = root ; break ; case RELATIVE : // Check to see if we are within a structure template by checking if // relativeRoot is set. If set, then proceed with lookup, otherwise // fail. if ( relativeRoot != null ) { node = relativeRoot ; } else { throw new EvaluationException ( "relative path ('" + path + "') cannot be used to retrieve element in configuration" ) ; } break ; case EXTERNAL : // This is an external path. Check the authority. String myObject = objectTemplate . name ; String externalObject = path . getAuthority ( ) ; if ( myObject . equals ( externalObject ) ) { // Easy case, this references itself. Just set the initial node // to the root of this object. node = root ; } else { // FIXME: Review this code. Much can probably be deleted. // Harder case, we must lookup the other object template, // compiling and building it as necessary. // Try loading the template. This may throw an // EvaluationException if something goes wrong in the load. Template externalTemplate = localAndGlobalLoad ( externalObject , ! errorIfNotFound ) ; // Check to see if the template was found. if ( externalTemplate != null && ! errorIfNotFound ) { // If we asked for only a lookup of the template, then we // need to ensure that the referenced template is added to // the dependencies. dependencies . put ( externalObject , externalTemplate ) ; objectDependencies . add ( externalObject ) ; } else if ( externalTemplate == null ) { // Throw an error or return null as appropriate. if ( errorIfNotFound ) { throw new EvaluationException ( "object template " + externalObject + " could not be found" , null ) ; } else { return null ; } } // Verify that the retrieved template is actually an object // template. if ( externalTemplate . type != TemplateType . OBJECT ) { throw new EvaluationException ( externalObject + " does not refer to an object template" ) ; } // Retrieve the build cache. BuildCache bcache = compiler . getBuildCache ( ) ; // Only check the object dependencies if this object is // currently in the "build" phase. If this is being validated, // then circular dependencies will be handled without problems. // If dependencies are checked, check BEFORE waiting for the // external object, otherwise the compilation may deadlock. if ( checkObjectDependencies ) { bcache . setDependency ( myObject , externalObject ) ; } // Wait for the result and set the node to the external object's // root element. BuildResult result = ( BuildResult ) bcache . waitForResult ( externalObject ) ; node = result . getRoot ( ) ; } break ; } // Now that the root node is defined, recursively descend through the // given terms to retrieve the desired element. assert ( node != null ) ; try { node = node . rget ( path . getTerms ( ) , 0 , node . isProtected ( ) , ! errorIfNotFound ) ; } catch ( InvalidTermException ite ) { throw new EvaluationException ( ite . formatMessage ( path ) ) ; } if ( ! errorIfNotFound || node != null ) { return node ; } else { throw new EvaluationException ( MessageUtils . format ( MSG_NO_VALUE_FOR_PATH , path . toString ( ) ) ) ; } } | Pull the value of an element from a configuration tree . This can either be an absolute relative or external path . | 796 | 22 |
137,709 | public void setLocalVariable ( String name , Term [ ] terms , Element value ) throws EvaluationException { assert ( name != null ) ; // Only truly local variables can be set via this method. Throw an // exception if a global variable is found which matches the name. if ( globalVariables . containsKey ( name ) ) { throw new EvaluationException ( MessageUtils . format ( MSG_CANNOT_MODIFY_GLOBAL_VARIABLE_FROM_DML , name ) ) ; } if ( terms == null || terms . length == 0 ) { // Revert back to the simple case that does not require // dereferencing. setLocalVariable ( name , value ) ; } else { // The more complicated case where we need to dereference the // variable. (And also possibly create the parents.) // Retrieve the value of the local variable. Element var = getLocalVariable ( name ) ; // If the value is a protected resource, then make a shallow copy // and replace the value of the local variable. if ( var != null && var . isProtected ( ) ) { var = var . writableCopy ( ) ; setLocalVariable ( name , var ) ; } // If the value does not exist, create a resource of the correct // type and insert into variable table. if ( var == null || var instanceof Undef ) { Term term = terms [ 0 ] ; if ( term . isKey ( ) ) { var = new HashResource ( ) ; } else { var = new ListResource ( ) ; } setLocalVariable ( name , var ) ; } // Recursively descend to set the value. assert ( var != null ) ; try { var . rput ( terms , 0 , value ) ; } catch ( InvalidTermException ite ) { throw new EvaluationException ( ite . formatVariableMessage ( name , terms ) ) ; } } } | Set the local variable to the given value . If the value is null then the corresponding variable will be removed . If there is a global variable of the same name then an EvaluationException will be thrown . | 398 | 40 |
137,710 | public void execute ( final Object observable , final Runnable change ) { listeners . disableFor ( observable ) ; change . run ( ) ; listeners . enableFor ( observable ) ; } | Executes a change to an observable of the users domain model without generating change commands for this change . | 38 | 20 |
137,711 | protected void executeWithNamedTemplate ( Context context , String name ) throws EvaluationException { assert ( context != null ) ; assert ( name != null ) ; Template template = null ; boolean runStatic = false ; try { template = context . localLoad ( name ) ; if ( template == null ) { template = context . globalLoad ( name ) ; runStatic = true ; } } catch ( EvaluationException ee ) { throw ee . addExceptionInfo ( getSourceRange ( ) , context ) ; } // Check that the template was actually loaded. if ( template == null ) { throw new EvaluationException ( "failed to load template: " + name , getSourceRange ( ) ) ; } TemplateType includeeType = context . getCurrentTemplate ( ) . type ; TemplateType includedType = template . type ; // Check that the template types are correct for the inclusion. if ( ! Template . checkValidInclude ( includeeType , includedType ) ) { throw new EvaluationException ( includeeType + " template cannot include " + includedType + " template" , getSourceRange ( ) ) ; } // Push the template, execute it, then pop it from the stack. // Template loops will be caught by the call depth check when pushing // the template. context . pushTemplate ( template , getSourceRange ( ) , Level . INFO , includedType . toString ( ) ) ; template . execute ( context , runStatic ) ; context . popTemplate ( Level . INFO , includedType . toString ( ) ) ; } | This is a utility method which performs an include from a fixed template name . The validity of the name should be checked by the subclass ; this avoids unnecessary regular expression matching . | 317 | 34 |
137,712 | static private Element runDefaultDml ( Operation dml ) throws SyntaxException { // If the argument is null, return null as the value immediately. if ( dml == null ) { return null ; } // Create a nearly empty execution context. There are no global // variables by default (including no 'SELF' variable). Only the // standard built-in functions are accessible. Context context = new CompileTimeContext ( ) ; Element value = null ; // Execute the DML block. The block must evaluate to an Element. Any // error is fatal for the compilation. try { value = context . executeDmlBlock ( dml ) ; } catch ( EvaluationException consumed ) { value = null ; } return value ; } | can be reused . | 152 | 4 |
137,713 | private String retrieveFromCache ( String url ) { String savedJson ; savedJson = mCacheQueryHandler . get ( getContext ( ) , url ) ; log ( "---------- body found in offline saver : " + savedJson ) ; log ( "----- NO NETWORK : retrieving ends" ) ; return savedJson ; } | Get a saved body for a given url . | 70 | 9 |
137,714 | private Context getContext ( ) { Context context = mContext . get ( ) ; if ( context == null ) { throw new IllegalStateException ( "Context used by the instance has been destroyed." ) ; } return context ; } | Retrieve the context if not yet garbage collected . | 47 | 10 |
137,715 | private Response save ( Response response ) { String jsonBody ; String key = response . request ( ) . url ( ) . toString ( ) ; log ( "----- SAVE FOR OFFLINE : saving starts" ) ; log ( "---------- for request : " + key ) ; log ( "---------- trying to parse response body" ) ; //Try to get response body BufferedReader reader ; StringBuilder sb = new StringBuilder ( ) ; log ( "---------- trying to parse response body" ) ; InputStream bodyStream = response . body ( ) . byteStream ( ) ; InputStreamReader bodyReader = new InputStreamReader ( bodyStream , Charset . forName ( "UTF-8" ) ) ; reader = new BufferedReader ( bodyReader ) ; String line ; try { while ( ( line = reader . readLine ( ) ) != null ) { sb . append ( line ) ; } bodyReader . close ( ) ; bodyReader . close ( ) ; reader . close ( ) ; } catch ( IOException e ) { Log . e ( TAG , "IOException : " + e . getMessage ( ) ) ; } jsonBody = sb . toString ( ) ; log ( "---------- trying to save response body for offline" ) ; mCacheQueryHandler . put ( key , jsonBody ) ; log ( "---------- url : " + key ) ; log ( "---------- body : " + jsonBody ) ; log ( "----- SAVE FOR OFFLINE : saving ends" ) ; return response . newBuilder ( ) . body ( ResponseBody . create ( response . body ( ) . contentType ( ) , jsonBody ) ) . build ( ) ; } | Allow to save the Response body for offline usage . | 352 | 10 |
137,716 | public void destroy ( ) { if ( mIsClosed ) { return ; } if ( mState != STATE_STOPPED ) { mDestroyDelayed = true ; return ; } mIsClosed = true ; PlaybackService . unregisterListener ( getContext ( ) , mInternalListener ) ; mInternalListener = null ; mApplicationContext . clear ( ) ; mApplicationContext = null ; mClientKey = null ; mPlayerPlaylist = null ; mCheerleaderPlayerListeners . clear ( ) ; } | Release resources associated with the player . | 111 | 7 |
137,717 | public void play ( int position ) { checkState ( ) ; ArrayList < SoundCloudTrack > tracks = mPlayerPlaylist . getPlaylist ( ) . getTracks ( ) ; if ( position >= 0 && position < tracks . size ( ) ) { SoundCloudTrack trackToPlay = tracks . get ( position ) ; mPlayerPlaylist . setPlayingTrack ( position ) ; PlaybackService . play ( getContext ( ) , mClientKey , trackToPlay ) ; } } | Play a track at a given position in the player playlist . | 102 | 12 |
137,718 | public void addTrack ( SoundCloudTrack track , boolean playNow ) { checkState ( ) ; mPlayerPlaylist . add ( track ) ; for ( CheerleaderPlaylistListener listener : mCheerleaderPlaylistListeners ) { listener . onTrackAdded ( track ) ; } if ( playNow ) { play ( mPlayerPlaylist . size ( ) - 1 ) ; } } | Add a track to the current SoundCloud player playlist . | 82 | 11 |
137,719 | public void addTracks ( List < SoundCloudTrack > tracks ) { checkState ( ) ; for ( SoundCloudTrack track : tracks ) { addTrack ( track ) ; } } | Add a list of track to thr current SoundCloud player playlist . | 38 | 13 |
137,720 | public void registerPlayerListener ( CheerleaderPlayerListener listener ) { checkState ( ) ; mCheerleaderPlayerListeners . add ( listener ) ; if ( mState == STATE_PLAYING ) { listener . onPlayerPlay ( mPlayerPlaylist . getCurrentTrack ( ) , mPlayerPlaylist . getCurrentTrackIndex ( ) ) ; } else if ( mState == STATE_PAUSED ) { listener . onPlayerPause ( ) ; } } | Register a listener to catch player events . | 97 | 8 |
137,721 | private void initInternalListener ( Context context ) { mInternalListener = new PlaybackListener ( ) { @ Override protected void onPlay ( SoundCloudTrack track ) { super . onPlay ( track ) ; mState = STATE_PLAYING ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onPlayerPlay ( track , mPlayerPlaylist . getCurrentTrackIndex ( ) ) ; } } @ Override protected void onPause ( ) { super . onPause ( ) ; mState = STATE_PAUSED ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onPlayerPause ( ) ; } } @ Override protected void onPlayerDestroyed ( ) { super . onPlayerDestroyed ( ) ; mState = STATE_STOPPED ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onPlayerDestroyed ( ) ; } if ( mDestroyDelayed ) { CheerleaderPlayer . this . destroy ( ) ; } } @ Override protected void onSeekTo ( int milli ) { super . onSeekTo ( milli ) ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onPlayerSeekTo ( milli ) ; } } @ Override protected void onBufferingStarted ( ) { super . onBufferingStarted ( ) ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onBufferingStarted ( ) ; } } @ Override protected void onBufferingEnded ( ) { super . onBufferingEnded ( ) ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onBufferingEnded ( ) ; } } @ Override protected void onProgressChanged ( int milli ) { super . onProgressChanged ( milli ) ; for ( CheerleaderPlayerListener listener : mCheerleaderPlayerListeners ) { listener . onProgressChanged ( milli ) ; } } } ; PlaybackService . registerListener ( context , mInternalListener ) ; } | Initialize the internal listener . | 461 | 6 |
137,722 | public static String getMessageString ( String msgKey ) { assert ( msgKey != null ) ; try { return bundle . getString ( msgKey ) ; } catch ( MissingResourceException mre ) { throw new CompilerError ( mre . getLocalizedMessage ( ) ) ; } catch ( ClassCastException cce ) { throw new CompilerError ( "bundle contains non-string object for key '" + msgKey + "'" ) ; } } | Look up a localized message in the message bundle and return a MessageFormat for it . | 97 | 17 |
137,723 | public static String format ( String msgKey , Object ... args ) { try { return MessageFormat . format ( getMessageString ( msgKey ) , args ) ; } catch ( IllegalArgumentException iae ) { throw new CompilerError ( "bundle contains invalid message format for key '" + msgKey + "'\n" + "error: " + iae . getMessage ( ) ) ; } } | Format a message corresponding to the given key and using the given arguments . | 86 | 14 |
137,724 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) // The alternative would be to change the TopologolyLayerCallback.send() to take List<? extends Command> private void execute ( final ListCommand command ) { getMetaData ( command ) ; final Queue < ListCommand > log = metaData . getUnapprovedCommands ( ) ; if ( log . isEmpty ( ) ) { updateVersion ( command ) ; executeCommand ( command ) ; } else if ( log . peek ( ) . getListVersionChange ( ) . equals ( command . getListVersionChange ( ) ) ) { updateVersion ( command ) ; log . remove ( ) ; } else { // repair indices List < ? extends ListCommand > repairedCommands = indexRepairer . repairCommands ( metaData . getUnapprovedCommands ( ) , command ) ; // repair versions if local commands are left after repairing indices. versionRepairer . repairLocalCommandsVersion ( metaData . getUnapprovedCommands ( ) , command ) ; repairedCommands = versionRepairer . repairRemoteCommandVersion ( repairedCommands , metaData . getUnapprovedCommandsAsList ( ) ) ; // re-send repaired local changes topologyLayerCallback . sendCommands ( ( List ) metaData . getUnapprovedCommandsAsList ( ) ) ; // execute repaired commands for ( final ListCommand repaired : repairedCommands ) { executeCommand ( repaired ) ; } updateVersion ( command ) ; } } | Executes a remotely received command repairs it when necessary and resends repaired versions of local commands that where obsoleted by the received command . | 316 | 28 |
137,725 | public void checkValidReplacement ( Element newValue ) throws EvaluationException { // Only need to check if new values is not undef or null. Undef or null // can replace any value. if ( ! ( newValue instanceof Undef ) && ! ( newValue instanceof Null ) ) { if ( ! this . getClass ( ) . isAssignableFrom ( newValue . getClass ( ) ) ) { throw new EvaluationException ( MessageUtils . format ( MSG_INVALID_REPLACEMENT , this . getTypeAsString ( ) , newValue . getTypeAsString ( ) ) ) ; } } } | Check that the newValue is a valid replacement for the this value . This implementation will check if the newValue is assignable from the current value or that the newValue is either undef or null . If not an evaluation exception will be thrown . This implementation should be overridden if more liberal replacements are allowed . | 134 | 63 |
137,726 | public Element rget ( Term [ ] terms , int index , boolean protect , boolean lookupOnly ) throws InvalidTermException { if ( ! lookupOnly ) { throw new EvaluationException ( MessageUtils . format ( MSG_ILLEGAL_DEREFERENCE , this . getTypeAsString ( ) ) ) ; } return null ; } | Dereference the Element to return the value of a child . Any resource should return the value of the given child . The default implementation of this method will throw an EvaluationException indicating that this Element cannot be dereferenced . | 70 | 46 |
137,727 | public ListResource rgetList ( Term [ ] terms , int index ) throws InvalidTermException { throw new EvaluationException ( MessageUtils . format ( MSG_ILLEGAL_DEREFERENCE , this . getTypeAsString ( ) ) ) ; } | This is a special lookup function that will retrieve a list from the resource . If the resource does not exist an empty list will be created . All necessary parent resources are created . The returned list is guaranteed to be a writable resource . | 54 | 47 |
137,728 | public void rput ( Term [ ] terms , int index , Element value ) throws InvalidTermException { throw new EvaluationException ( MessageUtils . format ( MSG_CANNOT_ADD_CHILD , this . getTypeAsString ( ) ) ) ; } | Add the given child to this resource creating intermediate resources as necessary . If this Element is not a resource then this will throw an InvalidTermException . The default implementation of this method throws such an exception . This resource must be a writable resource otherwise an exception will be thrown . | 54 | 55 |
137,729 | public static void main ( final String ... args ) { System . out . println ( "starting server" ) ; final Model model = new Model ( ) ; final SynchronizeFxServer syncFxServer = SynchronizeFxBuilder . create ( ) . server ( ) . model ( model ) . callback ( new ServerCallback ( ) { @ Override public void onError ( final SynchronizeFXException exception ) { System . err . println ( "Server Error:" + exception . getLocalizedMessage ( ) ) ; } @ Override public void onClientConnectionError ( final Object client , final SynchronizeFXException exception ) { System . err . println ( "An exception in the communication to a client occurred." + exception ) ; } } ) . build ( ) ; syncFxServer . start ( ) ; final Scanner console = new Scanner ( System . in ) ; boolean exit = false ; while ( ! exit ) { System . out . println ( "press 'q' for quit" ) ; final String input = console . next ( ) ; if ( "q" . equals ( input ) ) { exit = true ; } } console . close ( ) ; syncFxServer . shutdown ( ) ; } | The main entry point to the server application . | 257 | 9 |
137,730 | private static void checkNumericIndex ( long index ) { if ( index > Integer . MAX_VALUE ) { throw EvaluationException . create ( MSG_INDEX_EXCEEDS_MAXIMUM , index , Integer . MAX_VALUE ) ; } else if ( index < Integer . MIN_VALUE ) { throw EvaluationException . create ( MSG_INDEX_BELOW_MINIMUM , index , Integer . MIN_VALUE ) ; } } | An internal method to check that a numeric index is valid . It must be a non - negative integer . | 95 | 21 |
137,731 | private static long [ ] checkStringIndex ( String term ) { assert ( term != null ) ; // If second element is < 0, this is a dict key long [ ] result = { 0L , 1L } ; // Empty strings are not allowed. if ( "" . equals ( term ) ) { //$NON-NLS-1$ throw EvaluationException . create ( MSG_KEY_CANNOT_BE_EMPTY_STRING ) ; } if ( isIndexPattern . matcher ( term ) . matches ( ) ) { if ( isIndexLeadingZerosPattern . matcher ( term ) . matches ( ) ) { throw EvaluationException . create ( MSG_INVALID_LEADING_ZEROS_INDEX , term ) ; } else { // This is digits only, so try to convert it to a long. try { result [ 0 ] = Long . decode ( term ) . longValue ( ) ; checkNumericIndex ( result [ 0 ] ) ; } catch ( NumberFormatException nfe ) { throw EvaluationException . create ( MSG_KEY_CANNOT_BEGIN_WITH_DIGIT , term ) ; } } } else if ( isKeyPattern . matcher ( term ) . matches ( ) ) { // Return a negative number to indicate that this is an OK key // value. result [ 1 ] = - 1L ; } else { // Doesn't work for either a key or index. throw EvaluationException . create ( MSG_INVALID_KEY , term ) ; } return result ; } | An internal method to check that a string value is valid . It can either be an Integer or String which is returned . | 326 | 24 |
137,732 | public static Term create ( String term ) { Term res = createStringCache . get ( term ) ; if ( res == null ) { if ( term != null && term . length ( ) >= 2 && term . charAt ( 0 ) == ' ' && term . charAt ( term . length ( ) - 1 ) == ' ' ) { term = EscapeUtils . escape ( term . substring ( 1 , term . length ( ) - 1 ) ) ; } long [ ] value = checkStringIndex ( term ) ; if ( value [ 1 ] < 0L ) { res = ( Term ) StringProperty . getInstance ( term ) ; } else { res = ( Term ) create ( value [ 0 ] ) ; } createStringCache . put ( term , res ) ; } // no clone/copy needed for cached result return res ; } | Constructor of a path from a String . If the path does not have the correct syntax an IllegalArgumentException will be thrown . | 176 | 27 |
137,733 | public static Term create ( long index ) { Term res = createLongCache . get ( index ) ; if ( res == null ) { checkNumericIndex ( index ) ; // Generate a new property. res = ( Term ) LongProperty . getInstance ( index ) ; createLongCache . put ( index , res ) ; return res ; } // no clone/copy needed for cached result return res ; } | Create a term directly from a long index . | 85 | 9 |
137,734 | public static Term create ( Element element ) { if ( element instanceof StringProperty ) { return create ( ( ( StringProperty ) element ) . getValue ( ) ) ; } else if ( element instanceof LongProperty ) { return create ( ( ( LongProperty ) element ) . getValue ( ) . longValue ( ) ) ; } else { throw EvaluationException . create ( MSG_INVALID_ELEMENT_FOR_INDEX , element . getTypeAsString ( ) ) ; } } | Create a term from a given element . | 104 | 8 |
137,735 | public static int compare ( Term self , Term other ) { // Sanity check. if ( self == null || other == null ) { throw new NullPointerException ( ) ; } // Identical objects are always equal. if ( self == other ) { return 0 ; } // Easy case is when they are not the same type of term. if ( self . isKey ( ) != other . isKey ( ) ) { return ( self . isKey ( ) ) ? 1 : - 1 ; } // Compare the underlying values. try { if ( self . isKey ( ) ) { return self . getKey ( ) . compareTo ( other . getKey ( ) ) ; } else { return self . getIndex ( ) . compareTo ( other . getIndex ( ) ) ; } } catch ( InvalidTermException consumed ) { // This statement can never be reached because both objects are // either keys or indexes. This try/catch block is only here to make // the compiler happy. assert ( false ) ; return 0 ; } } | A utility method to allow the comparison of any two terms . | 215 | 12 |
137,736 | public void execute ( final List < Command > commands ) { try { modelWalkingSynchronizer . doWhenModelWalkerFinished ( ActionType . INCOMMING_COMMANDS , new Runnable ( ) { @ Override public void run ( ) { for ( Object command : commands ) { execute ( command ) ; } } } ) ; } catch ( final SynchronizeFXException e ) { topology . onError ( e ) ; } } | Executes commands to change the domain model of the user . | 97 | 12 |
137,737 | public void commandsForDomainModel ( final CommandsForDomainModelCallback callback ) { if ( this . root == null ) { topology . onError ( new SynchronizeFXException ( "Request to create necessary commands to reproduce the domain model " + " but the root object of the domain model is not set." ) ) ; return ; } try { modelWalkingSynchronizer . startModelWalking ( ) ; creator . commandsForDomainModel ( this . root , callback ) ; modelWalkingSynchronizer . finishedModelWalking ( ) ; } catch ( final SynchronizeFXException e ) { topology . onError ( e ) ; } } | This method creates the commands necessary to reproduce the entire domain model . | 137 | 13 |
137,738 | public void shutDown ( ) { synchronized ( channels ) { isCurrentlyShutingDown = true ; for ( final SynchronizeFXWebsocketChannel server : channels . values ( ) ) { server . shutdown ( ) ; } servers . clear ( ) ; channels . clear ( ) ; clients . clear ( ) ; isCurrentlyShutingDown = false ; } } | Shuts down this servers with all its channels and disconnects all remaining clients . | 75 | 16 |
137,739 | public void ensureMinimumBuildThreadLimit ( int minLimit ) { if ( buildThreadLimit . get ( ) < minLimit ) { synchronized ( buildThreadLock ) { buildThreadLimit . set ( minLimit ) ; ThreadPoolExecutor buildExecutor = executors . get ( TaskResult . ResultType . BUILD ) ; // Must set both the maximum and the core limits. If the core is // not set, then the thread pool will not be forced to expand to // the minimum number of threads required. buildExecutor . setMaximumPoolSize ( minLimit ) ; buildExecutor . setCorePoolSize ( minLimit ) ; } } } | Ensures that the number of threads in the build pool is at least as large as the number given . Because object templates can have dependencies on each other it is possible to deadlock the compilation with a rigidly fixed build queue . To avoid this allow the build queue limit to be increased . | 134 | 59 |
137,740 | public synchronized CompilerResults process ( ) { // Create the list to hold all of the exceptions. Set < Throwable > exceptions = new TreeSet < Throwable > ( new ThrowableComparator ( ) ) ; long start = new Date ( ) . getTime ( ) ; stats . setFileCount ( files . size ( ) ) ; // Trigger the compilation of the templates via the template cache. If // no building is going on, then the compile() method is used which // doesn't actually save the templates. This reduces drastically the // memory requirements. if ( options . formatters . size ( ) > 0 ) { for ( File f : files ) { ccache . retrieve ( f . getAbsolutePath ( ) , false ) ; } } else { // FIXME: Determine if this does the correct thing (nothing) for a syntax check. for ( File f : files ) { if ( ! f . isAbsolute ( ) && options . annotationBaseDirectory != null ) { f = new File ( options . annotationBaseDirectory , f . getPath ( ) ) ; } ccache . compile ( f . getAbsolutePath ( ) ) ; } } // Now continually loop through the result queue until we have all // of the results. while ( remainingTasks . get ( ) > 0 ) { try { Future < ? extends TaskResult > future = resultsQueue . take ( ) ; try { stats . incrementFinishedTasks ( future . get ( ) . type ) ; } catch ( ExecutionException ee ) { exceptions . add ( ee . getCause ( ) ) ; } remainingTasks . decrementAndGet ( ) ; stats . updateMemoryInfo ( ) ; } catch ( InterruptedException consumed ) { } } // Shutdown the executors. In certain environments (e.g. eclipse) the // required "modifyThread" permission may not have been granted. Not // having this permission may cause a thread leak. try { SecurityManager security = System . getSecurityManager ( ) ; if ( security != null ) { security . checkPermission ( new RuntimePermission ( "modifyThread" ) ) ; } // We've got the correct permission, so tell all of the executors to // shutdown. for ( TaskResult . ResultType t : TaskResult . ResultType . values ( ) ) { executors . get ( t ) . shutdown ( ) ; } } catch ( SecurityException se ) { // Emit a warning about the missing permission. System . err . println ( "WARNING: missing modifyThread permission" ) ; } // Finalize the statistics. long end = new Date ( ) . getTime ( ) ; stats . setBuildTime ( end - start ) ; return new CompilerResults ( stats , exceptions ) ; } | Process the templates referenced by the CompilerOptions object used to initialize this instance . This will run through the complete compiling building and validation stages as requested . This method should only be invoked once per instance . | 574 | 40 |
137,741 | public void submit ( Task < ? extends TaskResult > task ) { // Increment the counter which indicates the number of results to // expect. This must be done BEFORE actually submitting the task for // execution. remainingTasks . incrementAndGet ( ) ; // Increment the statistics and put the task on the correct queue. stats . incrementStartedTasks ( task . resultType ) ; executors . get ( task . resultType ) . submit ( task ) ; // Make sure that the task gets added to the results queue. resultsQueue . add ( task ) ; stats . updateMemoryInfo ( ) ; } | Submits a task to one of the compiler s task queues for processing . Although public this method should only be called by tasks started by the compiler itself . | 126 | 31 |
137,742 | public static SSLEngine createEngine ( final boolean clientMode ) { if ( context == null ) { context = createContext ( ) ; } SSLEngine engine = context . createSSLEngine ( ) ; engine . setUseClientMode ( clientMode ) ; return engine ; } | Creates a new engine for TLS communication in client or server mode . | 61 | 14 |
137,743 | public void readChild ( Element element , PrintWriter ps , int level , String name ) { String nbTab = tabMaker ( level ) ; if ( element instanceof Resource ) { Resource resource = ( Resource ) element ; writeBegin ( ps , nbTab , name , level , element . getTypeAsString ( ) ) ; for ( Resource . Entry entry : resource ) { Property key = entry . getKey ( ) ; Element value = entry . getValue ( ) ; level ++ ; readChild ( value , ps , level , key . toString ( ) ) ; level -- ; } writeEnd ( ps , nbTab , element . getTypeAsString ( ) ) ; } else { Property elem = ( Property ) element ; writeProperties ( ps , nbTab , name , element . getTypeAsString ( ) , elem . toString ( ) ) ; } } | Reads each child . | 186 | 5 |
137,744 | public String tabMaker ( int n ) { StringBuilder buf = new StringBuilder ( "" ) ; for ( int i = 1 ; i <= n ; i ++ ) { buf . append ( " " ) ; } String tab = buf . toString ( ) ; return tab ; } | Calculates the number of tabulations to write at the beginning of a line | 58 | 16 |
137,745 | public Element put ( String name , Element value ) { assert ( name != null ) ; Element oldValue = null ; if ( value != null ) { // Set the value and ensure that the replacement can be done. oldValue = map . put ( name , value ) ; if ( oldValue != null ) { oldValue . checkValidReplacement ( value ) ; } } else { // Remove the referenced variable. oldValue = map . remove ( name ) ; } return oldValue ; } | Assign the value to the given variable name . If the value is null then the variable is undefined . If an old value existed then this method will check that the new value is a valid replacement for the old one . If not an exception will be thrown . | 101 | 52 |
137,746 | private boolean checkField ( EditText editText ) { boolean valid = true ; if ( TextUtils . isEmpty ( editText . getText ( ) ) ) { editText . startAnimation ( mWiggle ) ; editText . requestFocus ( ) ; valid = false ; } return valid ; } | Check if the edit text is valid or not . | 63 | 10 |
137,747 | public Element put ( int index , Element newValue ) { Element oldValue = null ; int size = list . size ( ) ; if ( index < 0 ) { if ( index < - size ) { // negative indices do not auto-prepend // (asopposed to positive ones that grow the list by appending undef) throw new EvaluationException ( MessageUtils . format ( MSG_INVALID_NEGATIVE_LIST_INDEX , Integer . toString ( index ) , size ) ) ; } else { index += size ; } } try { if ( ( newValue != null ) && ! ( newValue instanceof Null ) ) { if ( index >= size ) { for ( int i = 0 ; i < index - size ; i ++ ) { list . add ( Undef . VALUE ) ; } list . add ( newValue ) ; } else { oldValue = list . set ( index , newValue ) ; if ( oldValue != null ) { oldValue . checkValidReplacement ( newValue ) ; } } } else { try { oldValue = list . remove ( index ) ; } catch ( IndexOutOfBoundsException ioobe ) { // Ignore this error; removing non-existant element is OK. } } } catch ( IndexOutOfBoundsException ioobe ) { throw new EvaluationException ( MessageUtils . format ( MSG_NONEXISTANT_LIST_ELEMENT , Integer . toString ( index ) ) ) ; } return oldValue ; } | This is an optimized version of the put method which doesn t require creating a Term object . | 317 | 18 |
137,748 | public SoundCloudTrack getCurrentTrack ( ) { if ( mCurrentTrackIndex > - 1 && mCurrentTrackIndex < mSoundCloudPlaylist . getTracks ( ) . size ( ) ) { return mSoundCloudPlaylist . getTracks ( ) . get ( mCurrentTrackIndex ) ; } return null ; } | Return the current track . | 68 | 5 |
137,749 | public void addAll ( List < SoundCloudTrack > tracks ) { for ( SoundCloudTrack track : tracks ) { add ( mSoundCloudPlaylist . getTracks ( ) . size ( ) , track ) ; } } | Add all tracks at the end of the playlist . | 47 | 10 |
137,750 | public void add ( int position , SoundCloudTrack track ) { if ( mCurrentTrackIndex == - 1 ) { mCurrentTrackIndex = 0 ; } mSoundCloudPlaylist . addTrack ( position , track ) ; } | Add a track to the given position . | 47 | 8 |
137,751 | public SoundCloudTrack next ( ) { mCurrentTrackIndex = ( mCurrentTrackIndex + 1 ) % mSoundCloudPlaylist . getTracks ( ) . size ( ) ; return mSoundCloudPlaylist . getTracks ( ) . get ( mCurrentTrackIndex ) ; } | Retrieve the next track . | 60 | 6 |
137,752 | public SoundCloudTrack previous ( ) { int tracks = mSoundCloudPlaylist . getTracks ( ) . size ( ) ; mCurrentTrackIndex = ( tracks + mCurrentTrackIndex - 1 ) % tracks ; return mSoundCloudPlaylist . getTracks ( ) . get ( mCurrentTrackIndex ) ; } | Retrieve the previous track . | 67 | 6 |
137,753 | void setPlayingTrack ( int playingTrackPosition ) { if ( playingTrackPosition < 0 || playingTrackPosition >= mSoundCloudPlaylist . getTracks ( ) . size ( ) ) { throw new IllegalArgumentException ( "No tracks a the position " + playingTrackPosition ) ; } mCurrentTrackIndex = playingTrackPosition ; } | Allow to set the current playing song index . private package . | 71 | 12 |
137,754 | protected String getChannelName ( final HttpServletRequest request ) { final String path = request . getPathInfo ( ) ; return path == null ? "" : path . startsWith ( "/" ) ? path . substring ( 1 ) : path ; } | Extracts the name of the channel the client that invoked a request wants to connect to . | 54 | 19 |
137,755 | @ Override public void destroy ( ) { synchronized ( channels ) { isCurrentlyShutingDown = true ; for ( final SynchronizeFXTomcatChannel server : channels . values ( ) ) { server . shutdown ( ) ; } servers . clear ( ) ; channels . clear ( ) ; isCurrentlyShutingDown = false ; } } | Disconnect all clients an clear the connections when the handler is destroyed by CDI . | 70 | 17 |
137,756 | public < T > void registerSerializableClass ( final Class < T > clazz , final Serializer < T > serializer ) { kryo . registerSerializableClass ( clazz , serializer ) ; } | Registers a class that may be send over the network . | 45 | 12 |
137,757 | public static NotificationManager getInstance ( Context context ) { if ( sInstance == null ) { sInstance = new NotificationManager ( context ) ; } return sInstance ; } | Encapsulate player notification behaviour . | 35 | 7 |
137,758 | private void initializeArtworkTarget ( ) { mThumbnailArtworkTarget = new Target ( ) { @ Override public void onBitmapLoaded ( Bitmap bitmap , Picasso . LoadedFrom from ) { mNotificationView . setImageViewBitmap ( R . id . simple_sound_cloud_notification_thumbnail , bitmap ) ; mNotificationExpandedView . setImageViewBitmap ( R . id . simple_sound_cloud_notification_thumbnail , bitmap ) ; mNotificationManager . notify ( NOTIFICATION_ID , buildNotification ( ) ) ; } @ Override public void onBitmapFailed ( Drawable errorDrawable ) { } @ Override public void onPrepareLoad ( Drawable placeHolderDrawable ) { } } ; } | Initialize target used to load artwork asynchronously . | 171 | 11 |
137,759 | private void initNotificationBuilder ( Context context ) { // inti builder. mNotificationBuilder = new NotificationCompat . Builder ( context ) ; mNotificationView = new RemoteViews ( context . getPackageName ( ) , R . layout . simple_sound_cloud_notification ) ; mNotificationExpandedView = new RemoteViews ( context . getPackageName ( ) , R . layout . simple_sound_cloud_notification_expanded ) ; // add right icon on Lollipop. if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { addSmallIcon ( mNotificationView ) ; addSmallIcon ( mNotificationExpandedView ) ; } // set pending intents mNotificationView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_previous , mPreviousPendingIntent ) ; mNotificationExpandedView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_previous , mPreviousPendingIntent ) ; mNotificationView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_next , mNextPendingIntent ) ; mNotificationExpandedView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_next , mNextPendingIntent ) ; mNotificationView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_play , mTogglePlaybackPendingIntent ) ; mNotificationExpandedView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_play , mTogglePlaybackPendingIntent ) ; mNotificationView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_clear , mClearPendingIntent ) ; mNotificationExpandedView . setOnClickPendingIntent ( R . id . simple_sound_cloud_notification_clear , mClearPendingIntent ) ; // add icon for action bar. mNotificationBuilder . setSmallIcon ( mNotificationConfig . getNotificationIcon ( ) ) ; // set the remote view. mNotificationBuilder . setContent ( mNotificationView ) ; // set the notification priority. mNotificationBuilder . setPriority ( NotificationCompat . PRIORITY_HIGH ) ; mNotificationBuilder . setStyle ( new NotificationCompat . DecoratedCustomViewStyle ( ) ) ; // set the content intent. Class < ? > playerActivity = mNotificationConfig . getNotificationActivity ( ) ; if ( playerActivity != null ) { Intent i = new Intent ( context , playerActivity ) ; PendingIntent contentIntent = PendingIntent . getActivity ( context , REQUEST_DISPLAYING_CONTROLLER , i , PendingIntent . FLAG_UPDATE_CURRENT ) ; mNotificationBuilder . setContentIntent ( contentIntent ) ; } } | Init all static components of the notification . | 671 | 8 |
137,760 | private void addSmallIcon ( RemoteViews notificationView ) { notificationView . setInt ( R . id . simple_sound_cloud_notification_icon , "setBackgroundResource" , mNotificationConfig . getNotificationIconBackground ( ) ) ; notificationView . setImageViewResource ( R . id . simple_sound_cloud_notification_icon , mNotificationConfig . getNotificationIcon ( ) ) ; } | Add the small right icon for Lollipop device . | 91 | 10 |
137,761 | static public boolean isValidTemplateName ( String name ) { // First do the easy check to make sure that the string isn't empty and // contains only valid characters. if ( ! validTemplateNameChars . matcher ( name ) . matches ( ) ) { return false ; } // Split the string on slashes and ensure that each one of the terms is // valid. Cannot be empty or start with a period. (Above check already // guarantees that only allowed characters are in the string.) for ( String t : name . split ( "/" ) ) { if ( "" . equals ( t ) || t . startsWith ( "." ) ) { return false ; } } // If we make it to this point, then the string has passed all of the // checks and is valid. return true ; } | Check to see if the given name is a valid template name . Valid template names may include only letters digits underscores hyphens periods pluses and slashes . In addition each term when split by slashes must not be empty and must not start with a period . The second case excludes potential hidden files and special names like . and .. . | 166 | 67 |
137,762 | public Object execute ( Context context , boolean runStatic ) { for ( Statement s : ( ( runStatic ) ? staticStatements : normalStatements ) ) { s . execute ( context ) ; } return null ; } | Execute each of the statements in turn . | 45 | 9 |
137,763 | public static boolean checkValidInclude ( TemplateType includeeType , TemplateType includedType ) { return allowedIncludes [ includeeType . ordinal ( ) ] [ includedType . ordinal ( ) ] ; } | Determine whether a particular include combination is legal . | 44 | 11 |
137,764 | public void templateNameVerification ( String expectedName ) throws SyntaxException { if ( ! name . equals ( expectedName ) ) { throw SyntaxException . create ( null , source , MSG_MISNAMED_TPL , expectedName ) ; } } | Check that the internal template name matches the expected template name . | 56 | 12 |
137,765 | public Observable < ArrayList < SoundCloudTrack > > getArtistTracks ( ) { checkState ( ) ; if ( mCacheRam . tracks . size ( ) != 0 ) { return Observable . create ( new Observable . OnSubscribe < ArrayList < SoundCloudTrack > > ( ) { @ Override public void call ( Subscriber < ? super ArrayList < SoundCloudTrack > > subscriber ) { subscriber . onNext ( mCacheRam . tracks ) ; subscriber . onCompleted ( ) ; } } ) ; } else { return mRetrofitService . getUserTracks ( mArtistName ) . map ( RxParser . PARSE_USER_TRACKS ) . map ( cacheTracks ( ) ) ; } } | Retrieve the public tracks of the supported artist . | 156 | 10 |
137,766 | public Observable < SoundCloudUser > getArtistProfile ( ) { checkState ( ) ; if ( mCacheRam . artistProfile != null ) { return Observable . create ( new Observable . OnSubscribe < SoundCloudUser > ( ) { @ Override public void call ( Subscriber < ? super SoundCloudUser > subscriber ) { subscriber . onNext ( mCacheRam . artistProfile ) ; subscriber . onCompleted ( ) ; } } ) ; } else { return mRetrofitService . getUser ( mArtistName ) . map ( RxParser . PARSE_USER ) . map ( cacheArtistProfile ( ) ) ; } } | Retrieve SoundCloud artist profile . | 135 | 7 |
137,767 | public Observable < ArrayList < SoundCloudComment > > getTrackComments ( final SoundCloudTrack track ) { checkState ( ) ; if ( mCacheRam . tracksComments . get ( track . getId ( ) ) != null ) { return Observable . create ( new Observable . OnSubscribe < ArrayList < SoundCloudComment > > ( ) { @ Override public void call ( Subscriber < ? super ArrayList < SoundCloudComment > > subscriber ) { subscriber . onNext ( mCacheRam . tracksComments . get ( track . getId ( ) ) ) ; subscriber . onCompleted ( ) ; } } ) ; } else { return mRetrofitService . getTrackComments ( track . getId ( ) ) . map ( RxParser . PARSE_COMMENTS ) . map ( cacheTrackComments ( ) ) ; } } | Retrieve comments related to a track of the supported artist . | 177 | 12 |
137,768 | private Func1 < SoundCloudUser , SoundCloudUser > cacheArtistProfile ( ) { return new Func1 < SoundCloudUser , SoundCloudUser > ( ) { @ Override public SoundCloudUser call ( SoundCloudUser soundCloudUser ) { mCacheRam . artistProfile = soundCloudUser ; return soundCloudUser ; } } ; } | Cache the artist profile retrieved from network in RAM to avoid requesting SoundCloud API for next call . | 73 | 19 |
137,769 | private Func1 < ArrayList < SoundCloudComment > , ArrayList < SoundCloudComment > > cacheTrackComments ( ) { return new Func1 < ArrayList < SoundCloudComment > , ArrayList < SoundCloudComment > > ( ) { @ Override public ArrayList < SoundCloudComment > call ( ArrayList < SoundCloudComment > trackComments ) { if ( trackComments . size ( ) > 0 ) { mCacheRam . tracksComments . put ( trackComments . get ( 0 ) . getTrackId ( ) , trackComments ) ; } return trackComments ; } } ; } | Cache the comments linked to a track retrieved from network in RAM to avoid requesting SoundCloud API for next call . | 124 | 22 |
137,770 | private Func1 < ArrayList < SoundCloudTrack > , ArrayList < SoundCloudTrack > > cacheTracks ( ) { return new Func1 < ArrayList < SoundCloudTrack > , ArrayList < SoundCloudTrack > > ( ) { @ Override public ArrayList < SoundCloudTrack > call ( ArrayList < SoundCloudTrack > soundCloudTracks ) { if ( soundCloudTracks . size ( ) > 0 ) { mCacheRam . tracks = soundCloudTracks ; } return soundCloudTracks ; } } ; } | Cache the tracks list of the supported artist retrieved from network in RAM to avoid requesting SoundCloud API for next call . | 114 | 23 |
137,771 | protected Term [ ] calculateTerms ( Context context ) throws EvaluationException { Term [ ] terms = new Term [ ops . length ] ; for ( int i = 0 ; i < ops . length ; i ++ ) { terms [ i ] = TermFactory . create ( ops [ i ] . execute ( context ) ) ; } return terms ; } | A utility method that creates a list of terms from the given arguments . | 71 | 14 |
137,772 | public void cleanReferenceCache ( ) { final long now = currentDateSupplier . get ( ) . getTime ( ) ; final Iterator < HardReference > it = hardReferences . iterator ( ) ; while ( it . hasNext ( ) ) { if ( it . next ( ) . keeptSince . getTime ( ) + REFERENCE_KEEPING_TIME <= now ) { it . remove ( ) ; } } } | Checks and cleans cached references that have timed out . | 91 | 11 |
137,773 | Iterable < Object > getHardReferences ( ) { final List < Object > references = new ArrayList < Object > ( hardReferences . size ( ) ) ; for ( final HardReference reference : hardReferences ) { references . add ( reference . referenceToKeep ) ; } return references ; } | The list of all references that are currently kept . | 60 | 10 |
137,774 | @ Override public Element execute ( Context context ) { assert ( ops . length == 2 || ops . length == 3 ) ; // Pop the condition from the data stack. boolean condition = false ; try { condition = ( ( BooleanProperty ) ops [ 0 ] . execute ( context ) ) . getValue ( ) ; } catch ( ClassCastException cce ) { throw new EvaluationException ( MessageUtils . format ( MSG_INVALID_IF_ELSE_TEST ) , sourceRange ) ; } // Choose the correct operation and execute it. Operation op = null ; if ( condition ) { op = ops [ 1 ] ; } else if ( ops . length > 2 ) { op = ops [ 2 ] ; } else { op = Undef . VALUE ; } return op . execute ( context ) ; } | Perform the if statement . It will pop a boolean from the data stack . If that boolean is false the next operand if popped from the operand stack ; if true nothing is done . | 171 | 39 |
137,775 | @ Override public void stop ( ) { System . out . print ( "Stopping the client..." ) ; client . disconnect ( ) ; System . out . println ( "done" ) ; } | Disconnect the client when the application is closed . | 41 | 10 |
137,776 | public static DeprecationWarnings getDeprecationWarnings ( int deprecationLevel , boolean failOnWarn ) { if ( deprecationLevel < 0 ) { return DeprecationWarnings . OFF ; } else { return failOnWarn ? DeprecationWarnings . FATAL : DeprecationWarnings . ON ; } } | Utility method to turn old options into new deprecation flag . | 79 | 14 |
137,777 | public static CompilerOptions createCheckSyntaxOptions ( DeprecationWarnings deprecationWarnings ) { Pattern debugNsInclude = null ; Pattern debugNsExclude = null ; int maxIteration = 5000 ; int maxRecursion = 50 ; Set < Formatter > formatters = new HashSet < Formatter > ( ) ; File outputDirectory = null ; File annotationDirectory = null ; File annotationBaseDirectory = null ; LinkedList < File > includeDirectories = new LinkedList < File > ( ) ; try { return new CompilerOptions ( debugNsInclude , debugNsExclude , maxIteration , maxRecursion , formatters , outputDirectory , includeDirectories , deprecationWarnings , annotationDirectory , annotationBaseDirectory , null , 0 ) ; } catch ( SyntaxException consumed ) { throw CompilerError . create ( MSG_FILE_BUG_REPORT ) ; } } | Create a CompilerOptions object that is appropriate for just doing a syntax check . | 195 | 16 |
137,778 | private void checkDirectory ( File d , String dtype ) { if ( ! d . isAbsolute ( ) ) { throw new IllegalArgumentException ( dtype + " directory must be an absolute path (" + d . getPath ( ) + ")" ) ; } if ( ! d . exists ( ) ) { throw new IllegalArgumentException ( dtype + " directory does not exist (" + d . getPath ( ) + ")" ) ; } if ( ! d . isDirectory ( ) ) { throw new IllegalArgumentException ( dtype + " directory value is not a directory (" + d . getPath ( ) + ")" ) ; } } | A private utility function to verify that the directory is really a directory exists and absolute . | 138 | 17 |
137,779 | public Set < File > resolveFileList ( List < String > objectNames , Collection < File > tplFiles ) { // First just copy the named templates. Set < File > filesToProcess = new TreeSet < File > ( ) ; if ( tplFiles != null ) { filesToProcess . addAll ( tplFiles ) ; } // Now loop over all of the object template names, lookup the files, and // add them to the set of files to process. if ( objectNames != null ) { for ( String oname : objectNames ) { SourceFile source = sourceRepository . retrievePanSource ( oname ) ; if ( ! source . isAbsent ( ) ) { filesToProcess . add ( source . getPath ( ) ) ; } else { throw EvaluationException . create ( ( SourceRange ) null , ( Context ) null , MSG_CANNOT_LOCATE_OBJECT_TEMPLATE , oname ) ; } } } return Collections . unmodifiableSet ( filesToProcess ) ; } | Resolve a list of object template names and template Files to a set of files based on this instance s include directories . | 216 | 24 |
137,780 | public boolean checkDebugEnabled ( String tplName ) { // Check first the exclude patterns. Any matching pattern in the exclude // list means that the debugging is disabled for the given template. if ( debugNsExclude != null && debugNsExclude . matcher ( tplName ) . matches ( ) ) { return false ; } // Now check the include patterns. Any matching pattern here means that // the debugging for this template is enabled. if ( debugNsInclude != null && debugNsInclude . matcher ( tplName ) . matches ( ) ) { return true ; } // If we get here, then the template didn't match anything. By default, // the debugging is turned off. return false ; } | A utility function that checks a given template name against the list of debug include and exclude patterns . | 150 | 19 |
137,781 | public static Set < Formatter > getFormatters ( String s ) { HashSet < Formatter > formatters = new HashSet < Formatter > ( ) ; String [ ] names = s . trim ( ) . split ( "\\s*,\\s*" ) ; for ( String fname : names ) { if ( "text" . equals ( fname ) ) { formatters . add ( TxtFormatter . getInstance ( ) ) ; } else if ( "json" . equals ( fname ) ) { formatters . add ( JsonFormatter . getInstance ( ) ) ; } else if ( "json.gz" . equals ( fname ) ) { formatters . add ( JsonGzipFormatter . getInstance ( ) ) ; } else if ( "dot" . equals ( fname ) ) { formatters . add ( DotFormatter . getInstance ( ) ) ; } else if ( "pan" . equals ( fname ) ) { formatters . add ( PanFormatter . getInstance ( ) ) ; } else if ( "pan.gz" . equals ( fname ) ) { formatters . add ( PanGzipFormatter . getInstance ( ) ) ; } else if ( "xml" . equals ( fname ) ) { formatters . add ( XmlFormatter . getInstance ( ) ) ; } else if ( "xml.gz" . equals ( fname ) ) { formatters . add ( XmlGzipFormatter . getInstance ( ) ) ; } else if ( "dep" . equals ( fname ) ) { formatters . add ( DepFormatter . getInstance ( ) ) ; } else if ( "dep.gz" . equals ( fname ) ) { formatters . add ( DepGzipFormatter . getInstance ( ) ) ; } else if ( "null" . equals ( fname ) ) { formatters . add ( NullFormatter . getInstance ( ) ) ; } else if ( "none" . equals ( fname ) ) { // No-op } } return formatters ; } | be used for a compilation . | 441 | 6 |
137,782 | public static void startActivity ( Context context , String artistName ) { Intent i = new Intent ( context , ArtistActivity . class ) ; i . putExtra ( BUNDLE_KEY_ARTIST_NAME , artistName ) ; context . startActivity ( i ) ; } | Start an ArtistActivity for a given artist name . Start activity pattern . | 58 | 14 |
137,783 | private void setTrackListPadding ( ) { mPlaylistRecyclerView . getViewTreeObserver ( ) . addOnPreDrawListener ( new ViewTreeObserver . OnPreDrawListener ( ) { @ Override public boolean onPreDraw ( ) { mPlaylistRecyclerView . getViewTreeObserver ( ) . removeOnPreDrawListener ( this ) ; int headerListHeight = getResources ( ) . getDimensionPixelOffset ( R . dimen . playback_view_height ) ; mPlaylistRecyclerView . setPadding ( 0 , mPlaylistRecyclerView . getHeight ( ) - headerListHeight , 0 , 0 ) ; mPlaylistRecyclerView . setAdapter ( mPlaylistAdapter ) ; // attach the dismiss gesture. new SwipeToDismissGesture . Builder ( SwipeToDismissDirection . HORIZONTAL ) . on ( mPlaylistRecyclerView ) . apply ( new DismissStrategy ( ) ) . backgroundColor ( getResources ( ) . getColor ( R . color . grey ) ) . build ( ) ; // hide if current play playlist is empty. if ( mPlaylistTracks . isEmpty ( ) ) { mPlaybackView . setTranslationY ( headerListHeight ) ; } return true ; } } ) ; } | Used to position the track list at the bottom of the screen . | 287 | 13 |
137,784 | private void getArtistData ( ) { mRetrievedTracks . clear ( ) ; mAdapter . notifyDataSetChanged ( ) ; mTracksSubscription = mCheerleaderClient . getArtistTracks ( ) . subscribeOn ( Schedulers . io ( ) ) . observeOn ( AndroidSchedulers . mainThread ( ) ) . subscribe ( displayTracks ( ) ) ; mProfileSubscription = mCheerleaderClient . getArtistProfile ( ) . observeOn ( AndroidSchedulers . mainThread ( ) ) . subscribeOn ( Schedulers . io ( ) ) . subscribe ( displayArtist ( ) ) ; } | Used to retrieved the tracks of the artist as well as artist details . | 136 | 14 |
137,785 | private String getExtraArtistName ( ) { Bundle extras = getIntent ( ) . getExtras ( ) ; if ( extras == null || ! extras . containsKey ( BUNDLE_KEY_ARTIST_NAME ) ) { return "" ; // activity started through the notification pending intent } return extras . getString ( BUNDLE_KEY_ARTIST_NAME ) ; } | Used to retrieve the artist name for the bundle . | 82 | 10 |
137,786 | void newMessage ( final byte [ ] message , final Session session ) { callback . recive ( serializer . deserialize ( message ) , session ) ; } | Inform this channel that one of its client has send a message . | 34 | 14 |
137,787 | public void startModelWalking ( ) { doWhenModelWalkerFinished ( ActionType . MODEL_WALKNG , new Runnable ( ) { @ Override public void run ( ) { memberLock . lock ( ) ; modelWalkingInProgess = true ; memberLock . unlock ( ) ; } } ) ; } | Informs this synchronizer that a new model walking process has started . | 71 | 14 |
137,788 | public void doWhenModelWalkerFinished ( final ActionType type , final Runnable action ) { memberLock . lock ( ) ; if ( ! modelWalkingInProgess ) { memberLock . unlock ( ) ; action . run ( ) ; return ; } CountDownLatch latch = new CountDownLatch ( 1 ) ; Set < CountDownLatch > latches = getLocksForAction ( type ) ; latches . add ( latch ) ; // FIXME There may be a race condition between the following unlock and lock. memberLock . unlock ( ) ; awaitUninterupptetly ( latch ) ; action . run ( ) ; memberLock . lock ( ) ; latches . remove ( latch ) ; runNext ( ) ; memberLock . unlock ( ) ; } | Lets the current thread sleep until a currently running model walking thread has finished . | 166 | 16 |
137,789 | public static void pause ( Context context , String clientId ) { Intent intent = new Intent ( context , PlaybackService . class ) ; intent . setAction ( ACTION_PAUSE_PLAYER ) ; intent . putExtra ( BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID , clientId ) ; context . startService ( intent ) ; } | Pause the SoundCloud player . | 79 | 6 |
137,790 | public static void resume ( Context context , String clientId ) { Intent intent = new Intent ( context , PlaybackService . class ) ; intent . setAction ( ACTION_RESUME_PLAYER ) ; intent . putExtra ( BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID , clientId ) ; context . startService ( intent ) ; } | Resume the SoundCloud player . | 79 | 7 |
137,791 | public static void stop ( Context context , String clientId ) { Intent intent = new Intent ( context , PlaybackService . class ) ; intent . setAction ( ACTION_STOP_PLAYER ) ; intent . putExtra ( BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID , clientId ) ; context . startService ( intent ) ; } | Stop the SoundCloud player . | 79 | 6 |
137,792 | public static void registerListener ( Context context , PlaybackListener listener ) { IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( PlaybackListener . ACTION_ON_TRACK_PLAYED ) ; filter . addAction ( PlaybackListener . ACTION_ON_PLAYER_PAUSED ) ; filter . addAction ( PlaybackListener . ACTION_ON_SEEK_COMPLETE ) ; filter . addAction ( PlaybackListener . ACTION_ON_PLAYER_DESTROYED ) ; filter . addAction ( PlaybackListener . ACTION_ON_BUFFERING_STARTED ) ; filter . addAction ( PlaybackListener . ACTION_ON_BUFFERING_ENDED ) ; filter . addAction ( PlaybackListener . ACTION_ON_PROGRESS_CHANGED ) ; LocalBroadcastManager . getInstance ( context . getApplicationContext ( ) ) . registerReceiver ( listener , filter ) ; } | Register a listener to catch player event . | 199 | 8 |
137,793 | public static void unregisterListener ( Context context , PlaybackListener listener ) { LocalBroadcastManager . getInstance ( context . getApplicationContext ( ) ) . unregisterReceiver ( listener ) ; } | Unregister a registered listener . | 42 | 6 |
137,794 | private void resume ( ) { if ( mIsPaused ) { mIsPaused = false ; mIsPausedAfterAudioFocusChanged = false ; // Try to gain the audio focus before preparing and starting the media player. if ( mAudioManager . requestAudioFocus ( this , AudioManager . STREAM_MUSIC , AudioManager . AUDIOFOCUS_GAIN ) == AudioManager . AUDIOFOCUS_REQUEST_GRANTED ) { mMediaPlayer . start ( ) ; Intent intent = new Intent ( PlaybackListener . ACTION_ON_TRACK_PLAYED ) ; intent . putExtra ( PlaybackListener . EXTRA_KEY_TRACK , mPlayerPlaylist . getCurrentTrack ( ) ) ; mLocalBroadcastManager . sendBroadcast ( intent ) ; updateNotification ( ) ; mMediaSession . setPlaybackState ( MediaSessionWrapper . PLAYBACK_STATE_PLAYING ) ; resumeTimer ( ) ; } } } | Resume the playback . | 207 | 5 |
137,795 | private void startTimer ( long duration ) { if ( mCountDown != null ) { mCountDown . cancel ( ) ; mCountDown = null ; } // refresh progress every seconds. mCountDown = new CountDownTimer ( duration , 1000 ) { @ Override public void onTick ( long millisUntilFinished ) { Intent i = new Intent ( PlaybackListener . ACTION_ON_PROGRESS_CHANGED ) ; i . putExtra ( PlaybackListener . EXTRA_KEY_CURRENT_TIME , mMediaPlayer . getCurrentPosition ( ) ) ; mLocalBroadcastManager . sendBroadcast ( i ) ; } @ Override public void onFinish ( ) { Intent i = new Intent ( PlaybackListener . ACTION_ON_PROGRESS_CHANGED ) ; i . putExtra ( PlaybackListener . EXTRA_KEY_CURRENT_TIME , ( int ) mPlayerPlaylist . getCurrentTrack ( ) . getDurationInMilli ( ) ) ; mLocalBroadcastManager . sendBroadcast ( i ) ; } } ; mCountDown . start ( ) ; } | Start internal timer used to propagate the playback position . | 237 | 10 |
137,796 | private void readObject ( java . io . ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; hashcode = value . hashCode ( ) ; } | This method is used to restore the volatile hashcode value when deserializing a Property object . | 42 | 19 |
137,797 | public UUID registerIfUnknown ( final Object object ) { final Optional < UUID > id = getId ( object ) ; if ( ! id . isPresent ( ) ) { return registerObject ( object ) ; } return id . get ( ) ; } | Registers an object in the meta model if it is not already registered . | 53 | 15 |
137,798 | public void registerObject ( final Object object , final UUID id ) { objectToId . put ( object , id ) ; idToObject . put ( id , object ) ; } | Registers an object in this model identified by a pre existing id . | 38 | 14 |
137,799 | private UUID registerObject ( final Object object ) { UUID id = UUID . randomUUID ( ) ; registerObject ( object , id ) ; return id ; } | Registers an object in this model identified by a newly created id . | 36 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.