idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
21,300
public void update ( Map < Subscription , Long > subs , long currentTime , long expirationTime ) { for ( Subscription sub : expressions ) { if ( subs . put ( sub , expirationTime ) == null ) { LOGGER . info ( "new subscription: {}" , sub ) ; } } Iterator < Map . Entry < Subscription , Long > > it = subs . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Map . Entry < Subscription , Long > entry = it . next ( ) ; if ( entry . getValue ( ) < currentTime ) { LOGGER . info ( "expired: {}" , entry . getKey ( ) ) ; it . remove ( ) ; } } }
Merge the subscriptions from this update into a map from subscriptions to expiration times .
21,301
Iterable < Measurement > convert ( Iterable < io . micrometer . core . instrument . Measurement > ms ) { long now = Clock . SYSTEM . wallTime ( ) ; List < Measurement > measurements = new ArrayList < > ( ) ; for ( io . micrometer . core . instrument . Measurement m : ms ) { Id measurementId = id . withTag ( "statistic" , m . getStatistic ( ) . getTagValueRepresentation ( ) ) ; measurements . add ( new Measurement ( measurementId , now , m . getValue ( ) ) ) ; } return measurements ; }
Helper for converting Micrometer measurements to Spectator measurements .
21,302
static ArrayTagSet create ( Iterable < Tag > tags ) { return ( tags instanceof ArrayTagSet ) ? ( ArrayTagSet ) tags : EMPTY . addAll ( tags ) ; }
Create a new tag set .
21,303
void add ( T item ) { int i = nextIndex . getAndIncrement ( ) % data . length ( ) ; data . set ( i , item ) ; }
Add a new item to the buffer . If the buffer is full a previous entry will get overwritten .
21,304
List < T > toList ( ) { List < T > items = new ArrayList < > ( data . length ( ) ) ; for ( int i = 0 ; i < data . length ( ) ; ++ i ) { T item = data . get ( i ) ; if ( item != null ) { items . add ( item ) ; } } return items ; }
Return a list with a copy of the data in the buffer .
21,305
private static ThreadFactory newThreadFactory ( final String id ) { return new ThreadFactory ( ) { private final AtomicInteger next = new AtomicInteger ( ) ; public Thread newThread ( Runnable r ) { final String name = "spectator-" + id + "-" + next . getAndIncrement ( ) ; final Thread t = new Thread ( r , name ) ; t . setDaemon ( true ) ; return t ; } } ; }
Create a thread factory using thread names based on the id . All threads will be configured as daemon threads .
21,306
public ScheduledFuture < ? > schedule ( Options options , Runnable task ) { if ( ! started ) { startThreads ( ) ; } DelayedTask t = new DelayedTask ( clock , options , task ) ; queue . put ( t ) ; return t ; }
Schedule a repetitive task .
21,307
public synchronized void shutdown ( ) { shutdown = true ; for ( int i = 0 ; i < threads . length ; ++ i ) { if ( threads [ i ] != null && threads [ i ] . isAlive ( ) ) { threads [ i ] . interrupt ( ) ; threads [ i ] = null ; } } }
Shutdown and cleanup resources associated with the scheduler . All threads will be interrupted but this method does not block for them to all finish execution .
21,308
static JmxConfig from ( Config config ) { try { ObjectName query = new ObjectName ( config . getString ( "query" ) ) ; List < JmxMeasurementConfig > ms = new ArrayList < > ( ) ; for ( Config cfg : config . getConfigList ( "measurements" ) ) { ms . add ( JmxMeasurementConfig . from ( cfg ) ) ; } return new JmxConfig ( query , ms ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "invalid mapping config" , e ) ; } }
Create a new instance from the Typesafe Config object .
21,309
@ SuppressWarnings ( "unchecked" ) private T unwrap ( T meter ) { T tmp = meter ; while ( tmp instanceof SwapMeter < ? > && registry == ( ( SwapMeter < ? > ) tmp ) . registry ) { tmp = ( ( SwapMeter < T > ) tmp ) . underlying ; } return tmp ; }
If the values are nested then unwrap any that have the same registry instance .
21,310
static DoubleDistributionSummary get ( Registry registry , Id id ) { DoubleDistributionSummary instance = INSTANCES . get ( id ) ; if ( instance == null ) { final Clock c = registry . clock ( ) ; DoubleDistributionSummary tmp = new DoubleDistributionSummary ( c , id , RESET_FREQ ) ; instance = INSTANCES . putIfAbsent ( id , tmp ) ; if ( instance == null ) { instance = tmp ; registry . register ( tmp ) ; } } return instance ; }
Get or create a double distribution summary with the specified id .
21,311
public static void read ( ) throws IOException , InterruptedException { for ( short channel = 0 ; channel < ADC_CHANNEL_COUNT ; channel ++ ) { int conversion_value = getConversionValue ( channel ) ; console . print ( String . format ( " | %04d" , conversion_value ) ) ; } console . print ( " |\r" ) ; Thread . sleep ( 250 ) ; }
Read data via SPI bus from MCP3002 chip .
21,312
public static int getConversionValue ( short channel ) throws IOException { byte data [ ] = new byte [ ] { ( byte ) 0b00000001 , ( byte ) ( 0b10000000 | ( ( ( channel & 7 ) << 4 ) ) ) , ( byte ) 0b00000000 } ; byte [ ] result = spi . write ( data ) ; int value = ( result [ 1 ] << 8 ) & 0b1100000000 ; value |= ( result [ 2 ] & 0xff ) ; return value ; }
Communicate to the ADC chip via SPI to get single - ended conversion value for a specified channel .
21,313
public static void setPlatform ( Platform platform ) throws PlatformAlreadyAssignedException { if ( PlatformManager . platform != null ) { throw new PlatformAlreadyAssignedException ( PlatformManager . platform ) ; } PlatformManager . platform = platform ; System . setProperty ( "pi4j.platform" , platform . id ( ) ) ; }
Set the runtime platform for Pi4J to use . This platform selection will be used to determine the default GPIO providers and I2C providers specific to the selected platform . A platform assignment can only be set once . If a second attempt to set a platform is attempted the PlatformAlreadyAssignedException will be thrown . Please note that platform assignment can be made automatically if you use a provider class prior to manually assigning a platform .
21,314
protected static Platform getDefaultPlatform ( ) { String envPlatformId = System . getenv ( "PI4J_PLATFORM" ) ; String platformId = System . getProperty ( "pi4j.platform" , envPlatformId ) ; if ( platformId != null && ! platformId . isEmpty ( ) ) { Platform pltfrm = Platform . fromId ( platformId ) ; if ( pltfrm != null ) { return pltfrm ; } } return Platform . RASPBERRYPI ; }
Internal method to get the default platform . It will attempt to first get the platform using the PI4J_PLATFORM environment variable if the environment variable is not configured then it will attempt to use the system property pi4j . platform . If the system property is not found or the value is not legal then return the default RASPBERRY_PI platform .
21,315
public List < String > getDeviceIDs ( ) { final List < String > ids = new ArrayList < > ( ) ; for ( final File deviceDir : getDeviceDirs ( ) ) { ids . add ( deviceDir . getName ( ) ) ; } return ids ; }
Gets a list of all registered slave device ids .
21,316
@ SuppressWarnings ( "unchecked" ) public < T > List < T > getDevices ( final Class < T > type ) { final List < W1Device > allDevices = getDevices ( ) ; final List < T > filteredDevices = new ArrayList < > ( ) ; for ( final W1Device device : allDevices ) { if ( type . isAssignableFrom ( device . getClass ( ) ) ) { filteredDevices . add ( ( T ) device ) ; } } return filteredDevices ; }
Get a list of devices that implement a certain interface .
21,317
public DeviceControllerDeviceStatus getDeviceStatus ( ) throws IOException { int deviceStatus = read ( MEMADDR_STATUS ) ; int reservedValue = deviceStatus & STATUS_RESERVED_MASK ; if ( reservedValue != STATUS_RESERVED_VALUE ) { throw new IOException ( "status-bits 4 to 8 must be 1 according to documentation chapter 4.2.2.1. got '" + Integer . toString ( reservedValue , 2 ) + "'!" ) ; } boolean eepromWriteActive = ( deviceStatus & STATUS_EEPROM_WRITEACTIVE_BIT ) > 0 ; boolean eepromWriteProtection = ( deviceStatus & STATUS_EEPROM_WRITEPROTECTION_BIT ) > 0 ; boolean wiperLock0 = ( deviceStatus & STATUS_WIPERLOCK0_BIT ) > 0 ; boolean wiperLock1 = ( deviceStatus & STATUS_WIPERLOCK1_BIT ) > 0 ; return new DeviceControllerDeviceStatus ( eepromWriteActive , eepromWriteProtection , wiperLock0 , wiperLock1 ) ; }
Returns the status of the device according EEPROM and WiperLocks .
21,318
public void increase ( final DeviceControllerChannel channel , final int steps ) throws IOException { if ( channel == null ) { throw new RuntimeException ( "null-channel is not allowed. For devices " + "knowing just one wiper Channel.A is mandatory for " + "parameter 'channel'" ) ; } byte memAddr = channel . getVolatileMemoryAddress ( ) ; increaseOrDecrease ( memAddr , true , steps ) ; }
Increments the volatile wiper for the given number steps .
21,319
public void decrease ( final DeviceControllerChannel channel , final int steps ) throws IOException { if ( channel == null ) { throw new RuntimeException ( "null-channel is not allowed. For devices " + "knowing just one wiper Channel.A is mandatory for " + "parameter 'channel'" ) ; } byte memAddr = channel . getVolatileMemoryAddress ( ) ; increaseOrDecrease ( memAddr , false , steps ) ; }
Decrements the volatile wiper for the given number steps .
21,320
public int getValue ( final DeviceControllerChannel channel , final boolean nonVolatile ) throws IOException { if ( channel == null ) { throw new RuntimeException ( "null-channel is not allowed. For devices " + "knowing just one wiper Channel.A is mandatory for " + "parameter 'channel'" ) ; } byte memAddr = nonVolatile ? channel . getNonVolatileMemoryAddress ( ) : channel . getVolatileMemoryAddress ( ) ; int currentValue = read ( memAddr ) ; return currentValue ; }
Receives the current wiper s value from the device .
21,321
public void setValue ( final DeviceControllerChannel channel , final int value , final boolean nonVolatile ) throws IOException { if ( channel == null ) { throw new RuntimeException ( "null-channel is not allowed. For devices " + "knowing just one wiper Channel.A is mandatory for " + "parameter 'channel'" ) ; } if ( value < 0 ) { throw new RuntimeException ( "only positive values are allowed! Got value '" + value + "' for writing to channel '" + channel . name ( ) + "'" ) ; } byte memAddr = nonVolatile ? channel . getNonVolatileMemoryAddress ( ) : channel . getVolatileMemoryAddress ( ) ; write ( memAddr , value ) ; }
Sets the wiper s value in the device .
21,322
public DeviceControllerTerminalConfiguration getTerminalConfiguration ( final DeviceControllerChannel channel ) throws IOException { if ( channel == null ) { throw new RuntimeException ( "null-channel is not allowed. For devices " + "knowing just one wiper Channel.A is mandatory for " + "parameter 'channel'" ) ; } int tcon = read ( channel . getTerminalControllAddress ( ) ) ; boolean channelEnabled = ( tcon & channel . getHardwareConfigControlBit ( ) ) > 0 ; boolean pinAEnabled = ( tcon & channel . getTerminalAConnectControlBit ( ) ) > 0 ; boolean pinWEnabled = ( tcon & channel . getWiperConnectControlBit ( ) ) > 0 ; boolean pinBEnabled = ( tcon & channel . getTerminalBConnectControlBit ( ) ) > 0 ; return new DeviceControllerTerminalConfiguration ( channel , channelEnabled , pinAEnabled , pinWEnabled , pinBEnabled ) ; }
Fetches the terminal - configuration from the device for a certain channel .
21,323
public void setTerminalConfiguration ( final DeviceControllerTerminalConfiguration config ) throws IOException { if ( config == null ) { throw new RuntimeException ( "null-config is not allowed!" ) ; } final DeviceControllerChannel channel = config . getChannel ( ) ; if ( channel == null ) { throw new RuntimeException ( "null-channel is not allowed. For devices " + "knowing just one wiper Channel.A is mandatory for " + "parameter 'channel'" ) ; } byte memAddr = config . getChannel ( ) . getTerminalControllAddress ( ) ; int tcon = read ( memAddr ) ; tcon = setBit ( tcon , channel . getHardwareConfigControlBit ( ) , config . isChannelEnabled ( ) ) ; tcon = setBit ( tcon , channel . getTerminalAConnectControlBit ( ) , config . isPinAEnabled ( ) ) ; tcon = setBit ( tcon , channel . getWiperConnectControlBit ( ) , config . isPinWEnabled ( ) ) ; tcon = setBit ( tcon , channel . getTerminalBConnectControlBit ( ) , config . isPinBEnabled ( ) ) ; write ( memAddr , tcon ) ; }
Sets the given terminal - configuration to the device .
21,324
private int read ( final byte memAddr ) throws IOException { byte [ ] cmd = new byte [ ] { ( byte ) ( ( memAddr << 4 ) | CMD_READ ) } ; byte [ ] buf = new byte [ 2 ] ; int read = i2cDevice . read ( cmd , 0 , cmd . length , buf , 0 , buf . length ) ; if ( read != 2 ) { throw new IOException ( "Expected to read two bytes but got: " + read ) ; } int first = buf [ 0 ] & 0xFF ; int second = buf [ 1 ] & 0xFF ; return ( first << 8 ) | second ; }
Reads two bytes from the devices at the given memory - address .
21,325
private void write ( final byte memAddr , final int value ) throws IOException { byte firstBit = ( byte ) ( ( value >> 8 ) & 0x000001 ) ; byte cmd = ( byte ) ( ( memAddr << 4 ) | CMD_WRITE | firstBit ) ; byte data = ( byte ) ( value & 0x00FF ) ; byte [ ] sequence = new byte [ ] { cmd , data } ; i2cDevice . write ( sequence , 0 , sequence . length ) ; }
Writes 9 bits of the given value to the device .
21,326
protected void selectBusSlave ( final I2CDevice device ) throws IOException { final int addr = device . getAddress ( ) ; if ( lastAddress != addr ) { lastAddress = addr ; file . ioctl ( I2CConstants . I2C_SLAVE , addr & 0xFF ) ; } }
Selects the slave device if not already selected on this bus . Uses SharedSecrets to get the POSIX file descriptor and runs the required ioctl s via JNI .
21,327
public static Pin [ ] allPins ( PinMode ... mode ) { List < Pin > results = new ArrayList < > ( ) ; for ( Pin p : pins . values ( ) ) { EnumSet < PinMode > supported_modes = p . getSupportedPinModes ( ) ; for ( PinMode m : mode ) { if ( supported_modes . contains ( m ) ) { results . add ( p ) ; continue ; } } } return results . toArray ( new Pin [ 0 ] ) ; }
Get all pin instances from this provider that support one of the provided pin modes .
21,328
public SensorState getState ( ) { if ( pin . isState ( openState ) ) return SensorState . OPEN ; else return SensorState . CLOSED ; }
Return the current sensor state based on the GPIO digital output pin state .
21,329
public static SpiDevice getInstance ( SpiChannel channel , SpiMode mode ) throws IOException { return new SpiDeviceImpl ( channel , mode ) ; }
Create new SpiDevice instance
21,330
public void setValue ( Pin pin , double value ) { if ( value <= getMinSupportedValue ( ) ) { value = getMinSupportedValue ( ) ; } else if ( value >= getMaxSupportedValue ( ) ) { value = getMaxSupportedValue ( ) ; } int write_value = ( int ) value ; try { byte packet [ ] = new byte [ 3 ] ; packet [ 0 ] = ( byte ) MCP4725_REG_WRITEDAC ; packet [ 1 ] = ( byte ) ( write_value >> 4 ) ; packet [ 2 ] = ( byte ) ( write_value << 4 ) ; device . write ( packet , 0 , 3 ) ; super . setValue ( pin , value ) ; } catch ( IOException e ) { throw new RuntimeException ( "Unable to write DAC output value." , e ) ; } }
Set the analog output value to an output pin on the DAC immediately .
21,331
protected void initialize ( final int initialValueForVolatileWipers ) throws IOException { if ( isCapableOfNonVolatileWiper ( ) ) { currentValue = controller . getValue ( DeviceControllerChannel . valueOf ( channel ) , false ) ; } else { final int newInitialValueForVolatileWipers = getValueAccordingBoundaries ( initialValueForVolatileWipers ) ; controller . setValue ( DeviceControllerChannel . valueOf ( channel ) , newInitialValueForVolatileWipers , MicrochipPotentiometerDeviceController . VOLATILE_WIPER ) ; currentValue = newInitialValueForVolatileWipers ; } }
Initializes the wiper to a defined status . For devices capable of non - volatile - wipers the non - volatile - value is loaded . For devices not capable the given value is set in the device .
21,332
public int updateCacheFromDevice ( ) throws IOException { currentValue = controller . getValue ( DeviceControllerChannel . valueOf ( channel ) , false ) ; return currentValue ; }
Updates the cache to the wiper s value .
21,333
public void decrease ( final int steps ) throws IOException { if ( currentValue == 0 ) { return ; } if ( steps < 0 ) { throw new RuntimeException ( "Only positive values for parameter 'steps' allowed!" ) ; } if ( getNonVolatileMode ( ) != MicrochipPotentiometerNonVolatileMode . VOLATILE_ONLY ) { throw new RuntimeException ( "'decrease' is only valid for NonVolatileMode.VOLATILE_ONLY!" ) ; } final int actualSteps ; if ( steps > currentValue ) { actualSteps = currentValue ; } else { actualSteps = steps ; } int newValue = currentValue - actualSteps ; if ( ( newValue == 0 ) || ( steps > 5 ) ) { setCurrentValue ( newValue ) ; } else { controller . decrease ( DeviceControllerChannel . valueOf ( channel ) , actualSteps ) ; currentValue = newValue ; } }
Decreases the wiper s value for n steps .
21,334
public void increase ( final int steps ) throws IOException { int maxValue = getMaxValue ( ) ; if ( currentValue == maxValue ) { return ; } if ( steps < 0 ) { throw new RuntimeException ( "only positive values for parameter 'steps' allowed!" ) ; } if ( getNonVolatileMode ( ) != MicrochipPotentiometerNonVolatileMode . VOLATILE_ONLY ) { throw new RuntimeException ( "'increase' is only valid for NonVolatileMode.VOLATILE_ONLY!" ) ; } final int actualSteps ; if ( ( steps + currentValue ) > maxValue ) { actualSteps = maxValue - currentValue ; } else { actualSteps = steps ; } int newValue = currentValue + actualSteps ; if ( ( newValue == maxValue ) || ( steps > 5 ) ) { setCurrentValue ( newValue ) ; } else { controller . increase ( DeviceControllerChannel . valueOf ( channel ) , actualSteps ) ; currentValue = newValue ; } }
Increases the wiper s value for n steps .
21,335
public void setWiperLock ( final boolean enabled ) throws IOException { controller . setWiperLock ( DeviceControllerChannel . valueOf ( channel ) , enabled ) ; }
Enables or disables wiper - lock . See chapter 5 . 3 .
21,336
private void doWiperAction ( final WiperAction wiperAction ) throws IOException { switch ( nonVolatileMode ) { case VOLATILE_ONLY : case VOLATILE_AND_NONVOLATILE : wiperAction . run ( MicrochipPotentiometerDeviceController . VOLATILE_WIPER ) ; break ; case NONVOLATILE_ONLY : } switch ( nonVolatileMode ) { case NONVOLATILE_ONLY : case VOLATILE_AND_NONVOLATILE : wiperAction . run ( MicrochipPotentiometerDeviceController . NONVOLATILE_WIPER ) ; break ; case VOLATILE_ONLY : } }
Runs a given wiperAction for the volatile - wiper the non - volatile - wiper or both according the current nonVolatileMode .
21,337
public PowerState getState ( ) { if ( pin . isState ( onState ) ) return PowerState . ON ; else if ( pin . isState ( offState ) ) return PowerState . OFF ; else return PowerState . UNKNOWN ; }
Return the current power state based on the GPIO digital output pin state .
21,338
protected static Pin createDigitalPinNoPullDown ( int address , String name ) { return createDigitalPin ( RaspiGpioProvider . NAME , address , name , EnumSet . of ( PinPullResistance . OFF , PinPullResistance . PULL_UP ) , PinEdge . all ( ) ) ; }
SDC . 0 pin has a physical pull - up resistor
21,339
public static Pin [ ] allPins ( SystemInfo . BoardType board ) { List < Pin > pins = new ArrayList < > ( ) ; pins . add ( RaspiPin . GPIO_00 ) ; pins . add ( RaspiPin . GPIO_01 ) ; pins . add ( RaspiPin . GPIO_02 ) ; pins . add ( RaspiPin . GPIO_03 ) ; pins . add ( RaspiPin . GPIO_04 ) ; pins . add ( RaspiPin . GPIO_05 ) ; pins . add ( RaspiPin . GPIO_06 ) ; pins . add ( RaspiPin . GPIO_07 ) ; pins . add ( RaspiPin . GPIO_08 ) ; pins . add ( RaspiPin . GPIO_09 ) ; pins . add ( RaspiPin . GPIO_10 ) ; pins . add ( RaspiPin . GPIO_11 ) ; pins . add ( RaspiPin . GPIO_12 ) ; pins . add ( RaspiPin . GPIO_13 ) ; pins . add ( RaspiPin . GPIO_14 ) ; pins . add ( RaspiPin . GPIO_15 ) ; pins . add ( RaspiPin . GPIO_16 ) ; if ( board == SystemInfo . BoardType . RaspberryPi_B_Rev1 ) { return pins . toArray ( new Pin [ 0 ] ) ; } if ( board == SystemInfo . BoardType . RaspberryPi_A || board == SystemInfo . BoardType . RaspberryPi_B_Rev2 ) { pins . add ( RaspiPin . GPIO_17 ) ; pins . add ( RaspiPin . GPIO_18 ) ; pins . add ( RaspiPin . GPIO_19 ) ; pins . add ( RaspiPin . GPIO_20 ) ; } else { pins . add ( RaspiPin . GPIO_21 ) ; pins . add ( RaspiPin . GPIO_22 ) ; pins . add ( RaspiPin . GPIO_23 ) ; pins . add ( RaspiPin . GPIO_24 ) ; pins . add ( RaspiPin . GPIO_25 ) ; pins . add ( RaspiPin . GPIO_26 ) ; pins . add ( RaspiPin . GPIO_27 ) ; pins . add ( RaspiPin . GPIO_28 ) ; pins . add ( RaspiPin . GPIO_29 ) ; pins . add ( RaspiPin . GPIO_30 ) ; pins . add ( RaspiPin . GPIO_31 ) ; } return pins . toArray ( new Pin [ 0 ] ) ; }
so this method definition will hide the subclass static method )
21,340
public synchronized static void write ( int fd , InputStream input ) throws IOException { if ( input . available ( ) <= 0 ) { throw new IOException ( "No available bytes in input stream to write to serial port." ) ; } ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int length ; byte [ ] data = new byte [ 1024 ] ; while ( ( length = input . read ( data , 0 , data . length ) ) != - 1 ) { buffer . write ( data , 0 , length ) ; } buffer . flush ( ) ; write ( fd , buffer . toByteArray ( ) , buffer . size ( ) ) ; }
Read content from an input stream of data and write it to the serial port transmit buffer .
21,341
public void setPercentValue ( Pin pin , Number percent ) { if ( percent . doubleValue ( ) <= 0 ) { setValue ( pin , getMinSupportedValue ( ) ) ; } else if ( percent . doubleValue ( ) >= 100 ) { setValue ( pin , getMaxSupportedValue ( ) ) ; } else { double value = ( getMaxSupportedValue ( ) - getMinSupportedValue ( ) ) * ( percent . doubleValue ( ) / 100f ) ; setValue ( pin , value ) ; } }
Set the current value in a percentage of the available range instead of a raw value .
21,342
public void setPercentValue ( GpioPinAnalogOutput pin , Number percent ) { setPercentValue ( pin . getPin ( ) , percent ) ; }
Set the current analog value as a percentage of the available range instead of a raw value . Thr framework will automatically convert the percentage to a scaled number in the ADC s value range .
21,343
public void setValue ( Pin pin , Number value ) { super . setValue ( pin , value . doubleValue ( ) ) ; }
Set the requested analog output pin s conversion value .
21,344
public void shutdown ( ) { if ( isShutdown ( ) ) return ; super . shutdown ( ) ; try { for ( Pin pin : allPins ) { Double value = getShutdownValue ( pin ) . doubleValue ( ) ; if ( value != null ) { setValue ( pin , value ) ; } } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
This method is used by the framework to shutdown the DAC instance and apply any configured shutdown values to the DAC pins .
21,345
public static void loadLibraryFromClasspath ( String path ) throws IOException { Path inputPath = Paths . get ( path ) ; if ( ! inputPath . isAbsolute ( ) ) { throw new IllegalArgumentException ( "The path has to be absolute, but found: " + inputPath ) ; } String fileNameFull = inputPath . getFileName ( ) . toString ( ) ; int dotIndex = fileNameFull . indexOf ( '.' ) ; if ( dotIndex < 0 || dotIndex >= fileNameFull . length ( ) - 1 ) { throw new IllegalArgumentException ( "The path has to end with a file name and extension, but found: " + fileNameFull ) ; } String fileName = fileNameFull . substring ( 0 , dotIndex ) ; String extension = fileNameFull . substring ( dotIndex ) ; Path target = Files . createTempFile ( fileName , extension ) ; File targetFile = target . toFile ( ) ; targetFile . deleteOnExit ( ) ; try ( InputStream source = NativeLibraryLoader . class . getResourceAsStream ( inputPath . toString ( ) ) ) { if ( source == null ) { throw new FileNotFoundException ( "File " + inputPath + " was not found in classpath." ) ; } Files . copy ( source , target , StandardCopyOption . REPLACE_EXISTING ) ; } System . load ( target . toAbsolutePath ( ) . toString ( ) ) ; }
Loads library from classpath
21,346
public String getHexByteString ( CharSequence prefix , CharSequence separator , CharSequence suffix ) throws IOException { byte data [ ] = getBytes ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < data . length ; i ++ ) { if ( i > 0 ) sb . append ( separator ) ; int v = data [ i ] & 0xff ; if ( prefix != null ) sb . append ( prefix ) ; sb . append ( hexArray [ v >> 4 ] ) ; sb . append ( hexArray [ v & 0xf ] ) ; if ( suffix != null ) sb . append ( suffix ) ; } return sb . toString ( ) ; }
Get a HEX string representation of the bytes available in the serial data receive buffer
21,347
public static double convert ( TemperatureScale from , TemperatureScale to , double temperature ) { switch ( from ) { case FARENHEIT : return convertFromFarenheit ( to , temperature ) ; case CELSIUS : return convertFromCelsius ( to , temperature ) ; case KELVIN : return convertFromKelvin ( to , temperature ) ; case RANKINE : return convertFromRankine ( to , temperature ) ; default : throw ( new RuntimeException ( "Invalid termpature conversion" ) ) ; } }
Convert a temperature value from one temperature scale to another .
21,348
public static double convertFromFarenheit ( TemperatureScale to , double temperature ) { switch ( to ) { case FARENHEIT : return temperature ; case CELSIUS : return convertFarenheitToCelsius ( temperature ) ; case KELVIN : return convertFarenheitToKelvin ( temperature ) ; case RANKINE : return convertFarenheitToRankine ( temperature ) ; default : throw ( new RuntimeException ( "Invalid termpature conversion" ) ) ; } }
Convert a temperature value from the Farenheit temperature scale to another .
21,349
public static double convertToFarenheit ( TemperatureScale from , double temperature ) { switch ( from ) { case FARENHEIT : return temperature ; case CELSIUS : return convertCelsiusToFarenheit ( temperature ) ; case KELVIN : return convertKelvinToFarenheit ( temperature ) ; case RANKINE : return convertRankineToFarenheit ( temperature ) ; default : throw ( new RuntimeException ( "Invalid termpature conversion" ) ) ; } }
Convert a temperature value from another temperature scale into the Farenheit temperature scale .
21,350
public static double convertFromCelsius ( TemperatureScale to , double temperature ) { switch ( to ) { case FARENHEIT : return convertCelsiusToFarenheit ( temperature ) ; case CELSIUS : return temperature ; case KELVIN : return convertCelsiusToKelvin ( temperature ) ; case RANKINE : return convertCelsiusToRankine ( temperature ) ; default : throw ( new RuntimeException ( "Invalid termpature conversion" ) ) ; } }
Convert a temperature value from the Celsius temperature scale to another .
21,351
public static double convertToCelsius ( TemperatureScale from , double temperature ) { switch ( from ) { case FARENHEIT : return convertFarenheitToCelsius ( temperature ) ; case CELSIUS : return temperature ; case KELVIN : return convertKelvinToCelsius ( temperature ) ; case RANKINE : return convertRankineToCelsius ( temperature ) ; default : throw ( new RuntimeException ( "Invalid termpature conversion" ) ) ; } }
Convert a temperature value from another temperature scale into the Celsius temperature scale .
21,352
public static double convertFromKelvin ( TemperatureScale to , double temperature ) { switch ( to ) { case FARENHEIT : return convertKelvinToFarenheit ( temperature ) ; case CELSIUS : return convertKelvinToCelsius ( temperature ) ; case KELVIN : return temperature ; case RANKINE : return convertKelvinToRankine ( temperature ) ; default : throw ( new RuntimeException ( "Invalid termpature conversion" ) ) ; } }
Convert a temperature value from the Kelvin temperature scale to another .
21,353
public static double convertToKelvin ( TemperatureScale from , double temperature ) { switch ( from ) { case FARENHEIT : return convertFarenheitToKelvin ( temperature ) ; case CELSIUS : return convertCelsiusToKelvin ( temperature ) ; case KELVIN : return temperature ; case RANKINE : return convertRankineToKelvin ( temperature ) ; default : throw ( new RuntimeException ( "Invalid termpature conversion" ) ) ; } }
Convert a temperature value from another temperature scale into the Kelvin temperature scale .
21,354
public static double convertFromRankine ( TemperatureScale to , double temperature ) { switch ( to ) { case FARENHEIT : return convertRankineToFarenheit ( temperature ) ; case CELSIUS : return convertRankineToCelsius ( temperature ) ; case KELVIN : return convertRankineToKelvin ( temperature ) ; case RANKINE : return temperature ; default : throw ( new RuntimeException ( "Invalid termpature conversion" ) ) ; } }
Convert a temperature value from the Rankine temperature scale to another .
21,355
public static double convertToRankine ( TemperatureScale from , double temperature ) { switch ( from ) { case FARENHEIT : return convertFarenheitToRankine ( temperature ) ; case CELSIUS : return convertCelsiusToRankine ( temperature ) ; case KELVIN : return convertKelvinToRankine ( temperature ) ; case RANKINE : return temperature ; default : throw ( new RuntimeException ( "Invalid termpature conversion" ) ) ; } }
Convert a temperature value from another temperature scale into the Rankine temperature scale .
21,356
public float getPercentValue ( Pin pin ) { double value = getValue ( pin ) ; if ( value > INVALID_VALUE ) { return ( float ) ( value / ( getMaxSupportedValue ( ) - getMinSupportedValue ( ) ) ) * 100f ; } return INVALID_VALUE ; }
Get the current value in a percentage of the available range instead of a raw value .
21,357
public void shutdown ( ) { if ( isShutdown ( ) ) return ; super . shutdown ( ) ; try { if ( monitor != null ) { monitor . shutdown ( ) ; monitor = null ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
This method is used by the framework to shutdown the background monitoring thread if needed when the program exits .
21,358
public void setEventThreshold ( double threshold , GpioPinAnalogInput ... pin ) { for ( GpioPin p : pin ) { setEventThreshold ( threshold , p . getPin ( ) ) ; } }
Set the event threshold value for a given analog input pin .
21,359
public void setMonitorEnabled ( boolean enabled ) { if ( enabled ) { if ( monitor == null ) { monitor = new AdcGpioProviderBase . ADCMonitor ( ) ; monitor . start ( ) ; } } else { try { if ( monitor != null ) { monitor . shutdown ( ) ; monitor = null ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }
Set the background monitoring thread s enabled state .
21,360
public void ioctl ( long command , int value ) throws IOException { final int response = directIOCTL ( getFileDescriptor ( ) , command , value ) ; if ( response < 0 ) throw new LinuxFileException ( ) ; }
Runs an ioctl value command on a file descriptor .
21,361
public void ioctl ( final long command , ByteBuffer data , IntBuffer offsets ) throws IOException { ByteBuffer originalData = data ; if ( data == null || offsets == null ) throw new NullPointerException ( "data and offsets required!" ) ; if ( offsets . order ( ) != ByteOrder . nativeOrder ( ) ) throw new IllegalArgumentException ( "provided IntBuffer offsets ByteOrder must be native!" ) ; try { if ( ! data . isDirect ( ) ) { ByteBuffer newBuf = getDataBuffer ( data . limit ( ) ) ; int pos = data . position ( ) ; data . rewind ( ) ; newBuf . clear ( ) ; newBuf . put ( data ) ; newBuf . position ( pos ) ; data = newBuf ; } if ( ! offsets . isDirect ( ) ) { IntBuffer newBuf = getOffsetsBuffer ( offsets . remaining ( ) ) ; newBuf . clear ( ) ; newBuf . put ( offsets ) ; newBuf . flip ( ) ; offsets = newBuf ; } } catch ( BufferOverflowException e ) { throw new ScratchBufferOverrun ( ) ; } if ( ( offsets . remaining ( ) & 1 ) != 0 ) throw new IllegalArgumentException ( "offset buffer must be even length!" ) ; for ( int i = offsets . position ( ) ; i < offsets . limit ( ) ; i += 2 ) { final int ptrOffset = offsets . get ( i ) ; final int dataOffset = offsets . get ( i + 1 ) ; if ( dataOffset >= data . capacity ( ) || dataOffset < 0 ) throw new IndexOutOfBoundsException ( "invalid data offset specified in buffer: " + dataOffset ) ; if ( ( ptrOffset + wordSize ) > data . capacity ( ) || ptrOffset < 0 ) throw new IndexOutOfBoundsException ( "invalid pointer offset specified in buffer: " + ptrOffset ) ; } final int response = directIOCTLStructure ( getFileDescriptor ( ) , command , data , data . position ( ) , offsets , offsets . position ( ) , offsets . remaining ( ) ) ; if ( response < 0 ) throw new LinuxFileException ( ) ; offsets . position ( offsets . limit ( ) ) ; data . rewind ( ) ; if ( originalData != data ) { originalData . rewind ( ) ; originalData . put ( data ) ; originalData . rewind ( ) ; } }
Runs an ioctl on a file descriptor . Uses special offset buffer to produce real C - like structures with pointers . Advanced use only! Must be able to produce byte - perfect data structures just as gcc would on this system including struct padding and pointer size .
21,362
private int getFileDescriptor ( ) throws IOException { final int fd = SharedSecrets . getJavaIOFileDescriptorAccess ( ) . get ( getFD ( ) ) ; if ( fd < 1 ) throw new IOException ( "failed to get POSIX file descriptor!" ) ; return fd ; }
Gets the real POSIX file descriptor for use by custom jni calls .
21,363
public ByteBuffer mmap ( int length , MMAPProt prot , MMAPFlags flags , int offset ) throws IOException { long pointer = mmap ( getFileDescriptor ( ) , length , prot . flag , flags . flag , offset ) ; if ( pointer == - 1 ) throw new LinuxFileException ( ) ; return newMappedByteBuffer ( length , pointer , ( ) -> { munmapDirect ( pointer , length ) ; } ) ; }
Direct memory mapping from a file descriptor . This is normally possible through the local FileChannel but NIO will try to truncate files if they don t report a correct size . This will avoid that .
21,364
public RelayState getState ( ) { if ( pin . isState ( openState ) ) return RelayState . OPEN ; else return RelayState . CLOSED ; }
Return the current relay state based on the GPIO digital output pin state .
21,365
public void setState ( MotorState state ) { switch ( state ) { case STOP : { currentState = MotorState . STOP ; for ( GpioPinDigitalOutput pin : pins ) pin . setState ( offState ) ; break ; } case FORWARD : { currentState = MotorState . FORWARD ; if ( ! controlThread . isAlive ( ) ) { controlThread = new GpioStepperMotorControl ( ) ; controlThread . start ( ) ; } break ; } case REVERSE : { currentState = MotorState . REVERSE ; if ( ! controlThread . isAlive ( ) ) { controlThread = new GpioStepperMotorControl ( ) ; controlThread . start ( ) ; } break ; } default : { throw new UnsupportedOperationException ( "Cannot set motor state: " + state . toString ( ) ) ; } } }
change the current stepper motor state
21,366
private void doStep ( boolean forward ) { if ( forward ) sequenceIndex ++ ; else sequenceIndex -- ; if ( sequenceIndex >= stepSequence . length ) sequenceIndex = 0 ; else if ( sequenceIndex < 0 ) sequenceIndex = ( stepSequence . length - 1 ) ; for ( int pinIndex = 0 ; pinIndex < pins . length ; pinIndex ++ ) { double nib = Math . pow ( 2 , pinIndex ) ; if ( ( stepSequence [ sequenceIndex ] & ( int ) nib ) > 0 ) pins [ pinIndex ] . setState ( onState ) ; else pins [ pinIndex ] . setState ( offState ) ; } try { Thread . sleep ( stepIntervalMilliseconds , stepIntervalNanoseconds ) ; } catch ( InterruptedException e ) { } }
this method performs the calculations and work to control the GPIO pins to move the stepper motor forward or reverse
21,367
public int calculateOffPositionForPulseDuration ( int duration ) { validatePwmDuration ( duration ) ; int result = ( PWM_STEPS - 1 ) * duration / periodDurationMicros ; if ( result < 1 ) { result = 1 ; } else if ( result > PWM_STEPS - 1 ) { result = PWM_STEPS - 1 ; } return result ; }
Calculates the OFF position for a certain pulse duration .
21,368
public static I2CBus getInstance ( int busNumber , long lockAquireTimeout , TimeUnit lockAquireTimeoutUnit ) throws UnsupportedBusNumberException , IOException { return provider . getBus ( busNumber , lockAquireTimeout , lockAquireTimeoutUnit ) ; }
Create new I2CBus instance .
21,369
public static int [ ] getBusIds ( ) throws IOException { Set < Integer > set = null ; for ( Path device : Files . newDirectoryStream ( Paths . get ( "/sys/bus/i2c/devices" ) , "*" ) ) { String [ ] tokens = device . toString ( ) . split ( "-" ) ; if ( tokens . length == 2 ) { if ( set == null ) { set = new HashSet < Integer > ( ) ; } set . add ( Integer . valueOf ( tokens [ 1 ] ) ) ; } } int [ ] result = null ; if ( set != null ) { int counter = 0 ; result = new int [ set . size ( ) ] ; for ( Integer value : set ) { result [ counter ] = value . intValue ( ) ; counter = counter + 1 ; } } return result ; }
Fetch all available I2C bus numbers from sysfs . Returns null if nothing was found .
21,370
public void close ( ) throws IllegalStateException , IOException { if ( isClosed ( ) ) throw new IllegalStateException ( "Serial connection is not open; cannot 'close()'." ) ; SerialInterrupt . removeListener ( fileDescriptor ) ; com . pi4j . jni . Serial . close ( fileDescriptor ) ; fileDescriptor = - 1 ; }
This method is called to close a currently open open serial port .
21,371
public void open ( String file ) throws IOException { filename = file ; if ( fd > 0 ) { throw new IOException ( "File " + filename + " already open." ) ; } fd = WDT . open ( file ) ; if ( fd < 0 ) { throw new IOException ( "Cannot open file handle for " + filename + " got " + fd + " back." ) ; } }
Open custom Watchdog
21,372
public void setTimeOut ( int timeout ) throws IOException { isOpen ( ) ; int ret = WDT . setTimeOut ( fd , timeout ) ; if ( ret < 0 ) { throw new IOException ( "Cannot set timeout for " + filename + " got " + ret + " back." ) ; } }
Set new timeout
21,373
public void heartbeat ( ) throws IOException { isOpen ( ) ; int ret = WDT . ping ( fd ) ; if ( ret < 0 ) { throw new IOException ( "Heartbeat error. File " + filename + " got " + ret + " back." ) ; } }
Ping a watchdog .
21,374
public void disable ( ) throws IOException { isOpen ( ) ; int ret = WDT . disable ( fd ) ; if ( ret < 0 ) { throw new IOException ( "Cannot disable WatchDog. File " + filename + " got " + ret + " back." ) ; } }
Disable watchdog with Magic Close . Now watchdog not working . Close watchdog without call disable causes RaspberryPi reboot!
21,375
private static ThreadFactory getThreadFactory ( final String nameFormat ) { final ThreadFactory defaultThreadFactory = Executors . privilegedThreadFactory ( ) ; return new ThreadFactory ( ) { final AtomicLong count = ( nameFormat != null ) ? new AtomicLong ( 0 ) : null ; public Thread newThread ( Runnable runnable ) { Thread thread = defaultThreadFactory . newThread ( runnable ) ; if ( nameFormat != null ) { thread . setName ( String . format ( nameFormat , count . getAndIncrement ( ) ) ) ; } return thread ; } } ; }
return an instance to the thread factory used to create new executor services
21,376
public ExecutorService newSingleThreadExecutorService ( ) { ExecutorService singleThreadExecutorService = Executors . newSingleThreadExecutor ( getThreadFactory ( "pi4j-single-executor-%d" ) ) ; singleThreadExecutorServices . add ( singleThreadExecutorService ) ; return singleThreadExecutorService ; }
return a new instance of a single thread executor service
21,377
public void shutdown ( ) { for ( ExecutorService singleThreadExecutorService : singleThreadExecutorServices ) { shutdownExecutor ( singleThreadExecutorService ) ; } shutdownExecutor ( getInternalScheduledExecutorService ( ) ) ; shutdownExecutor ( getInternalGpioExecutorService ( ) ) ; }
shutdown executor threads
21,378
public static void main ( String args [ ] ) throws InterruptedException , IOException { System . out . println ( "<--Pi4J ) ; pibrella . button ( ) . addListener ( new ButtonPressedListener ( ) { public void onButtonPressed ( ButtonEvent event ) { System . out . println ( "[BUTTON PRESSED]" ) ; pulseRate = 30 ; if ( sampleTuneThread . isAlive ( ) ) stopSampleTune ( ) ; else playSampleTune ( ) ; } } ) ; pibrella . button ( ) . addListener ( new ButtonReleasedListener ( ) { public void onButtonReleased ( ButtonEvent event ) { System . out . println ( "[BUTTON RELEASED]" ) ; pulseRate = 100 ; } } ) ; while ( true ) { for ( int index = PibrellaLed . RED . getIndex ( ) ; index <= PibrellaLed . GREEN . getIndex ( ) ; index ++ ) { pibrella . getLed ( index ) . pulse ( pulseRate , true ) ; } for ( int index = PibrellaLed . GREEN . getIndex ( ) ; index >= PibrellaLed . RED . getIndex ( ) ; index -- ) { pibrella . getLed ( index ) . pulse ( pulseRate , true ) ; } } }
Start Pibrella Example
21,379
public void updateGridDensity ( int currTime , double decayFactor , double dl , double dm ) { int lastAtt = this . getAttribute ( ) ; double densityOfG = ( Math . pow ( decayFactor , ( currTime - this . getDensityTimeStamp ( ) ) ) * this . getGridDensity ( ) ) ; this . setGridDensity ( densityOfG , currTime ) ; if ( this . isSparse ( dl ) ) this . attribute = SPARSE ; else if ( this . isDense ( dm ) ) this . attribute = DENSE ; else this . attribute = TRANSITIONAL ; if ( this . getAttribute ( ) == lastAtt ) this . attChange = false ; else this . attChange = true ; }
Implements the update the density of all grids step given at line 2 of both Fig 3 and Fig 4 of Chen and Tu 2007 .
21,380
public weka . core . Instance wekaInstance ( Instance inst ) { weka . core . Instance wekaInstance ; if ( ( ( InstanceImpl ) inst ) . instanceData instanceof SparseInstanceData ) { InstanceImpl instance = ( InstanceImpl ) inst ; SparseInstanceData sparseInstanceData = ( SparseInstanceData ) instance . instanceData ; wekaInstance = new weka . core . SparseInstance ( instance . weight ( ) , sparseInstanceData . getAttributeValues ( ) , sparseInstanceData . getIndexValues ( ) , sparseInstanceData . getNumberAttributes ( ) ) ; } else { Instance instance = inst ; wekaInstance = new weka . core . DenseInstance ( instance . weight ( ) , instance . toDoubleArray ( ) ) ; } if ( this . wekaInstanceInformation == null ) { this . wekaInstanceInformation = this . wekaInstancesInformation ( inst . dataset ( ) ) ; } wekaInstance . setDataset ( wekaInstanceInformation ) ; if ( inst . numOutputAttributes ( ) == 1 ) { wekaInstance . setClassValue ( inst . classValue ( ) ) ; } return wekaInstance ; }
Weka instance .
21,381
public weka . core . Instances wekaInstances ( Instances instances ) { weka . core . Instances wekaInstances = wekaInstancesInformation ( instances ) ; this . wekaInstanceInformation = wekaInstances ; for ( int i = 0 ; i < instances . numInstances ( ) ; i ++ ) { wekaInstances . add ( wekaInstance ( instances . instance ( i ) ) ) ; } return wekaInstances ; }
Weka instances .
21,382
public weka . core . Instances wekaInstancesInformation ( Instances instances ) { weka . core . Instances wekaInstances ; ArrayList < weka . core . Attribute > attInfo = new ArrayList < weka . core . Attribute > ( ) ; for ( int i = 0 ; i < instances . numAttributes ( ) ; i ++ ) { attInfo . add ( wekaAttribute ( i , instances . attribute ( i ) ) ) ; } wekaInstances = new weka . core . Instances ( instances . getRelationName ( ) , attInfo , 0 ) ; if ( instances . instanceInformation . numOutputAttributes ( ) == 1 ) { wekaInstances . setClassIndex ( instances . classIndex ( ) ) ; } else { wekaInstances . setClassIndex ( instances . instanceInformation . numOutputAttributes ( ) - 1 ) ; } return wekaInstances ; }
Weka instances information .
21,383
protected weka . core . Attribute wekaAttribute ( int index , Attribute attribute ) { weka . core . Attribute wekaAttribute ; if ( attribute . isNominal ( ) ) { wekaAttribute = new weka . core . Attribute ( attribute . name ( ) , attribute . getAttributeValues ( ) , index ) ; } else { wekaAttribute = new weka . core . Attribute ( attribute . name ( ) , index ) ; } return wekaAttribute ; }
Weka attribute .
21,384
protected void setGraph ( MeasureCollection [ ] measures , MeasureCollection [ ] stds , Color [ ] colors ) { this . measures = measures ; this . measureStds = stds ; this . colors = colors ; repaint ( ) ; }
Sets the graph by updating the measures and currently measure index . This method should not be directly called but may be used by subclasses to save space .
21,385
public static String stripPackagePrefix ( String className , Class < ? > expectedType ) { if ( className . startsWith ( expectedType . getPackage ( ) . getName ( ) ) ) { return className . substring ( expectedType . getPackage ( ) . getName ( ) . length ( ) + 1 ) ; } return className ; }
Gets the class name without its package name prefix .
21,386
public int [ ] [ ] getEMClusteringVariances ( double [ ] [ ] pointArray , int k ) { initFields ( pointArray , k ) ; setInitialPartitions ( pointArray , k ) ; double currentExpectation , newExpectation = 0.0 ; double expectationDeviation ; int count = 0 ; do { currentExpectation = newExpectation ; getNewClusterRepresentation ( ) ; calculateAllProbabilities ( ) ; newExpectation = expectation ( ) ; expectationDeviation = 1.0 - ( currentExpectation / newExpectation ) ; count ++ ; } while ( expectationDeviation > minDeviation && count < MAXITER ) ; return createProjectedClustering ( ) ; }
Performs an EM clustering on the provided data set !! Only the variances are calculated and used for point assignments ! !!! the number k of returned clusters might be smaller than k !!!
21,387
private void setInitialPartitions ( double [ ] [ ] pointArray , int k ) { if ( pointArray . length < k ) { System . err . println ( "cannot cluster less than k points into k clusters..." ) ; System . exit ( 0 ) ; } Random random = new Random ( randomSeed ) ; TreeSet < Integer > usedPoints = new TreeSet < Integer > ( ) ; int nextIndex ; for ( int i = 0 ; i < k ; i ++ ) { nextIndex = ( ( Double ) ( Math . floor ( random . nextDouble ( ) * n ) ) ) . intValue ( ) ; if ( usedPoints . contains ( nextIndex ) ) { i -- ; continue ; } else { for ( int d = 0 ; d < dim ; d ++ ) { clusterMeans [ i ] [ d ] = pointArray [ nextIndex ] [ d ] ; } } } int minDistIndex = 0 ; double minDist , currentDist ; for ( int x = 0 ; x < pointArray . length ; x ++ ) { minDist = Double . MAX_VALUE ; for ( int i = 0 ; i < k ; i ++ ) { currentDist = euclideanDistance ( clusterMeans [ i ] , pointArray [ x ] ) ; if ( currentDist < minDist ) { minDist = currentDist ; minDistIndex = i ; } } pCgivenX [ minDistIndex ] [ x ] = 1.0 ; } }
creates an initial partitioning
21,388
public void doLabelAcqReport ( Example < Instance > trainInst , int labelAcquired ) { this . acquisitionRateEstimator . add ( labelAcquired ) ; this . acquiredInstances += labelAcquired ; }
Receives the information if a label has been acquired and increases counters .
21,389
public static String removeSubstring ( String inString , String substring ) { StringBuffer result = new StringBuffer ( ) ; int oldLoc = 0 , loc = 0 ; while ( ( loc = inString . indexOf ( substring , oldLoc ) ) != - 1 ) { result . append ( inString . substring ( oldLoc , loc ) ) ; oldLoc = loc + substring . length ( ) ; } result . append ( inString . substring ( oldLoc ) ) ; return result . toString ( ) ; }
Removes all occurrences of a string from another string .
21,390
public static String replaceSubstring ( String inString , String subString , String replaceString ) { StringBuffer result = new StringBuffer ( ) ; int oldLoc = 0 , loc = 0 ; while ( ( loc = inString . indexOf ( subString , oldLoc ) ) != - 1 ) { result . append ( inString . substring ( oldLoc , loc ) ) ; result . append ( replaceString ) ; oldLoc = loc + subString . length ( ) ; } result . append ( inString . substring ( oldLoc ) ) ; return result . toString ( ) ; }
Replaces with a new string all occurrences of a string from another string .
21,391
public static String doubleToString ( double value , int afterDecimalPoint ) { StringBuffer stringBuffer ; double temp ; int dotPosition ; long precisionValue ; temp = value * Math . pow ( 10.0 , afterDecimalPoint ) ; if ( Math . abs ( temp ) < Long . MAX_VALUE ) { precisionValue = ( temp > 0 ) ? ( long ) ( temp + 0.5 ) : - ( long ) ( Math . abs ( temp ) + 0.5 ) ; if ( precisionValue == 0 ) { stringBuffer = new StringBuffer ( String . valueOf ( 0 ) ) ; } else { stringBuffer = new StringBuffer ( String . valueOf ( precisionValue ) ) ; } if ( afterDecimalPoint == 0 ) { return stringBuffer . toString ( ) ; } dotPosition = stringBuffer . length ( ) - afterDecimalPoint ; while ( ( ( precisionValue < 0 ) && ( dotPosition < 1 ) ) || ( dotPosition < 0 ) ) { if ( precisionValue < 0 ) { stringBuffer . insert ( 1 , '0' ) ; } else { stringBuffer . insert ( 0 , '0' ) ; } dotPosition ++ ; } stringBuffer . insert ( dotPosition , '.' ) ; if ( ( precisionValue < 0 ) && ( stringBuffer . charAt ( 1 ) == '.' ) ) { stringBuffer . insert ( 1 , '0' ) ; } else if ( stringBuffer . charAt ( 0 ) == '.' ) { stringBuffer . insert ( 0 , '0' ) ; } int currentPos = stringBuffer . length ( ) - 1 ; while ( ( currentPos > dotPosition ) && ( stringBuffer . charAt ( currentPos ) == '0' ) ) { stringBuffer . setCharAt ( currentPos -- , ' ' ) ; } if ( stringBuffer . charAt ( currentPos ) == '.' ) { stringBuffer . setCharAt ( currentPos , ' ' ) ; } return stringBuffer . toString ( ) . trim ( ) ; } return new String ( "" + value ) ; }
Rounds a double and converts it into String .
21,392
public static String doubleToString ( double value , int width , int afterDecimalPoint ) { String tempString = doubleToString ( value , afterDecimalPoint ) ; char [ ] result ; int dotPosition ; if ( ( afterDecimalPoint >= width ) || ( tempString . indexOf ( 'E' ) != - 1 ) ) { return tempString ; } result = new char [ width ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = ' ' ; } if ( afterDecimalPoint > 0 ) { dotPosition = tempString . indexOf ( '.' ) ; if ( dotPosition == - 1 ) { dotPosition = tempString . length ( ) ; } else { result [ width - afterDecimalPoint - 1 ] = '.' ; } } else { dotPosition = tempString . length ( ) ; } int offset = width - afterDecimalPoint - dotPosition ; if ( afterDecimalPoint > 0 ) { offset -- ; } if ( offset < 0 ) { return tempString ; } for ( int i = 0 ; i < dotPosition ; i ++ ) { result [ offset + i ] = tempString . charAt ( i ) ; } for ( int i = dotPosition + 1 ; i < tempString . length ( ) ; i ++ ) { result [ offset + i ] = tempString . charAt ( i ) ; } return new String ( result ) ; }
Rounds a double and converts it into a formatted decimal - justified String . Trailing 0 s are replaced with spaces .
21,393
public static void checkForRemainingOptions ( String [ ] options ) throws Exception { int illegalOptionsFound = 0 ; StringBuffer text = new StringBuffer ( ) ; if ( options == null ) { return ; } for ( int i = 0 ; i < options . length ; i ++ ) { if ( options [ i ] . length ( ) > 0 ) { illegalOptionsFound ++ ; text . append ( options [ i ] + ' ' ) ; } } if ( illegalOptionsFound > 0 ) { throw new Exception ( "Illegal options: " + text ) ; } }
Checks if the given array contains any non - empty options .
21,394
public static String convertNewLines ( String string ) { int index ; StringBuffer newStringBuffer = new StringBuffer ( ) ; while ( ( index = string . indexOf ( '\n' ) ) != - 1 ) { if ( index > 0 ) { newStringBuffer . append ( string . substring ( 0 , index ) ) ; } newStringBuffer . append ( '\\' ) ; newStringBuffer . append ( 'n' ) ; if ( ( index + 1 ) < string . length ( ) ) { string = string . substring ( index + 1 ) ; } else { string = "" ; } } newStringBuffer . append ( string ) ; string = newStringBuffer . toString ( ) ; newStringBuffer = new StringBuffer ( ) ; while ( ( index = string . indexOf ( '\r' ) ) != - 1 ) { if ( index > 0 ) { newStringBuffer . append ( string . substring ( 0 , index ) ) ; } newStringBuffer . append ( '\\' ) ; newStringBuffer . append ( 'r' ) ; if ( ( index + 1 ) < string . length ( ) ) { string = string . substring ( index + 1 ) ; } else { string = "" ; } } newStringBuffer . append ( string ) ; return newStringBuffer . toString ( ) ; }
Converts carriage returns and new lines in a string into \ r and \ n .
21,395
public static String [ ] splitOptions ( String quotedOptionString ) throws Exception { Vector < String > optionsVec = new Vector < String > ( ) ; String str = new String ( quotedOptionString ) ; int i ; while ( true ) { i = 0 ; while ( ( i < str . length ( ) ) && ( Character . isWhitespace ( str . charAt ( i ) ) ) ) i ++ ; str = str . substring ( i ) ; if ( str . length ( ) == 0 ) break ; if ( str . charAt ( 0 ) == '"' ) { i = 1 ; while ( i < str . length ( ) ) { if ( str . charAt ( i ) == str . charAt ( 0 ) ) break ; if ( str . charAt ( i ) == '\\' ) { i += 1 ; if ( i >= str . length ( ) ) throw new Exception ( "String should not finish with \\" ) ; } i += 1 ; } if ( i >= str . length ( ) ) throw new Exception ( "Quote parse error." ) ; String optStr = str . substring ( 1 , i ) ; optStr = unbackQuoteChars ( optStr ) ; optionsVec . addElement ( optStr ) ; str = str . substring ( i + 1 ) ; } else { i = 0 ; while ( ( i < str . length ( ) ) && ( ! Character . isWhitespace ( str . charAt ( i ) ) ) ) i ++ ; String optStr = str . substring ( 0 , i ) ; optionsVec . addElement ( optStr ) ; str = str . substring ( i ) ; } } String [ ] options = new String [ optionsVec . size ( ) ] ; for ( i = 0 ; i < optionsVec . size ( ) ; i ++ ) { options [ i ] = ( String ) optionsVec . elementAt ( i ) ; } return options ; }
Split up a string containing options into an array of strings one for each option .
21,396
public static String joinOptions ( String [ ] optionArray ) { String optionString = "" ; for ( int i = 0 ; i < optionArray . length ; i ++ ) { if ( optionArray [ i ] . equals ( "" ) ) { continue ; } boolean escape = false ; for ( int n = 0 ; n < optionArray [ i ] . length ( ) ; n ++ ) { if ( Character . isWhitespace ( optionArray [ i ] . charAt ( n ) ) ) { escape = true ; break ; } } if ( escape ) { optionString += '"' + backQuoteChars ( optionArray [ i ] ) + '"' ; } else { optionString += optionArray [ i ] ; } optionString += " " ; } return optionString . trim ( ) ; }
Joins all the options in an option array into a single string as might be used on the command line .
21,397
public static double info ( int counts [ ] ) { int total = 0 ; double x = 0 ; for ( int j = 0 ; j < counts . length ; j ++ ) { x -= xlogx ( counts [ j ] ) ; total += counts [ j ] ; } return x + xlogx ( total ) ; }
Computes entropy for an array of integers .
21,398
public static double kthSmallestValue ( int [ ] array , int k ) { int [ ] index = new int [ array . length ] ; for ( int i = 0 ; i < index . length ; i ++ ) { index [ i ] = i ; } return array [ index [ select ( array , index , 0 , array . length - 1 , k ) ] ] ; }
Returns the kth - smallest value in the array .
21,399
public static int maxIndex ( int [ ] ints ) { int maximum = 0 ; int maxIndex = 0 ; for ( int i = 0 ; i < ints . length ; i ++ ) { if ( ( i == 0 ) || ( ints [ i ] > maximum ) ) { maxIndex = i ; maximum = ints [ i ] ; } } return maxIndex ; }
Returns index of maximum element in a given array of integers . First maximum is returned .