idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
33,400 | private void resizeIfNeeded ( ) { int oldRenderWidth = Display . getWidth ( ) ; int oldRenderHeight = Display . getHeight ( ) ; if ( this . renderWidth == oldRenderWidth && this . renderHeight == oldRenderHeight ) return ; try { int old_x = Display . getX ( ) ; int old_y = Display . getY ( ) ; Display . setLocation ( old_x , old_y ) ; Display . setDisplayMode ( new DisplayMode ( this . renderWidth , this . renderHeight ) ) ; System . out . println ( "Resized the window" ) ; } catch ( LWJGLException e ) { System . out . println ( "Failed to resize the window!" ) ; e . printStackTrace ( ) ; } forceResize ( this . renderWidth , this . renderHeight ) ; } | Resizes the window and the Minecraft rendering if necessary . Set renderWidth and renderHeight first . |
33,401 | public void stop ( MissionDiagnostics diags ) { if ( ! this . isRunning ) { return ; } if ( this . videoProducer != null ) this . videoProducer . cleanup ( ) ; try { MinecraftForge . EVENT_BUS . unregister ( this ) ; } catch ( Exception e ) { System . out . println ( "Failed to unregister video hook: " + e ) ; } this . connection . close ( ) ; this . isRunning = false ; Display . setResizable ( true ) ; if ( diags != null ) { VideoData vd = new VideoData ( ) ; vd . setFrameType ( this . videoProducer . getVideoType ( ) . toString ( ) ) ; vd . setFramesSent ( ( int ) this . framesSent ) ; if ( this . timeOfLastFrame == this . timeOfFirstFrame ) vd . setAverageFpsSent ( new BigDecimal ( 0 ) ) ; else vd . setAverageFpsSent ( new BigDecimal ( 1000.0 * this . framesSent / ( this . timeOfLastFrame - this . timeOfFirstFrame ) ) ) ; diags . getVideoData ( ) . add ( vd ) ; } } | Stop sending video . |
33,402 | private void forceResize ( int width , int height ) { boolean devEnv = ( Boolean ) Launch . blackboard . get ( "fml.deobfuscatedEnvironment" ) ; String resizeMethodName = devEnv ? "resize" : "func_71370_a" ; Class [ ] cArgs = new Class [ 2 ] ; cArgs [ 0 ] = int . class ; cArgs [ 1 ] = int . class ; Method resize ; try { resize = Minecraft . class . getDeclaredMethod ( resizeMethodName , cArgs ) ; resize . setAccessible ( true ) ; resize . invoke ( Minecraft . getMinecraft ( ) , width , height ) ; } catch ( NoSuchMethodException e ) { e . printStackTrace ( ) ; } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } | Force Minecraft to resize its GUI |
33,403 | public static IBlockState ParseBlockType ( String s ) { if ( s == null ) return null ; Block block = ( Block ) Block . REGISTRY . getObject ( new ResourceLocation ( s ) ) ; if ( block instanceof BlockAir && ! s . equals ( "air" ) ) return null ; return block . getDefaultState ( ) ; } | Attempts to parse the block type string . |
33,404 | public static Item ParseItemType ( String s , boolean checkBlocks ) { if ( s == null ) return null ; Item item = ( Item ) Item . REGISTRY . getObject ( new ResourceLocation ( s ) ) ; if ( item == null && checkBlocks ) { IBlockState block = MinecraftTypeHelper . ParseBlockType ( s ) ; item = ( block != null && block . getBlock ( ) != null ) ? Item . getItemFromBlock ( block . getBlock ( ) ) : null ; } return item ; } | Attempts to parse the item type string . |
33,405 | public static boolean blockColourMatches ( IBlockState bs , List < Colour > allowedColours ) { for ( IProperty prop : bs . getProperties ( ) . keySet ( ) ) { if ( prop . getName ( ) . equals ( "color" ) && prop . getValueClass ( ) == net . minecraft . item . EnumDyeColor . class ) { net . minecraft . item . EnumDyeColor current = ( net . minecraft . item . EnumDyeColor ) bs . getValue ( prop ) ; for ( Colour col : allowedColours ) { if ( current . getName ( ) . equalsIgnoreCase ( col . name ( ) ) ) return true ; } } } return false ; } | Test whether this block has a colour attribute which matches the list of allowed colours |
33,406 | public static boolean blockVariantMatches ( IBlockState bs , List < Variation > allowedVariants ) { for ( IProperty prop : bs . getProperties ( ) . keySet ( ) ) { if ( prop . getName ( ) . equals ( "variant" ) && prop . getValueClass ( ) . isEnum ( ) ) { Object current = bs . getValue ( prop ) ; if ( current != null ) { for ( Variation var : allowedVariants ) { if ( var . getValue ( ) . equalsIgnoreCase ( current . toString ( ) ) ) return true ; } } } } return false ; } | Test whether this block has a variant attribute which matches the list of allowed variants |
33,407 | public static Colour attemptToGetAsColour ( String part ) { String target = part . toUpperCase ( ) ; for ( int i = 0 ; i < Colour . values ( ) . length ; i ++ ) { String col = Colour . values ( ) [ i ] . name ( ) . replace ( "_" , "" ) ; if ( col . equals ( target ) ) return Colour . values ( ) [ i ] ; } return null ; } | Attempt to parse string as a Colour |
33,408 | public static Variation attemptToGetAsVariant ( String part ) { try { StoneTypes var = StoneTypes . valueOf ( part . toUpperCase ( ) ) ; if ( var != null ) { Variation bv = new Variation ( ) ; bv . setValue ( var . value ( ) ) ; return bv ; } } catch ( Exception e ) { } try { WoodTypes var = WoodTypes . valueOf ( part . toUpperCase ( ) ) ; if ( var != null ) { Variation bv = new Variation ( ) ; bv . setValue ( var . value ( ) ) ; return bv ; } } catch ( Exception e ) { } try { FlowerTypes var = FlowerTypes . fromValue ( part ) ; if ( var != null ) { Variation bv = new Variation ( ) ; bv . setValue ( var . value ( ) ) ; return bv ; } } catch ( Exception e ) { } try { EntityTypes var = EntityTypes . fromValue ( part ) ; if ( var != null ) { Variation bv = new Variation ( ) ; bv . setValue ( var . value ( ) ) ; return bv ; } } catch ( Exception e ) { } try { MonsterEggTypes var = MonsterEggTypes . fromValue ( part ) ; if ( var != null ) { Variation bv = new Variation ( ) ; bv . setValue ( var . value ( ) ) ; return bv ; } } catch ( Exception e ) { } try { ShapeTypes var = ShapeTypes . fromValue ( part ) ; if ( var != null ) { Variation bv = new Variation ( ) ; bv . setValue ( var . value ( ) ) ; return bv ; } } catch ( Exception e ) { } try { HalfTypes var = HalfTypes . fromValue ( part ) ; if ( var != null ) { Variation bv = new Variation ( ) ; bv . setValue ( var . value ( ) ) ; return bv ; } } catch ( Exception e ) { } return null ; } | Attempt to parse string as a Variation |
33,409 | public static ItemStack getItemStackFromParameterString ( String parameters ) { List < String > params = new ArrayList < String > ( Arrays . asList ( parameters . split ( " " ) ) ) ; Colour col = null ; Variation var = null ; Iterator < String > it = params . iterator ( ) ; while ( it . hasNext ( ) && col == null ) { col = MinecraftTypeHelper . attemptToGetAsColour ( it . next ( ) ) ; if ( col != null ) it . remove ( ) ; } it = params . iterator ( ) ; while ( it . hasNext ( ) && var == null ) { var = MinecraftTypeHelper . attemptToGetAsVariant ( it . next ( ) ) ; if ( var != null ) it . remove ( ) ; } if ( params . size ( ) == 0 ) return null ; String itemName = params . get ( 0 ) ; DrawItem di = new DrawItem ( ) ; di . setColour ( col ) ; di . setVariant ( var ) ; di . setType ( itemName ) ; return getItemStackFromDrawItem ( di ) ; } | Take a string of parameters delimited by spaces and create an ItemStack from it . |
33,410 | static IBlockState applyVariant ( IBlockState state , Variation variant ) { boolean relaxRequirements = false ; for ( int i = 0 ; i < 2 ; i ++ ) { for ( IProperty prop : state . getProperties ( ) . keySet ( ) ) { if ( ( prop . getName ( ) . equals ( "variant" ) || relaxRequirements ) && prop . getValueClass ( ) . isEnum ( ) ) { Object [ ] values = prop . getValueClass ( ) . getEnumConstants ( ) ; for ( Object obj : values ) { if ( obj != null && obj . toString ( ) . equalsIgnoreCase ( variant . getValue ( ) ) ) { return state . withProperty ( prop , ( Comparable ) obj ) ; } } } } relaxRequirements = true ; } return state ; } | Select the request variant of the Minecraft block if applicable |
33,411 | static IBlockState applyColour ( IBlockState state , Colour colour ) { for ( IProperty prop : state . getProperties ( ) . keySet ( ) ) { if ( prop . getName ( ) . equals ( "color" ) && prop . getValueClass ( ) == net . minecraft . item . EnumDyeColor . class ) { net . minecraft . item . EnumDyeColor current = ( net . minecraft . item . EnumDyeColor ) state . getValue ( prop ) ; if ( ! current . getName ( ) . equalsIgnoreCase ( colour . name ( ) ) ) { return state . withProperty ( prop , EnumDyeColor . valueOf ( colour . name ( ) ) ) ; } } } return state ; } | Recolour the Minecraft block |
33,412 | static IBlockState applyFacing ( IBlockState state , Facing facing ) { for ( IProperty prop : state . getProperties ( ) . keySet ( ) ) { if ( prop . getName ( ) . equals ( "facing" ) ) { if ( prop . getValueClass ( ) == EnumFacing . class ) { EnumFacing current = ( EnumFacing ) state . getValue ( prop ) ; if ( ! current . getName ( ) . equalsIgnoreCase ( facing . name ( ) ) ) { return state . withProperty ( prop , EnumFacing . valueOf ( facing . name ( ) ) ) ; } } else if ( prop . getValueClass ( ) == EnumOrientation . class ) { EnumOrientation current = ( EnumOrientation ) state . getValue ( prop ) ; if ( ! current . getName ( ) . equalsIgnoreCase ( facing . name ( ) ) ) { return state . withProperty ( prop , EnumOrientation . valueOf ( facing . name ( ) ) ) ; } } } } return state ; } | Change the facing attribute of the Minecraft block |
33,413 | private KeyHook create ( KeyBinding key ) { if ( key != null && key instanceof KeyHook ) { return ( KeyHook ) key ; } return new KeyHook ( key . getKeyDescription ( ) , key . getKeyCode ( ) , key . getKeyCategory ( ) ) ; } | Helper function to create a KeyHook object for a given KeyBinding object . |
33,414 | public void setOverriding ( boolean b ) { if ( this . keyHook != null ) { this . keyHook . isDown = false ; this . keyHook . justPressed = false ; this . keyHook . isOverridingPresses = b ; } } | Switch this object on or off . |
33,415 | public void add ( int dimension , float value ) { if ( this . map . containsKey ( dimension ) ) this . map . put ( dimension , this . map . get ( dimension ) + value ) ; else this . map . put ( dimension , value ) ; } | Add a given reward value on a specified dimension . |
33,416 | public void add ( MultidimensionalReward other ) { for ( Map . Entry < Integer , Float > entry : other . map . entrySet ( ) ) { Integer dimension = entry . getKey ( ) ; Float reward_value = entry . getValue ( ) ; this . add ( dimension . intValue ( ) , reward_value . floatValue ( ) ) ; } } | Merge in another multidimensional reward structure . |
33,417 | public Reward getAsReward ( ) { Reward reward = new Reward ( ) ; for ( Map . Entry < Integer , Float > entry : this . map . entrySet ( ) ) { Integer dimension = entry . getKey ( ) ; Float reward_value = entry . getValue ( ) ; Value reward_entry = new Value ( ) ; reward_entry . setDimension ( dimension ) ; reward_entry . setValue ( new BigDecimal ( reward_value ) ) ; reward . getValue ( ) . add ( reward_entry ) ; } return reward ; } | Retrieve the reward structure as defined by the schema . |
33,418 | public String getAsXMLString ( ) { String rewardString = null ; try { rewardString = SchemaHelper . serialiseObject ( this . getAsReward ( ) , Reward . class ) ; } catch ( JAXBException e ) { System . out . println ( "Caught reward serialization exception: " + e ) ; } return rewardString ; } | Gets the reward structure as an XML string as defined by the schema . |
33,419 | public double getRewardTotal ( ) { double rewards = 0.0 ; for ( Map . Entry < Integer , Float > entry : this . map . entrySet ( ) ) { rewards += entry . getValue ( ) ; } return rewards ; } | Get the total rewards from all dimensions each of which may be positive or negative . |
33,420 | public void serve ( ) throws IOException { ServerSocket serverSocket = new ServerSocket ( port ) ; while ( true ) { try { final Socket socket = serverSocket . accept ( ) ; Thread thread = new Thread ( "EnvServerSocketHandler" ) { public void run ( ) { boolean running = false ; try { checkHello ( socket ) ; while ( true ) { DataInputStream din = new DataInputStream ( socket . getInputStream ( ) ) ; int hdr = din . readInt ( ) ; byte [ ] data = new byte [ hdr ] ; din . readFully ( data ) ; String command = new String ( data , utf8 ) ; if ( command . startsWith ( "<Step" ) ) { step ( command , socket , din ) ; } else if ( command . startsWith ( "<Peek" ) ) { peek ( command , socket , din ) ; } else if ( command . startsWith ( "<Init" ) ) { init ( command , socket ) ; } else if ( command . startsWith ( "<Find" ) ) { find ( command , socket ) ; } else if ( command . startsWith ( "<MissionInit" ) ) { if ( missionInit ( din , command , socket ) ) running = true ; } else if ( command . startsWith ( "<Quit" ) ) { quit ( command , socket ) ; } else if ( command . startsWith ( "<Exit" ) ) { exit ( command , socket ) ; } else if ( command . startsWith ( "<Close" ) ) { close ( command , socket ) ; } else if ( command . startsWith ( "<Status" ) ) { status ( command , socket ) ; } else if ( command . startsWith ( "<Echo" ) ) { command = "<Echo>" + command + "</Echo>" ; data = command . getBytes ( utf8 ) ; hdr = data . length ; DataOutputStream dout = new DataOutputStream ( socket . getOutputStream ( ) ) ; dout . writeInt ( hdr ) ; dout . write ( data , 0 , hdr ) ; dout . flush ( ) ; } else { throw new IOException ( "Unknown env service command" ) ; } } } catch ( IOException ioe ) { TCPUtils . Log ( Level . SEVERE , "MalmoEnv socket error: " + ioe + " (can be on disconnect)" ) ; try { if ( running ) { TCPUtils . Log ( Level . INFO , "Want to quit on disconnect." ) ; setWantToQuit ( ) ; } socket . close ( ) ; } catch ( IOException ioe2 ) { } } } } ; thread . start ( ) ; } catch ( IOException ioe ) { TCPUtils . Log ( Level . SEVERE , "MalmoEnv service exits on " + ioe ) ; } } } | Start servicing the MalmoEnv protocol . |
33,421 | private byte [ ] getObservation ( boolean done ) { byte [ ] obs = envState . obs ; if ( obs == null && ! done ) { try { cond . await ( COND_WAIT_SECONDS , TimeUnit . SECONDS ) ; } catch ( InterruptedException ie ) { } obs = envState . obs ; } if ( obs == null ) { obs = new byte [ 0 ] ; } return obs ; } | Get the current observation . If none and not done wait for a short time . |
33,422 | public void observation ( String info ) { String pattern = "\"turn_key\":\"" ; int i = info . indexOf ( pattern ) ; String turnKey = "" ; if ( i != - 1 ) { turnKey = info . substring ( i + pattern . length ( ) , info . length ( ) - 1 ) ; turnKey = turnKey . substring ( 0 , turnKey . indexOf ( "\"" ) ) ; } lock . lock ( ) ; try { if ( ! envState . turnKey . equals ( turnKey ) ) { } if ( ! envState . lastTurnKey . equals ( turnKey ) ) { envState . turnKey = turnKey ; } envState . info = info ; cond . signalAll ( ) ; } finally { lock . unlock ( ) ; } } | Record a Malmo observation json - as the env info since an environment obs is a video frame . |
33,423 | public boolean doIWantToQuit ( MissionInit missionInit ) { lock . lock ( ) ; try { return envState . quit ; } finally { lock . unlock ( ) ; } } | IWantToQuit implementation . |
33,424 | public void stopServer ( ) { Log ( Level . INFO , "Attempting to stop SocketServer" ) ; keepRunning = false ; if ( this . serverSocket != null ) { try { this . serverSocket . close ( ) ; } catch ( IOException e ) { Log ( Level . WARNING , "Something happened when closing SocketServer: " + e ) ; } this . serverSocket = null ; } } | Immediately stop waiting for messages and close the SocketServer . |
33,425 | public void start ( ) { this . isLive = true ; try { execute ( ) ; } catch ( Exception e ) { System . out . println ( "State start - exception: " + e ) ; e . printStackTrace ( ) ; } } | Called to kick off the episode - should be no need for subclasses to override . |
33,426 | public void getReward ( MissionInit missionInit , MultidimensionalReward multidimReward ) { super . getReward ( missionInit , multidimReward ) ; if ( this . rewardDensity == RewardDensityForBuildAndBreak . MISSION_END ) { if ( multidimReward . isFinalReward ( ) && this . reward != 0 ) { float adjusted_reward = adjustAndDistributeReward ( this . reward , this . dimension , this . rscparams . getRewardDistribution ( ) ) ; multidimReward . add ( this . dimension , adjusted_reward ) ; } } else { if ( this . reward != 0 ) { synchronized ( this ) { float adjusted_reward = adjustAndDistributeReward ( this . reward , this . dimension , this . rscparams . getRewardDistribution ( ) ) ; multidimReward . add ( this . dimension , adjusted_reward ) ; this . reward = 0 ; } } } } | Get the reward value for the current Minecraft state . |
33,427 | public void cleanup ( ) { super . cleanup ( ) ; MinecraftForge . EVENT_BUS . unregister ( this ) ; structureHasBeenCompleted = false ; MalmoMod . MalmoMessageHandler . deregisterForMessage ( this , MalmoMessageType . SERVER_MISSIONOVER ) ; } | Called once after the mission ends - use for any necessary cleanup . |
33,428 | private void addHandler ( Object handler ) { if ( handler == null ) return ; if ( handler instanceof IVideoProducer ) addVideoProducer ( ( IVideoProducer ) handler ) ; else if ( handler instanceof IAudioProducer ) addAudioProducer ( ( IAudioProducer ) handler ) ; else if ( handler instanceof ICommandHandler ) addCommandHandler ( ( ICommandHandler ) handler ) ; else if ( handler instanceof IObservationProducer ) addObservationProducer ( ( IObservationProducer ) handler ) ; else if ( handler instanceof IRewardProducer ) addRewardProducer ( ( IRewardProducer ) handler ) ; else if ( handler instanceof IWorldGenerator ) addWorldGenerator ( ( IWorldGenerator ) handler ) ; else if ( handler instanceof IWorldDecorator ) addWorldDecorator ( ( IWorldDecorator ) handler ) ; else if ( handler instanceof IWantToQuit ) addQuitProducer ( ( IWantToQuit ) handler ) ; else this . failedHandlers += handler . getClass ( ) . getSimpleName ( ) + " isn't of a recognised handler type.\n" ; } | Add this handler to our set creating containers as needs be . |
33,429 | private Object createHandlerFromParams ( Object xmlHandler ) { if ( xmlHandler == null ) return null ; Object handler = null ; String handlerClass = xmlHandler . getClass ( ) . getSimpleName ( ) ; if ( handlerClass == null || handlerClass . length ( ) == 0 ) { return null ; } try { Class < ? > c = Class . forName ( "com.microsoft.Malmo.MissionHandlers." + handlerClass + "Implementation" ) ; handler = c . newInstance ( ) ; if ( ! ( ( HandlerBase ) handler ) . parseParameters ( xmlHandler ) ) this . failedHandlers += handlerClass + " failed to parse parameters.\n" ; } catch ( ClassNotFoundException e ) { System . out . println ( "Duff MissionHandler requested: " + handlerClass ) ; this . failedHandlers += "Failed to find " + handlerClass + "\n" ; } catch ( InstantiationException e ) { System . out . println ( "Could not instantiate specified MissionHandler." ) ; this . failedHandlers += "Failed to create " + handlerClass + "\n" ; } catch ( IllegalAccessException e ) { System . out . println ( "Could not instantiate specified MissionHandler." ) ; this . failedHandlers += "Failed to access " + handlerClass + "\n" ; } return handler ; } | Attempt to create an instance of the specified handler class using reflection . |
33,430 | static public void update ( Configuration configs ) { scoringPolicy = configs . get ( MalmoMod . SCORING_CONFIGS , "policy" , DEFAULT_NO_SCORING ) . getInt ( ) ; if ( scoringPolicy > 0 ) { String customLogHandler = configs . get ( MalmoMod . SCORING_CONFIGS , "handler" , "" ) . getString ( ) ; setLogging ( Level . INFO , customLogHandler ) ; } if ( logging ) log ( "<ScoreInit><Policy>" + scoringPolicy + "</Policy></ScoreInit>" ) ; } | Initialize scoing . |
33,431 | public static void logMissionInit ( MissionInit missionInit ) throws JAXBException { if ( ! logging || ! isScoring ( ) ) return ; totalRewards = 0.0 ; String missionXml = SchemaHelper . serialiseObject ( missionInit . getMission ( ) , Mission . class ) ; String hash ; try { hash = digest ( missionXml ) ; } catch ( NoSuchAlgorithmException e ) { hash = "" ; } List < AgentSection > agents = missionInit . getMission ( ) . getAgentSection ( ) ; String agentName = agents . get ( missionInit . getClientRole ( ) ) . getName ( ) ; StringBuffer message = new StringBuffer ( "<MissionInit><MissionDigest>" ) ; message . append ( hash ) ; message . append ( "</MissionDigest>" ) ; message . append ( "<AgentName>" ) ; message . append ( agentName ) ; message . append ( "</AgentName></MissionInit>" ) ; if ( scoringPolicy == TOTAL_WITH_MISSION_XML ) message . append ( missionXml ) ; log ( message . toString ( ) ) ; } | Record a secure hash of the mission init XML - if scoring . |
33,432 | public static void logReward ( String reward ) { if ( ! logging || ! isScoring ( ) ) return ; if ( scoringPolicy == LOG_EACH_REWARD ) { log ( "<Reward>" + reward + "</Reward>" ) ; } else if ( scoringPolicy == TOTAL_ALL_REWARDS || scoringPolicy == TOTAL_WITH_MISSION_XML ) { int i = reward . indexOf ( ":" ) ; totalRewards += Double . parseDouble ( reward . substring ( i + 1 ) ) ; } } | Log a reward . |
33,433 | public static void logMissionEndRewards ( Reward reward ) throws JAXBException { if ( ! logging || ! isScoring ( ) ) return ; if ( scoringPolicy == LOG_EACH_REWARD ) { String rewardString = SchemaHelper . serialiseObject ( reward , Reward . class ) ; log ( "<MissionEnd>" + rewardString + "</MissionEnd>" ) ; } else if ( scoringPolicy == TOTAL_ALL_REWARDS || scoringPolicy == TOTAL_WITH_MISSION_XML ) { List < Reward . Value > values = reward . getValue ( ) ; for ( Reward . Value v : values ) { totalRewards += v . getValue ( ) . doubleValue ( ) ; } log ( "<MissionTotal>" + totalRewards + "</MissionTotal>" ) ; } totalRewards = 0.0 ; } | Log mission end rewards . |
33,434 | private void fixAdditionalKeyBindings ( GameSettings settings ) { if ( this . additionalKeys == null ) { return ; } KeyBinding [ ] bindings = ( KeyBinding [ ] ) ArrayUtils . addAll ( settings . keyBindings , this . additionalKeys . toArray ( ) ) ; settings . keyBindings = bindings ; } | Call this to finalise any additional key bindings we want to create in the mod . |
33,435 | static private JAXBContext getJAXBContext ( Class < ? > objclass ) throws JAXBException { JAXBContext jaxbContext ; if ( jaxbContentCache . containsKey ( objclass . getName ( ) ) ) { jaxbContext = jaxbContentCache . get ( objclass . getName ( ) ) ; } else { jaxbContext = JAXBContext . newInstance ( objclass ) ; jaxbContentCache . put ( objclass . getName ( ) , jaxbContext ) ; } return jaxbContext ; } | Serialise the object to an XML string |
33,436 | static public Object deserialiseObject ( String xml , String xsdFile , Class < ? > objclass ) throws JAXBException , SAXException , XMLStreamException { Object obj = null ; JAXBContext jaxbContext = getJAXBContext ( objclass ) ; SchemaFactory schemaFactory = SchemaFactory . newInstance ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; final String schemaResourceFilename = new String ( xsdFile ) ; URL schemaURL = MalmoMod . class . getClassLoader ( ) . getResource ( schemaResourceFilename ) ; Schema schema = schemaFactory . newSchema ( schemaURL ) ; Unmarshaller jaxbUnmarshaller = jaxbContext . createUnmarshaller ( ) ; jaxbUnmarshaller . setSchema ( schema ) ; StringReader stringReader = new StringReader ( xml ) ; XMLInputFactory xif = XMLInputFactory . newFactory ( ) ; xif . setProperty ( XMLInputFactory . IS_SUPPORTING_EXTERNAL_ENTITIES , false ) ; xif . setProperty ( XMLInputFactory . SUPPORT_DTD , false ) ; XMLStreamReader XMLreader = xif . createXMLStreamReader ( stringReader ) ; obj = jaxbUnmarshaller . unmarshal ( XMLreader ) ; return obj ; } | Attempt to construct the specified object from this XML string |
33,437 | static public String getRootNodeName ( String xml ) { String rootNodeName = null ; try { DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setExpandEntityReferences ( false ) ; DocumentBuilder dBuilder = dbf . newDocumentBuilder ( ) ; InputSource inputSource = new InputSource ( new StringReader ( xml ) ) ; Document doc = dBuilder . parse ( inputSource ) ; doc . getDocumentElement ( ) . normalize ( ) ; rootNodeName = doc . getDocumentElement ( ) . getNodeName ( ) ; } catch ( SAXException e ) { System . out . println ( "SAX exception: " + e ) ; } catch ( IOException e ) { System . out . println ( "IO exception: " + e ) ; } catch ( ParserConfigurationException e ) { System . out . println ( "ParserConfiguration exception: " + e ) ; } return rootNodeName ; } | Retrieve the name of the root node in an XML string . |
33,438 | static public void setMissionControlPort ( int port ) { if ( port != AddressHelper . missionControlPort ) { AddressHelper . missionControlPort = port ; ModMetadata md = Loader . instance ( ) . activeModContainer ( ) . getMetadata ( ) ; if ( port != - 1 ) md . description = "Talk to this Mod using port " + TextFormatting . GREEN + port ; else md . description = TextFormatting . RED + "ERROR: No mission control port - check configuration" ; } } | Set the actual port used for mission control - not persisted could be different each time the Mod is run . |
33,439 | public boolean sendTCPString ( String message , int retries ) { Log ( Level . FINE , "About to send: " + message ) ; byte [ ] bytes = message . getBytes ( ) ; return sendTCPBytes ( bytes , retries ) ; } | Send string over TCP to the specified address via the specified port including a header . |
33,440 | private void addChatMatchSpecToRewardStructure ( ChatMatchSpec c ) { Float reward = c . getReward ( ) . floatValue ( ) ; Pattern pattern = Pattern . compile ( c . getRegex ( ) , Pattern . CASE_INSENSITIVE ) ; patternMap . put ( pattern , reward ) ; distributionMap . put ( pattern , c . getDistribution ( ) ) ; } | Helper function for adding a chat match specification to the pattern map . |
33,441 | public int sample ( ) { double val = this . rand . nextDouble ( ) * this . sum ; int sample = 0 ; while ( sample < this . likelihoods . length ) { val -= this . likelihoods [ sample ] ; if ( val < 0 ) { return sample ; } sample ++ ; } return this . rand . nextInt ( this . likelihoods . length ) ; } | Sample a value from the distribution . |
33,442 | public static void setShakeGestureSensitivity ( float sensitivity ) { requireApplication ( ) ; AppComponent . Holder . getInstance ( application ) . getPublicControl ( ) . setShakeGestureSensitivity ( sensitivity ) ; } | Set the sensitivity threshold of shake detection in G s . Default is 3 |
33,443 | public static void setPlugins ( PluginSource pluginSource ) { requireApplication ( ) ; AppComponent . Holder . getInstance ( application ) . getPublicControl ( ) . setPluginSource ( pluginSource ) ; } | Hook to manually register a plugin source . This API does not update the Hyperion menu retroactively so clients should call this as early as possible . |
33,444 | public void enqueue ( T item ) { queue [ head ] = item ; head ++ ; size ++ ; if ( head == queue . length ) head = 0 ; } | Add an item to the queue . |
33,445 | @ SuppressWarnings ( "unchecked" ) public T getItem ( int index ) { int target = head - 1 - index ; if ( target < 0 ) target = size + target - head ; return ( T ) queue [ target ] ; } | Get the item at a position n positions from the head . |
33,446 | public static boolean isPhoenixProcess ( Context context ) { int currentPid = Process . myPid ( ) ; ActivityManager manager = ( ActivityManager ) context . getSystemService ( Context . ACTIVITY_SERVICE ) ; List < ActivityManager . RunningAppProcessInfo > runningProcesses = manager . getRunningAppProcesses ( ) ; if ( runningProcesses != null ) { for ( ActivityManager . RunningAppProcessInfo processInfo : runningProcesses ) { if ( processInfo . pid == currentPid && processInfo . processName . endsWith ( ":phoenix" ) ) { return true ; } } } return false ; } | Checks if the current process is a temporary Phoenix Process . This can be used to avoid initialisation of unused resources or to prevent running code that is not multi - process ready . |
33,447 | public void doFrame ( long timestampNanoseconds ) { long frameIntervalNanoseconds = timestampNanoseconds - lastTimestampNanoseconds ; if ( lastTimestampNanoseconds != NEVER ) { double droppedFrameIntervalSeconds = hardwareFrameIntervalSeconds * 1.5 ; double frameIntervalSeconds = frameIntervalNanoseconds / 1_000_000_000.0 ; if ( droppedFrameIntervalSeconds < frameIntervalSeconds ) { playTickSound ( ) ; if ( areHapticsEnabled ) { playTickHaptics ( ) ; } } } lastTimestampNanoseconds = timestampNanoseconds ; Choreographer . getInstance ( ) . postFrameCallback ( this ) ; } | Choreographer . FrameCallback |
33,448 | private void updateAperture ( int newValue , long now ) { int previous = targetAperture ; targetAperture = newValue ; targetAperture = Math . max ( minAperture , targetAperture ) ; int maxAperture = Math . min ( this . maxAperture , activeSockets . size ( ) + pool . poolSize ( ) ) ; targetAperture = Math . min ( maxAperture , targetAperture ) ; lastApertureRefresh = now ; pendings . reset ( ( minPendings + maxPendings ) / 2 ) ; if ( targetAperture != previous ) { logger . debug ( "Current pending={}, new target={}, previous target={}" , pendings . value ( ) , targetAperture , previous ) ; } } | Update the aperture value and ensure its value stays in the right range . |
33,449 | private static void writeAndFlush ( final ByteBuffer buffer , final OutputStream outputStream ) throws IOException { if ( buffer . hasArray ( ) ) { outputStream . write ( buffer . array ( ) , buffer . position ( ) , buffer . remaining ( ) ) ; } else { while ( buffer . hasRemaining ( ) ) { final int size = Math . min ( buffer . remaining ( ) , 8 * 1024 ) ; final byte [ ] chunk = new byte [ size ] ; buffer . get ( chunk ) ; outputStream . write ( chunk ) ; } } outputStream . flush ( ) ; } | Write the contents of the given ByteBuffer to the OutputStream and flush the stream . |
33,450 | private String urlEncode ( final String unencoded ) throws DockerException { try { final String encode = URLEncoder . encode ( unencoded , UTF_8 . name ( ) ) ; return encode . replaceAll ( "\\+" , "%20" ) ; } catch ( UnsupportedEncodingException e ) { throw new DockerException ( e ) ; } } | URL - encodes a string when used as a URL query parameter s value . |
33,451 | private String urlEncodeFilters ( final Map < String , List < String > > filters ) throws DockerException { try { final String unencodedFilters = objectMapper ( ) . writeValueAsString ( filters ) ; if ( ! unencodedFilters . isEmpty ( ) ) { return urlEncode ( unencodedFilters ) ; } } catch ( IOException e ) { throw new DockerException ( e ) ; } return null ; } | Takes a map of filters and URL - encodes them . If the map is empty or an exception occurs return null . |
33,452 | public RegistryAuth fromConfig ( final Path configPath , final String serverAddress ) throws IOException { return authForRegistry ( configPath , serverAddress ) ; } | Returns the RegistryAuth for the config file for the given registry server name . |
33,453 | private RegistryAuth authWithCredentialHelper ( final String credsStore , final String registry ) throws IOException { final DockerCredentialHelperAuth dockerCredentialHelperAuth = DockerCredentialHelper . get ( credsStore , registry ) ; return dockerCredentialHelperAuth == null ? null : dockerCredentialHelperAuth . toRegistryAuth ( ) ; } | Obtain auth using a credential helper . |
33,454 | public String buildImageId ( ) { final String stream = stream ( ) ; return stream != null && stream . startsWith ( "Successfully built" ) ? stream . substring ( stream . lastIndexOf ( ' ' ) + 1 ) . trim ( ) : null ; } | Checks if the stream field contains a string a like Successfully built 2d6e00052167 and if so returns the image id . Otherwise null is returned . This string is expected when an image is built successfully . |
33,455 | static String parseRegistryUrl ( final String url ) { if ( url . equals ( "docker.io" ) || url . equals ( "index.docker.io" ) ) { return DEFAULT_REGISTRY_URL ; } else if ( url . matches ( "(^|(\\w+)\\.)gcr\\.io$" ) || url . equals ( "gcr.kubernetes.io" ) ) { return "https://" + url ; } else if ( url . equals ( "quay.io" ) ) { return "quay.io" ; } else if ( ! url . contains ( "http://" ) && ! url . contains ( "https://" ) ) { return "https://" + url ; } else { return url ; } } | Return registry server address given first part of image . |
33,456 | public static int store ( final String credsStore , final DockerCredentialHelperAuth auth ) throws IOException , InterruptedException { return credentialHelperDelegate . store ( credsStore , auth ) ; } | Store an auth value in the credsStore . |
33,457 | public static int erase ( final String credsStore , final String registry ) throws IOException , InterruptedException { return credentialHelperDelegate . erase ( credsStore , registry ) ; } | Erase an auth value from a credsStore matching a registry . |
33,458 | public static DockerCredentialHelperAuth get ( final String credsStore , final String registry ) throws IOException { return credentialHelperDelegate . get ( credsStore , registry ) ; } | Get an auth value from a credsStore for a registry . |
33,459 | public static Map < String , String > list ( final String credsStore ) throws IOException { return credentialHelperDelegate . list ( credsStore ) ; } | Lists credentials stored in the credsStore . |
33,460 | public static Builder forAuth ( final String auth ) { final String [ ] authParams = Base64 . decodeAsString ( auth ) . split ( ":" , 2 ) ; if ( authParams . length != 2 ) { return builder ( ) ; } return builder ( ) . username ( authParams [ 0 ] . trim ( ) ) . password ( authParams [ 1 ] . trim ( ) ) ; } | Construct a Builder based upon the auth field of the docker client config file . |
33,461 | public static Builder fromStream ( final InputStream credentialsStream ) throws IOException { final GoogleCredentials credentials = GoogleCredentials . fromStream ( credentialsStream ) ; return new Builder ( credentials ) ; } | Constructs a ContainerRegistryAuthSupplier for the account with the given credentials . |
33,462 | private AccessToken getAccessToken ( ) throws IOException { synchronized ( credentials ) { if ( needsRefresh ( credentials . getAccessToken ( ) ) ) { credentialRefresher . refresh ( credentials ) ; } } return credentials . getAccessToken ( ) ; } | Get an accessToken to use possibly refreshing the token if it expires within the minimumExpiryMillis . |
33,463 | public SpannableString formatDistance ( double distance ) { double distanceSmallUnit = TurfConversion . convertLength ( distance , TurfConstants . UNIT_METERS , smallUnit ) ; double distanceLargeUnit = TurfConversion . convertLength ( distance , TurfConstants . UNIT_METERS , largeUnit ) ; if ( distanceLargeUnit > LARGE_UNIT_THRESHOLD ) { return getDistanceString ( roundToDecimalPlace ( distanceLargeUnit , 0 ) , largeUnit ) ; } else if ( distanceSmallUnit < SMALL_UNIT_THRESHOLD ) { return getDistanceString ( roundToClosestIncrement ( distanceSmallUnit ) , smallUnit ) ; } else { return getDistanceString ( roundToDecimalPlace ( distanceLargeUnit , 1 ) , largeUnit ) ; } } | Returns a formatted SpannableString with bold and size formatting . I . e . 10 mi 350 m |
33,464 | private String roundToClosestIncrement ( double distance ) { int roundedNumber = ( ( int ) Math . round ( distance ) ) / roundingIncrement * roundingIncrement ; return String . valueOf ( roundedNumber < roundingIncrement ? roundingIncrement : roundedNumber ) ; } | Returns number rounded to closest specified rounding increment unless the number is less than the rounding increment then the rounding increment is returned |
33,465 | private String roundToDecimalPlace ( double distance , int decimalPlace ) { numberFormat . setMaximumFractionDigits ( decimalPlace ) ; return numberFormat . format ( distance ) ; } | Rounds given number to the given decimal place |
33,466 | private SpannableString getDistanceString ( String distance , String unit ) { SpannableString spannableString = new SpannableString ( String . format ( "%s %s" , distance , unitStrings . get ( unit ) ) ) ; spannableString . setSpan ( new StyleSpan ( Typeface . BOLD ) , 0 , distance . length ( ) , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; spannableString . setSpan ( new RelativeSizeSpan ( 0.65f ) , distance . length ( ) + 1 , spannableString . length ( ) , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; return spannableString ; } | Takes in a distance and units and returns a formatted SpannableString where the number is bold and the unit is shrunked to . 65 times the size |
33,467 | public void onDestroy ( ) { stopNavigation ( ) ; removeOffRouteListener ( null ) ; removeProgressChangeListener ( null ) ; removeMilestoneEventListener ( null ) ; removeNavigationEventListener ( null ) ; removeFasterRouteListener ( null ) ; removeRawLocationListener ( null ) ; } | Critical to place inside your navigation activity so that when your application gets destroyed the navigation service unbinds and gets destroyed preventing any memory leaks . Calling this also removes all listeners that have been attached . |
33,468 | @ SuppressWarnings ( "WeakerAccess" ) public void removeMilestone ( int milestoneIdentifier ) { for ( Milestone milestone : milestones ) { if ( milestoneIdentifier == milestone . getIdentifier ( ) ) { removeMilestone ( milestone ) ; return ; } } Timber . w ( "No milestone found with the specified identifier." ) ; } | Remove a specific milestone by passing in the identifier associated with the milestone you d like to remove . If the identifier passed in does not match one of the milestones in the list a warning will return in the log . |
33,469 | public void updateWaynameQueryMap ( boolean isEnabled ) { if ( mapWayName != null ) { mapWayName . updateWayNameQueryMap ( isEnabled ) ; } else { settings . updateWayNameEnabled ( isEnabled ) ; } } | Enables or disables the way name chip underneath the location icon . |
33,470 | void unpack ( File src , String destPath , UnpackUpdateTask . ProgressUpdateListener updateListener ) { new UnpackerTask ( offlineNavigator ) . executeOnExecutor ( AsyncTask . THREAD_POOL_EXECUTOR , src . getAbsolutePath ( ) , destPath + File . separator ) ; new UnpackUpdateTask ( updateListener ) . executeOnExecutor ( AsyncTask . THREAD_POOL_EXECUTOR , src ) ; } | Unpacks a TAR file at the srcPath into the destination directory . |
33,471 | public int onStartCommand ( Intent intent , int flags , int startId ) { NavigationTelemetry . getInstance ( ) . initializeLifecycleMonitor ( getApplication ( ) ) ; return START_STICKY ; } | Only should be called once since we want the service to continue running until the navigation session ends . |
33,472 | public String buildUrl ( ) { String onlineUrl = onlineRoute . getCall ( ) . request ( ) . url ( ) . toString ( ) ; String offlineUrl = buildOfflineUrl ( onlineUrl ) ; return offlineUrl ; } | Builds a URL string for offline . |
33,473 | public void showRerouteState ( ) { if ( rerouteLayout . getVisibility ( ) == INVISIBLE ) { rerouteLayout . startAnimation ( rerouteSlideDownTop ) ; rerouteLayout . setVisibility ( VISIBLE ) ; } } | Will slide the reroute view down from the top of the screen and make it visible |
33,474 | public void hideRerouteState ( ) { if ( rerouteLayout . getVisibility ( ) == VISIBLE ) { rerouteLayout . startAnimation ( rerouteSlideUpTop ) ; rerouteLayout . setVisibility ( INVISIBLE ) ; } } | Will slide the reroute view up to the top of the screen and hide it |
33,475 | private void initialize ( ) { LocaleUtils localeUtils = new LocaleUtils ( ) ; String language = localeUtils . inferDeviceLanguage ( getContext ( ) ) ; String unitType = localeUtils . getUnitTypeForDeviceLocale ( getContext ( ) ) ; int roundingIncrement = NavigationConstants . ROUNDING_INCREMENT_FIFTY ; distanceFormatter = new DistanceFormatter ( getContext ( ) , language , unitType , roundingIncrement ) ; inflate ( getContext ( ) , R . layout . instruction_view_layout , this ) ; } | Inflates this layout needed for this view and initializes the locale as the device locale . |
33,476 | private void initializeLandscapeListListener ( ) { instructionLayoutText . setOnClickListener ( new OnClickListener ( ) { public void onClick ( View instructionLayoutText ) { boolean instructionsVisible = instructionListLayout . getVisibility ( ) == VISIBLE ; if ( ! instructionsVisible ) { showInstructionList ( ) ; } else { hideInstructionList ( ) ; } } } ) ; } | For landscape orientation the click listener is attached to the instruction text layout and the constraints are adjusted before animating |
33,477 | private boolean newDistanceText ( InstructionModel model ) { return ! upcomingDistanceText . getText ( ) . toString ( ) . isEmpty ( ) && ! TextUtils . isEmpty ( model . retrieveStepDistanceRemaining ( ) ) && ! upcomingDistanceText . getText ( ) . toString ( ) . contentEquals ( model . retrieveStepDistanceRemaining ( ) . toString ( ) ) ; } | Looks to see if we have a new distance text . |
33,478 | private void updateDistanceText ( InstructionModel model ) { if ( newDistanceText ( model ) ) { distanceText ( model ) ; } else if ( upcomingDistanceText . getText ( ) . toString ( ) . isEmpty ( ) ) { distanceText ( model ) ; } } | Looks to see if we have a new distance text . Sets new distance text if found . |
33,479 | private void updateInstructionList ( InstructionModel model ) { RouteProgress routeProgress = model . retrieveProgress ( ) ; boolean isListShowing = instructionListLayout . getVisibility ( ) == VISIBLE ; rvInstructions . stopScroll ( ) ; instructionListAdapter . updateBannerListWith ( routeProgress , isListShowing ) ; } | Used to update the instructions list with the current steps . |
33,480 | static String buildInstructionString ( RouteProgress routeProgress , Milestone milestone ) { if ( milestone . getInstruction ( ) != null ) { return milestone . getInstruction ( ) . buildInstruction ( routeProgress ) ; } return EMPTY_STRING ; } | When a milestones triggered it s instruction needs to be built either using the provided string or an empty string . |
33,481 | static double routeDistanceRemaining ( double legDistanceRemaining , int legIndex , DirectionsRoute directionsRoute ) { if ( directionsRoute . legs ( ) . size ( ) < 2 ) { return legDistanceRemaining ; } for ( int i = legIndex + 1 ; i < directionsRoute . legs ( ) . size ( ) ; i ++ ) { legDistanceRemaining += directionsRoute . legs ( ) . get ( i ) . distance ( ) ; } return legDistanceRemaining ; } | Takes in the leg distance remaining value already calculated and if additional legs need to be traversed along after the current one adds those distances and returns the new distance . Otherwise if the route only contains one leg or the users on the last leg this value will equal the leg distance remaining . |
33,482 | private File saveAsFile ( ResponseBody responseBody ) { if ( responseBody == null ) { return null ; } try { File file = new File ( destDirectory + File . separator + fileName + retrieveUniqueId ( ) + "." + extension ) ; InputStream inputStream = null ; OutputStream outputStream = null ; try { inputStream = responseBody . byteStream ( ) ; outputStream = new FileOutputStream ( file ) ; byte [ ] buffer = new byte [ 4096 ] ; int numOfBufferedBytes ; while ( ( numOfBufferedBytes = inputStream . read ( buffer ) ) != END_OF_FILE_DENOTER ) { outputStream . write ( buffer , 0 , numOfBufferedBytes ) ; } outputStream . flush ( ) ; return file ; } catch ( IOException exception ) { return null ; } catch ( Exception exception ) { return null ; } finally { if ( inputStream != null ) { inputStream . close ( ) ; } if ( outputStream != null ) { outputStream . close ( ) ; } } } catch ( IOException exception ) { return null ; } } | Saves the file returned in the response body as a file in the cache directory |
33,483 | public static int retrieveThemeColor ( Context context , int resId ) { TypedValue outValue = resolveAttributeFromId ( context , resId ) ; if ( outValue . type >= TypedValue . TYPE_FIRST_COLOR_INT && outValue . type <= TypedValue . TYPE_LAST_COLOR_INT ) { return outValue . data ; } else { return ContextCompat . getColor ( context , outValue . resourceId ) ; } } | Looks are current theme and retrieves the color attribute for the given set theme . |
33,484 | public static int retrieveNavigationViewStyle ( Context context , int styleResId ) { TypedValue outValue = resolveAttributeFromId ( context , styleResId ) ; return outValue . resourceId ; } | Looks are current theme and retrieves the style for the given resId set in the theme . |
33,485 | void configure ( String tilePath , OnOfflineTilesConfiguredCallback callback ) { new ConfigureRouterTask ( navigator , tilePath , callback ) . execute ( ) ; } | Configures the navigator for getting offline routes |
33,486 | void retrieveRouteFor ( OfflineRoute offlineRoute , OnOfflineRouteFoundCallback callback ) { new OfflineRouteRetrievalTask ( navigator , callback ) . execute ( offlineRoute ) ; } | Uses libvalhalla and local tile data to generate mapbox - directions - api - like json |
33,487 | List < Point > sliceRoute ( LineString lineString ) { double distanceMeters = TurfMeasurement . length ( lineString , TurfConstants . UNIT_METERS ) ; if ( distanceMeters <= 0 ) { return Collections . emptyList ( ) ; } List < Point > points = new ArrayList < > ( ) ; for ( double i = 0 ; i < distanceMeters ; i += distance ) { Point point = TurfMeasurement . along ( lineString , i , TurfConstants . UNIT_METERS ) ; points . add ( point ) ; } return points ; } | Interpolates the route into even points along the route and adds these to the points list . |
33,488 | private void addPriorityInfo ( BannerComponents bannerComponents , int index ) { Integer abbreviationPriority = bannerComponents . abbreviationPriority ( ) ; if ( abbreviations . get ( abbreviationPriority ) == null ) { abbreviations . put ( abbreviationPriority , new ArrayList < Integer > ( ) ) ; } abbreviations . get ( abbreviationPriority ) . add ( index ) ; } | Adds the given BannerComponents object to the list of abbreviations so that when the list of BannerComponentNodes is completed text can be abbreviated properly to fit the specified TextView . |
33,489 | private String abbreviateBannerText ( TextView textView , List < BannerComponentNode > bannerComponentNodes ) { String bannerText = join ( bannerComponentNodes ) ; if ( abbreviations . isEmpty ( ) ) { return bannerText ; } bannerText = abbreviateUntilTextFits ( textView , bannerText , bannerComponentNodes ) ; abbreviations . clear ( ) ; return bannerText ; } | Using the abbreviations HashMap which should already be populated abbreviates the text in the bannerComponentNodes until the text fits the given TextView . |
33,490 | public void configure ( String version , OnOfflineTilesConfiguredCallback callback ) { offlineNavigator . configure ( new File ( tilePath , version ) . getAbsolutePath ( ) , callback ) ; } | Configures the navigator for getting offline routes . |
33,491 | public Locale inferDeviceLocale ( Context context ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . N ) { return context . getResources ( ) . getConfiguration ( ) . getLocales ( ) . get ( 0 ) ; } else { return context . getResources ( ) . getConfiguration ( ) . locale ; } } | Returns the device locale for which to use as a default if no language is specified |
33,492 | public String getNonEmptyLanguage ( Context context , String language ) { if ( language == null ) { return inferDeviceLanguage ( context ) ; } return language ; } | Returns the locale passed in if it is not null otherwise returns the device locale |
33,493 | public String retrieveNonNullUnitType ( Context context , String unitType ) { if ( unitType == null ) { return getUnitTypeForDeviceLocale ( context ) ; } return unitType ; } | Returns the unitType passed in if it is not null otherwise returns the a unitType based on the device Locale . |
33,494 | public static double differenceBetweenAngles ( double alpha , double beta ) { double phi = Math . abs ( beta - alpha ) % 360 ; return phi > 180 ? 360 - phi : phi ; } | Returns the smallest angle between two angles . |
33,495 | public void play ( SpeechAnnouncement announcement ) { boolean isInvalidAnnouncement = announcement == null ; if ( isInvalidAnnouncement ) { return ; } this . announcement = announcement ; playAnnouncementTextAndTypeFrom ( announcement ) ; } | Plays the specified text instruction using MapboxSpeech API defaulting to SSML input type |
33,496 | public void play ( SpeechAnnouncement speechAnnouncement ) { boolean isValidAnnouncement = speechAnnouncement != null && ! TextUtils . isEmpty ( speechAnnouncement . announcement ( ) ) ; boolean canPlay = isValidAnnouncement && languageSupported && ! isMuted ; if ( ! canPlay ) { return ; } fireInstructionListenerIfApi14 ( ) ; HashMap < String , String > params = new HashMap < > ( 1 ) ; params . put ( TextToSpeech . Engine . KEY_PARAM_UTTERANCE_ID , DEFAULT_UTTERANCE_ID ) ; textToSpeech . speak ( speechAnnouncement . announcement ( ) , TextToSpeech . QUEUE_ADD , params ) ; } | Plays the given voice instruction using TTS |
33,497 | public void onNewRouteProgress ( Location location , RouteProgress routeProgress ) { notificationProvider . updateNavigationNotification ( routeProgress ) ; eventDispatcher . onProgressChange ( location , routeProgress ) ; } | Corresponds to ProgressChangeListener object updating the notification and passing information to the navigation event dispatcher . |
33,498 | public void onMilestoneTrigger ( List < Milestone > triggeredMilestones , RouteProgress routeProgress ) { for ( Milestone milestone : triggeredMilestones ) { String instruction = buildInstructionString ( routeProgress , milestone ) ; eventDispatcher . onMilestoneEvent ( routeProgress , instruction , milestone ) ; } } | With each valid and successful rawLocation update this will get called once the work on the navigation engine thread has finished . Depending on whether or not a milestone gets triggered or not the navigation event dispatcher will be called to notify the developer . |
33,499 | private List < BannerComponentNode > parseBannerComponents ( BannerText bannerText ) { int length = 0 ; List < BannerComponentNode > bannerComponentNodes = new ArrayList < > ( ) ; for ( BannerComponents components : bannerText . components ( ) ) { BannerComponentNode node = null ; for ( NodeCreator nodeCreator : nodeCreators ) { if ( nodeCreator . isNodeType ( components ) ) { node = nodeCreator . setupNode ( components , bannerComponentNodes . size ( ) , length , bannerText . modifier ( ) ) ; break ; } } if ( node != null ) { bannerComponentNodes . add ( node ) ; length += components . text ( ) . length ( ) ; } } return bannerComponentNodes ; } | Parses the banner components and processes them using the nodeCreators in the order they were originally passed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.