id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
28,700
Netflix/spectator
spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/ServerGroup.java
ServerGroup.sequence
public String sequence() { return dN == asg.length() ? null : substr(asg, dN + 1, asg.length()); }
java
public String sequence() { return dN == asg.length() ? null : substr(asg, dN + 1, asg.length()); }
[ "public", "String", "sequence", "(", ")", "{", "return", "dN", "==", "asg", ".", "length", "(", ")", "?", "null", ":", "substr", "(", "asg", ",", "dN", "+", "1", ",", "asg", ".", "length", "(", ")", ")", ";", "}" ]
If the server group has a sequence number, then return it. Otherwise return null.
[ "If", "the", "server", "group", "has", "a", "sequence", "number", "then", "return", "it", ".", "Otherwise", "return", "null", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/ServerGroup.java#L138-L140
28,701
Netflix/spectator
spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcLogger.java
GcLogger.start
public synchronized void start(GcEventListener listener) { // TODO: this class has a bad mix of static fields used from an instance of the class. For now // this has been changed not to throw to make the dependency injection use-cases work. A // more general refactor of the GcLogger class is needed. if (notifListener != null) { LOGGER.warn("logger already started"); return; } eventListener = listener; notifListener = new GcNotificationListener(); for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) { if (mbean instanceof NotificationEmitter) { final NotificationEmitter emitter = (NotificationEmitter) mbean; emitter.addNotificationListener(notifListener, null, null); } } }
java
public synchronized void start(GcEventListener listener) { // TODO: this class has a bad mix of static fields used from an instance of the class. For now // this has been changed not to throw to make the dependency injection use-cases work. A // more general refactor of the GcLogger class is needed. if (notifListener != null) { LOGGER.warn("logger already started"); return; } eventListener = listener; notifListener = new GcNotificationListener(); for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) { if (mbean instanceof NotificationEmitter) { final NotificationEmitter emitter = (NotificationEmitter) mbean; emitter.addNotificationListener(notifListener, null, null); } } }
[ "public", "synchronized", "void", "start", "(", "GcEventListener", "listener", ")", "{", "// TODO: this class has a bad mix of static fields used from an instance of the class. For now", "// this has been changed not to throw to make the dependency injection use-cases work. A", "// more general refactor of the GcLogger class is needed.", "if", "(", "notifListener", "!=", "null", ")", "{", "LOGGER", ".", "warn", "(", "\"logger already started\"", ")", ";", "return", ";", "}", "eventListener", "=", "listener", ";", "notifListener", "=", "new", "GcNotificationListener", "(", ")", ";", "for", "(", "GarbageCollectorMXBean", "mbean", ":", "ManagementFactory", ".", "getGarbageCollectorMXBeans", "(", ")", ")", "{", "if", "(", "mbean", "instanceof", "NotificationEmitter", ")", "{", "final", "NotificationEmitter", "emitter", "=", "(", "NotificationEmitter", ")", "mbean", ";", "emitter", ".", "addNotificationListener", "(", "notifListener", ",", "null", ",", "null", ")", ";", "}", "}", "}" ]
Start collecting data about GC events. @param listener If not null, the listener will be called with the event objects after metrics and the log buffer is updated.
[ "Start", "collecting", "data", "about", "GC", "events", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcLogger.java#L119-L135
28,702
Netflix/spectator
spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcLogger.java
GcLogger.stop
public synchronized void stop() { Preconditions.checkState(notifListener != null, "logger has not been started"); for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) { if (mbean instanceof NotificationEmitter) { final NotificationEmitter emitter = (NotificationEmitter) mbean; try { emitter.removeNotificationListener(notifListener); } catch (ListenerNotFoundException e) { LOGGER.warn("could not remove gc listener", e); } } } notifListener = null; }
java
public synchronized void stop() { Preconditions.checkState(notifListener != null, "logger has not been started"); for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) { if (mbean instanceof NotificationEmitter) { final NotificationEmitter emitter = (NotificationEmitter) mbean; try { emitter.removeNotificationListener(notifListener); } catch (ListenerNotFoundException e) { LOGGER.warn("could not remove gc listener", e); } } } notifListener = null; }
[ "public", "synchronized", "void", "stop", "(", ")", "{", "Preconditions", ".", "checkState", "(", "notifListener", "!=", "null", ",", "\"logger has not been started\"", ")", ";", "for", "(", "GarbageCollectorMXBean", "mbean", ":", "ManagementFactory", ".", "getGarbageCollectorMXBeans", "(", ")", ")", "{", "if", "(", "mbean", "instanceof", "NotificationEmitter", ")", "{", "final", "NotificationEmitter", "emitter", "=", "(", "NotificationEmitter", ")", "mbean", ";", "try", "{", "emitter", ".", "removeNotificationListener", "(", "notifListener", ")", ";", "}", "catch", "(", "ListenerNotFoundException", "e", ")", "{", "LOGGER", ".", "warn", "(", "\"could not remove gc listener\"", ",", "e", ")", ";", "}", "}", "}", "notifListener", "=", "null", ";", "}" ]
Stop collecting GC events.
[ "Stop", "collecting", "GC", "events", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcLogger.java#L138-L151
28,703
Netflix/spectator
spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcLogger.java
GcLogger.getLogs
public List<GcEvent> getLogs() { final List<GcEvent> logs = new ArrayList<>(); for (CircularBuffer<GcEvent> buffer : gcLogs.values()) { logs.addAll(buffer.toList()); } Collections.sort(logs, GcEvent.REVERSE_TIME_ORDER); return logs; }
java
public List<GcEvent> getLogs() { final List<GcEvent> logs = new ArrayList<>(); for (CircularBuffer<GcEvent> buffer : gcLogs.values()) { logs.addAll(buffer.toList()); } Collections.sort(logs, GcEvent.REVERSE_TIME_ORDER); return logs; }
[ "public", "List", "<", "GcEvent", ">", "getLogs", "(", ")", "{", "final", "List", "<", "GcEvent", ">", "logs", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "CircularBuffer", "<", "GcEvent", ">", "buffer", ":", "gcLogs", ".", "values", "(", ")", ")", "{", "logs", ".", "addAll", "(", "buffer", ".", "toList", "(", ")", ")", ";", "}", "Collections", ".", "sort", "(", "logs", ",", "GcEvent", ".", "REVERSE_TIME_ORDER", ")", ";", "return", "logs", ";", "}" ]
Return the current set of GC events in the in-memory log.
[ "Return", "the", "current", "set", "of", "GC", "events", "in", "the", "in", "-", "memory", "log", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/GcLogger.java#L154-L161
28,704
Netflix/spectator
spectator-ext-aws2/src/main/java/com/netflix/spectator/aws2/SpectatorExecutionInterceptor.java
SpectatorExecutionInterceptor.isStatusSet
private boolean isStatusSet(ExecutionAttributes attrs) { Boolean s = attrs.getAttribute(STATUS_IS_SET); return s != null && s; }
java
private boolean isStatusSet(ExecutionAttributes attrs) { Boolean s = attrs.getAttribute(STATUS_IS_SET); return s != null && s; }
[ "private", "boolean", "isStatusSet", "(", "ExecutionAttributes", "attrs", ")", "{", "Boolean", "s", "=", "attrs", ".", "getAttribute", "(", "STATUS_IS_SET", ")", ";", "return", "s", "!=", "null", "&&", "s", ";", "}" ]
For network errors there will not be a response so the status will not have been set. This method looks for a flag in the attributes to see if we need to close off the log entry for the attempt.
[ "For", "network", "errors", "there", "will", "not", "be", "a", "response", "so", "the", "status", "will", "not", "have", "been", "set", ".", "This", "method", "looks", "for", "a", "flag", "in", "the", "attributes", "to", "see", "if", "we", "need", "to", "close", "off", "the", "log", "entry", "for", "the", "attempt", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-aws2/src/main/java/com/netflix/spectator/aws2/SpectatorExecutionInterceptor.java#L73-L76
28,705
Netflix/spectator
spectator-reg-atlas/src/main/java/com/netflix/spectator/atlas/impl/Subscriptions.java
Subscriptions.update
public void update(Map<Subscription, Long> subs, long currentTime, long expirationTime) { // Update expiration time for existing subs and log new ones for (Subscription sub : expressions) { if (subs.put(sub, expirationTime) == null) { LOGGER.info("new subscription: {}", sub); } } // Remove any expired entries 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(); } } }
java
public void update(Map<Subscription, Long> subs, long currentTime, long expirationTime) { // Update expiration time for existing subs and log new ones for (Subscription sub : expressions) { if (subs.put(sub, expirationTime) == null) { LOGGER.info("new subscription: {}", sub); } } // Remove any expired entries 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(); } } }
[ "public", "void", "update", "(", "Map", "<", "Subscription", ",", "Long", ">", "subs", ",", "long", "currentTime", ",", "long", "expirationTime", ")", "{", "// Update expiration time for existing subs and log new ones", "for", "(", "Subscription", "sub", ":", "expressions", ")", "{", "if", "(", "subs", ".", "put", "(", "sub", ",", "expirationTime", ")", "==", "null", ")", "{", "LOGGER", ".", "info", "(", "\"new subscription: {}\"", ",", "sub", ")", ";", "}", "}", "// Remove any expired entries", "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. @param subs Existing subscriptions. The map value is the expiration time in millis since the epoch. @param currentTime Current time to use for checking if entries are expired. @param expirationTime Expiration time used for new and updated entries.
[ "Merge", "the", "subscriptions", "from", "this", "update", "into", "a", "map", "from", "subscriptions", "to", "expiration", "times", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-reg-atlas/src/main/java/com/netflix/spectator/atlas/impl/Subscriptions.java#L56-L73
28,706
Netflix/spectator
spectator-reg-micrometer/src/main/java/com/netflix/spectator/micrometer/MicrometerMeter.java
MicrometerMeter.convert
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; }
java
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; }
[ "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.
[ "Helper", "for", "converting", "Micrometer", "measurements", "to", "Spectator", "measurements", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-reg-micrometer/src/main/java/com/netflix/spectator/micrometer/MicrometerMeter.java#L46-L54
28,707
Netflix/spectator
spectator-api/src/main/java/com/netflix/spectator/api/ArrayTagSet.java
ArrayTagSet.create
static ArrayTagSet create(Iterable<Tag> tags) { return (tags instanceof ArrayTagSet) ? (ArrayTagSet) tags : EMPTY.addAll(tags); }
java
static ArrayTagSet create(Iterable<Tag> tags) { return (tags instanceof ArrayTagSet) ? (ArrayTagSet) tags : EMPTY.addAll(tags); }
[ "static", "ArrayTagSet", "create", "(", "Iterable", "<", "Tag", ">", "tags", ")", "{", "return", "(", "tags", "instanceof", "ArrayTagSet", ")", "?", "(", "ArrayTagSet", ")", "tags", ":", "EMPTY", ".", "addAll", "(", "tags", ")", ";", "}" ]
Create a new tag set.
[ "Create", "a", "new", "tag", "set", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/api/ArrayTagSet.java#L48-L50
28,708
Netflix/spectator
spectator-ext-gc/src/main/java/com/netflix/spectator/gc/CircularBuffer.java
CircularBuffer.add
void add(T item) { int i = nextIndex.getAndIncrement() % data.length(); data.set(i, item); }
java
void add(T item) { int i = nextIndex.getAndIncrement() % data.length(); data.set(i, item); }
[ "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.
[ "Add", "a", "new", "item", "to", "the", "buffer", ".", "If", "the", "buffer", "is", "full", "a", "previous", "entry", "will", "get", "overwritten", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/CircularBuffer.java#L38-L41
28,709
Netflix/spectator
spectator-ext-gc/src/main/java/com/netflix/spectator/gc/CircularBuffer.java
CircularBuffer.toList
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; }
java
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; }
[ "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.
[ "Return", "a", "list", "with", "a", "copy", "of", "the", "data", "in", "the", "buffer", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-gc/src/main/java/com/netflix/spectator/gc/CircularBuffer.java#L54-L63
28,710
Netflix/spectator
spectator-api/src/main/java/com/netflix/spectator/impl/Scheduler.java
Scheduler.newThreadFactory
private static ThreadFactory newThreadFactory(final String id) { return new ThreadFactory() { private final AtomicInteger next = new AtomicInteger(); @Override public Thread newThread(Runnable r) { final String name = "spectator-" + id + "-" + next.getAndIncrement(); final Thread t = new Thread(r, name); t.setDaemon(true); return t; } }; }
java
private static ThreadFactory newThreadFactory(final String id) { return new ThreadFactory() { private final AtomicInteger next = new AtomicInteger(); @Override public Thread newThread(Runnable r) { final String name = "spectator-" + id + "-" + next.getAndIncrement(); final Thread t = new Thread(r, name); t.setDaemon(true); return t; } }; }
[ "private", "static", "ThreadFactory", "newThreadFactory", "(", "final", "String", "id", ")", "{", "return", "new", "ThreadFactory", "(", ")", "{", "private", "final", "AtomicInteger", "next", "=", "new", "AtomicInteger", "(", ")", ";", "@", "Override", "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.
[ "Create", "a", "thread", "factory", "using", "thread", "names", "based", "on", "the", "id", ".", "All", "threads", "will", "be", "configured", "as", "daemon", "threads", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/Scheduler.java#L88-L99
28,711
Netflix/spectator
spectator-api/src/main/java/com/netflix/spectator/impl/Scheduler.java
Scheduler.schedule
public ScheduledFuture<?> schedule(Options options, Runnable task) { if (!started) { startThreads(); } DelayedTask t = new DelayedTask(clock, options, task); queue.put(t); return t; }
java
public ScheduledFuture<?> schedule(Options options, Runnable task) { if (!started) { startThreads(); } DelayedTask t = new DelayedTask(clock, options, task); queue.put(t); return t; }
[ "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. @param options Options for controlling the execution of the task. See {@link Options} for more information. @param task Task to execute. @return Future that can be used for cancelling the current and future executions of the task. There is no value associated with the task so the future is just for checking if it is still running to stopping it from running in the future.
[ "Schedule", "a", "repetitive", "task", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/Scheduler.java#L158-L165
28,712
Netflix/spectator
spectator-api/src/main/java/com/netflix/spectator/impl/Scheduler.java
Scheduler.shutdown
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; } } }
java
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; } } }
[ "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.
[ "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", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/Scheduler.java#L171-L179
28,713
Netflix/spectator
spectator-ext-jvm/src/main/java/com/netflix/spectator/jvm/JmxConfig.java
JmxConfig.from
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); } }
java
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); } }
[ "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.
[ "Create", "a", "new", "instance", "from", "the", "Typesafe", "Config", "object", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-jvm/src/main/java/com/netflix/spectator/jvm/JmxConfig.java#L35-L46
28,714
Netflix/spectator
spectator-api/src/main/java/com/netflix/spectator/impl/SwapMeter.java
SwapMeter.unwrap
@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; }
java
@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; }
[ "@", "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.
[ "If", "the", "values", "are", "nested", "then", "unwrap", "any", "that", "have", "the", "same", "registry", "instance", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-api/src/main/java/com/netflix/spectator/impl/SwapMeter.java#L85-L92
28,715
Netflix/spectator
spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/DoubleDistributionSummary.java
DoubleDistributionSummary.get
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; }
java
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; }
[ "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. @param registry Registry to use. @param id Identifier for the metric being registered. @return Distribution summary corresponding to the id.
[ "Get", "or", "create", "a", "double", "distribution", "summary", "with", "the", "specified", "id", "." ]
259318252770de3bad581b85adff187d8f2c6537
https://github.com/Netflix/spectator/blob/259318252770de3bad581b85adff187d8f2c6537/spectator-ext-sandbox/src/main/java/com/netflix/spectator/sandbox/DoubleDistributionSummary.java#L70-L82
28,716
Pi4J/pi4j
pi4j-example/src/main/java/odroid/xu4/SpiExample.java
SpiExample.read
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)); // print 4 digits with leading zeros } console.print(" |\r"); Thread.sleep(250); }
java
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)); // print 4 digits with leading zeros } console.print(" |\r"); Thread.sleep(250); }
[ "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", ")", ")", ";", "// print 4 digits with leading zeros", "}", "console", ".", "print", "(", "\" |\\r\"", ")", ";", "Thread", ".", "sleep", "(", "250", ")", ";", "}" ]
Read data via SPI bus from MCP3002 chip. @throws IOException
[ "Read", "data", "via", "SPI", "bus", "from", "MCP3002", "chip", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-example/src/main/java/odroid/xu4/SpiExample.java#L122-L129
28,717
Pi4J/pi4j
pi4j-example/src/main/java/odroid/xu4/SpiExample.java
SpiExample.getConversionValue
public static int getConversionValue(short channel) throws IOException { // create a data buffer and initialize a conversion request payload byte data[] = new byte[] { (byte) 0b00000001, // first byte, start bit (byte)(0b10000000 |( ((channel & 7) << 4))), // second byte transmitted -> (SGL/DIF = 1, D2=D1=D0=0) (byte) 0b00000000 // third byte transmitted....don't care }; // send conversion request to ADC chip via SPI channel byte[] result = spi.write(data); // calculate and return conversion value from result bytes int value = (result[1]<< 8) & 0b1100000000; //merge data[1] & data[2] to get 10-bit result value |= (result[2] & 0xff); return value; }
java
public static int getConversionValue(short channel) throws IOException { // create a data buffer and initialize a conversion request payload byte data[] = new byte[] { (byte) 0b00000001, // first byte, start bit (byte)(0b10000000 |( ((channel & 7) << 4))), // second byte transmitted -> (SGL/DIF = 1, D2=D1=D0=0) (byte) 0b00000000 // third byte transmitted....don't care }; // send conversion request to ADC chip via SPI channel byte[] result = spi.write(data); // calculate and return conversion value from result bytes int value = (result[1]<< 8) & 0b1100000000; //merge data[1] & data[2] to get 10-bit result value |= (result[2] & 0xff); return value; }
[ "public", "static", "int", "getConversionValue", "(", "short", "channel", ")", "throws", "IOException", "{", "// create a data buffer and initialize a conversion request payload", "byte", "data", "[", "]", "=", "new", "byte", "[", "]", "{", "(", "byte", ")", "0b00000001", ",", "// first byte, start bit", "(", "byte", ")", "(", "0b10000000", "|", "(", "(", "(", "channel", "&", "7", ")", "<<", "4", ")", ")", ")", ",", "// second byte transmitted -> (SGL/DIF = 1, D2=D1=D0=0)", "(", "byte", ")", "0b00000000", "// third byte transmitted....don't care", "}", ";", "// send conversion request to ADC chip via SPI channel", "byte", "[", "]", "result", "=", "spi", ".", "write", "(", "data", ")", ";", "// calculate and return conversion value from result bytes", "int", "value", "=", "(", "result", "[", "1", "]", "<<", "8", ")", "&", "0b1100000000", ";", "//merge data[1] & data[2] to get 10-bit result", "value", "|=", "(", "result", "[", "2", "]", "&", "0xff", ")", ";", "return", "value", ";", "}" ]
Communicate to the ADC chip via SPI to get single-ended conversion value for a specified channel. @param channel analog input channel on ADC chip @return conversion value for specified analog input channel @throws IOException
[ "Communicate", "to", "the", "ADC", "chip", "via", "SPI", "to", "get", "single", "-", "ended", "conversion", "value", "for", "a", "specified", "channel", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-example/src/main/java/odroid/xu4/SpiExample.java#L138-L154
28,718
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/platform/PlatformManager.java
PlatformManager.setPlatform
public static void setPlatform(Platform platform) throws PlatformAlreadyAssignedException { // prevent changing the platform once it has been initially set if(PlatformManager.platform != null){ throw new PlatformAlreadyAssignedException(PlatformManager.platform); } // set internal platform instance PlatformManager.platform = platform; // apply Pi4J platform system property System.setProperty("pi4j.platform", platform.id()); }
java
public static void setPlatform(Platform platform) throws PlatformAlreadyAssignedException { // prevent changing the platform once it has been initially set if(PlatformManager.platform != null){ throw new PlatformAlreadyAssignedException(PlatformManager.platform); } // set internal platform instance PlatformManager.platform = platform; // apply Pi4J platform system property System.setProperty("pi4j.platform", platform.id()); }
[ "public", "static", "void", "setPlatform", "(", "Platform", "platform", ")", "throws", "PlatformAlreadyAssignedException", "{", "// prevent changing the platform once it has been initially set", "if", "(", "PlatformManager", ".", "platform", "!=", "null", ")", "{", "throw", "new", "PlatformAlreadyAssignedException", "(", "PlatformManager", ".", "platform", ")", ";", "}", "// set internal platform instance", "PlatformManager", ".", "platform", "=", "platform", ";", "// apply Pi4J platform system property", "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. @param platform platform to assign @throws PlatformAlreadyAssignedException
[ "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", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/platform/PlatformManager.java#L82-L93
28,719
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/platform/PlatformManager.java
PlatformManager.getDefaultPlatform
protected static Platform getDefaultPlatform(){ // attempt to get assigned platform identifier from the environment variables String envPlatformId = System.getenv("PI4J_PLATFORM"); // attempt to get assigned platform identifier from the system properties String platformId = System.getProperty("pi4j.platform", envPlatformId); // if a platform id was found in the system properties, then // attempt to lookup the platform enumeration using the platform // identifier string. If found then return the platform enum. if(platformId != null && !platformId.isEmpty()){ Platform pltfrm = Platform.fromId(platformId); if(pltfrm != null){ return pltfrm; } } // the RASPBERRY_PI is the default platform; // (... in time perhaps some auto-platform detection could be implemented here ...) return Platform.RASPBERRYPI; }
java
protected static Platform getDefaultPlatform(){ // attempt to get assigned platform identifier from the environment variables String envPlatformId = System.getenv("PI4J_PLATFORM"); // attempt to get assigned platform identifier from the system properties String platformId = System.getProperty("pi4j.platform", envPlatformId); // if a platform id was found in the system properties, then // attempt to lookup the platform enumeration using the platform // identifier string. If found then return the platform enum. if(platformId != null && !platformId.isEmpty()){ Platform pltfrm = Platform.fromId(platformId); if(pltfrm != null){ return pltfrm; } } // the RASPBERRY_PI is the default platform; // (... in time perhaps some auto-platform detection could be implemented here ...) return Platform.RASPBERRYPI; }
[ "protected", "static", "Platform", "getDefaultPlatform", "(", ")", "{", "// attempt to get assigned platform identifier from the environment variables", "String", "envPlatformId", "=", "System", ".", "getenv", "(", "\"PI4J_PLATFORM\"", ")", ";", "// attempt to get assigned platform identifier from the system properties", "String", "platformId", "=", "System", ".", "getProperty", "(", "\"pi4j.platform\"", ",", "envPlatformId", ")", ";", "// if a platform id was found in the system properties, then", "// attempt to lookup the platform enumeration using the platform", "// identifier string. If found then return the platform enum.", "if", "(", "platformId", "!=", "null", "&&", "!", "platformId", ".", "isEmpty", "(", ")", ")", "{", "Platform", "pltfrm", "=", "Platform", ".", "fromId", "(", "platformId", ")", ";", "if", "(", "pltfrm", "!=", "null", ")", "{", "return", "pltfrm", ";", "}", "}", "// the RASPBERRY_PI is the default platform;", "// (... in time perhaps some auto-platform detection could be implemented here ...)", "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. @return default platform enumeration
[ "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", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/platform/PlatformManager.java#L105-L125
28,720
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/w1/W1Master.java
W1Master.getDeviceIDs
public List<String> getDeviceIDs() { final List<String> ids = new ArrayList<>(); for (final File deviceDir : getDeviceDirs()) { ids.add(deviceDir.getName()); } /* * //for (final W1Device device: devices) { ids.add(device.getId()); */ return ids; }
java
public List<String> getDeviceIDs() { final List<String> ids = new ArrayList<>(); for (final File deviceDir : getDeviceDirs()) { ids.add(deviceDir.getName()); } /* * //for (final W1Device device: devices) { ids.add(device.getId()); */ return ids; }
[ "public", "List", "<", "String", ">", "getDeviceIDs", "(", ")", "{", "final", "List", "<", "String", ">", "ids", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "final", "File", "deviceDir", ":", "getDeviceDirs", "(", ")", ")", "{", "ids", ".", "add", "(", "deviceDir", ".", "getName", "(", ")", ")", ";", "}", "/*\n * //for (final W1Device device: devices) { ids.add(device.getId());\n */", "return", "ids", ";", "}" ]
Gets a list of all registered slave device ids. @return list of slave ids, can be empty, never null.
[ "Gets", "a", "list", "of", "all", "registered", "slave", "device", "ids", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/w1/W1Master.java#L172-L181
28,721
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/w1/W1Master.java
W1Master.getDevices
@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; }
java
@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; }
[ "@", "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. @param type @param <T> @return
[ "Get", "a", "list", "of", "devices", "that", "implement", "a", "certain", "interface", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/w1/W1Master.java#L239-L249
28,722
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java
MicrochipPotentiometerDeviceController.getDeviceStatus
public DeviceControllerDeviceStatus getDeviceStatus() throws IOException { // get status from device int deviceStatus = read(MEMADDR_STATUS); // check formal criterias 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) + "'!"); } // build the result 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); }
java
public DeviceControllerDeviceStatus getDeviceStatus() throws IOException { // get status from device int deviceStatus = read(MEMADDR_STATUS); // check formal criterias 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) + "'!"); } // build the result 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); }
[ "public", "DeviceControllerDeviceStatus", "getDeviceStatus", "(", ")", "throws", "IOException", "{", "// get status from device", "int", "deviceStatus", "=", "read", "(", "MEMADDR_STATUS", ")", ";", "// check formal criterias", "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", ")", "+", "\"'!\"", ")", ";", "}", "// build the result", "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. @return The device's status @throws IOException Thrown if communication fails or device returned a malformed result
[ "Returns", "the", "status", "of", "the", "device", "according", "EEPROM", "and", "WiperLocks", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L121-L149
28,723
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java
MicrochipPotentiometerDeviceController.increase
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'"); } // decrease only works on volatile-wiper byte memAddr = channel.getVolatileMemoryAddress(); increaseOrDecrease(memAddr, true, steps); }
java
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'"); } // decrease only works on volatile-wiper byte memAddr = channel.getVolatileMemoryAddress(); increaseOrDecrease(memAddr, true, steps); }
[ "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'\"", ")", ";", "}", "// decrease only works on volatile-wiper", "byte", "memAddr", "=", "channel", ".", "getVolatileMemoryAddress", "(", ")", ";", "increaseOrDecrease", "(", "memAddr", ",", "true", ",", "steps", ")", ";", "}" ]
Increments the volatile wiper for the given number steps. @param channel Which wiper @param steps The number of steps @throws IOException Thrown if communication fails or device returned a malformed result
[ "Increments", "the", "volatile", "wiper", "for", "the", "given", "number", "steps", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L158-L172
28,724
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java
MicrochipPotentiometerDeviceController.decrease
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'"); } // decrease only works on volatile-wiper byte memAddr = channel.getVolatileMemoryAddress(); increaseOrDecrease(memAddr, false, steps); }
java
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'"); } // decrease only works on volatile-wiper byte memAddr = channel.getVolatileMemoryAddress(); increaseOrDecrease(memAddr, false, steps); }
[ "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'\"", ")", ";", "}", "// decrease only works on volatile-wiper", "byte", "memAddr", "=", "channel", ".", "getVolatileMemoryAddress", "(", ")", ";", "increaseOrDecrease", "(", "memAddr", ",", "false", ",", "steps", ")", ";", "}" ]
Decrements the volatile wiper for the given number steps. @param channel Which wiper @param steps The number of steps @throws IOException Thrown if communication fails or device returned a malformed result
[ "Decrements", "the", "volatile", "wiper", "for", "the", "given", "number", "steps", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L181-L195
28,725
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java
MicrochipPotentiometerDeviceController.getValue
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'"); } // choose proper memory address (see TABLE 4-1) byte memAddr = nonVolatile ? channel.getNonVolatileMemoryAddress() : channel.getVolatileMemoryAddress(); // read current value int currentValue = read(memAddr); return currentValue; }
java
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'"); } // choose proper memory address (see TABLE 4-1) byte memAddr = nonVolatile ? channel.getNonVolatileMemoryAddress() : channel.getVolatileMemoryAddress(); // read current value int currentValue = read(memAddr); return currentValue; }
[ "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'\"", ")", ";", "}", "// choose proper memory address (see TABLE 4-1)", "byte", "memAddr", "=", "nonVolatile", "?", "channel", ".", "getNonVolatileMemoryAddress", "(", ")", ":", "channel", ".", "getVolatileMemoryAddress", "(", ")", ";", "// read current value", "int", "currentValue", "=", "read", "(", "memAddr", ")", ";", "return", "currentValue", ";", "}" ]
Receives the current wiper's value from the device. @param channel Which wiper @param nonVolatile volatile or non-volatile value @return The wiper's value @throws IOException Thrown if communication fails or device returned a malformed result
[ "Receives", "the", "current", "wiper", "s", "value", "from", "the", "device", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L205-L224
28,726
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java
MicrochipPotentiometerDeviceController.setValue
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() + "'"); } // choose proper memory address (see TABLE 4-1) byte memAddr = nonVolatile ? channel.getNonVolatileMemoryAddress() : channel.getVolatileMemoryAddress(); // write the value to the device write(memAddr, value); }
java
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() + "'"); } // choose proper memory address (see TABLE 4-1) byte memAddr = nonVolatile ? channel.getNonVolatileMemoryAddress() : channel.getVolatileMemoryAddress(); // write the value to the device write(memAddr, value); }
[ "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", "(", ")", "+", "\"'\"", ")", ";", "}", "// choose proper memory address (see TABLE 4-1)", "byte", "memAddr", "=", "nonVolatile", "?", "channel", ".", "getNonVolatileMemoryAddress", "(", ")", ":", "channel", ".", "getVolatileMemoryAddress", "(", ")", ";", "// write the value to the device", "write", "(", "memAddr", ",", "value", ")", ";", "}" ]
Sets the wiper's value in the device. @param channel Which wiper @param value The wiper's value @param nonVolatile volatile or non-volatile value @throws IOException Thrown if communication fails or device returned a malformed result
[ "Sets", "the", "wiper", "s", "value", "in", "the", "device", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L234-L256
28,727
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java
MicrochipPotentiometerDeviceController.getTerminalConfiguration
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'"); } // read configuration from device int tcon = read(channel.getTerminalControllAddress()); // build result 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); }
java
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'"); } // read configuration from device int tcon = read(channel.getTerminalControllAddress()); // build result 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); }
[ "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'\"", ")", ";", "}", "// read configuration from device", "int", "tcon", "=", "read", "(", "channel", ".", "getTerminalControllAddress", "(", ")", ")", ";", "// build result", "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. @param channel The channel @return The current terminal-configuration @throws IOException Thrown if communication fails or device returned a malformed result
[ "Fetches", "the", "terminal", "-", "configuration", "from", "the", "device", "for", "a", "certain", "channel", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L265-L286
28,728
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java
MicrochipPotentiometerDeviceController.setTerminalConfiguration
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(); // read current configuration from device int tcon = read(memAddr); // modify configuration 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 new configuration to device write(memAddr, tcon); }
java
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(); // read current configuration from device int tcon = read(memAddr); // modify configuration 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 new configuration to device write(memAddr, tcon); }
[ "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", "(", ")", ";", "// read current configuration from device", "int", "tcon", "=", "read", "(", "memAddr", ")", ";", "// modify configuration", "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 new configuration to device", "write", "(", "memAddr", ",", "tcon", ")", ";", "}" ]
Sets the given terminal-configuration to the device. @param config A terminal-configuration for a certain channel. @throws IOException Thrown if communication fails or device returned a malformed result
[ "Sets", "the", "given", "terminal", "-", "configuration", "to", "the", "device", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L294-L325
28,729
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java
MicrochipPotentiometerDeviceController.read
private int read(final byte memAddr) throws IOException { // ask device for reading data - see FIGURE 7-5 byte[] cmd = new byte[] { (byte) ((memAddr << 4) | CMD_READ) }; // read two bytes 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); } // transform signed byte to unsigned byte stored as int int first = buf[0] & 0xFF; int second = buf[1] & 0xFF; // interpret two bytes as one integer return (first << 8) | second; }
java
private int read(final byte memAddr) throws IOException { // ask device for reading data - see FIGURE 7-5 byte[] cmd = new byte[] { (byte) ((memAddr << 4) | CMD_READ) }; // read two bytes 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); } // transform signed byte to unsigned byte stored as int int first = buf[0] & 0xFF; int second = buf[1] & 0xFF; // interpret two bytes as one integer return (first << 8) | second; }
[ "private", "int", "read", "(", "final", "byte", "memAddr", ")", "throws", "IOException", "{", "// ask device for reading data - see FIGURE 7-5", "byte", "[", "]", "cmd", "=", "new", "byte", "[", "]", "{", "(", "byte", ")", "(", "(", "memAddr", "<<", "4", ")", "|", "CMD_READ", ")", "}", ";", "// read two bytes", "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", ")", ";", "}", "// transform signed byte to unsigned byte stored as int", "int", "first", "=", "buf", "[", "0", "]", "&", "0xFF", ";", "int", "second", "=", "buf", "[", "1", "]", "&", "0xFF", ";", "// interpret two bytes as one integer", "return", "(", "first", "<<", "8", ")", "|", "second", ";", "}" ]
Reads two bytes from the devices at the given memory-address. @param memAddr The memory-address to read from @return The two bytes read @throws IOException Thrown if communication fails or device returned a malformed result
[ "Reads", "two", "bytes", "from", "the", "devices", "at", "the", "given", "memory", "-", "address", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L396-L416
28,730
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java
MicrochipPotentiometerDeviceController.write
private void write(final byte memAddr, final int value) throws IOException { // bit 8 of value byte firstBit = (byte) ((value >> 8) & 0x000001); // ask device for setting a value - see FIGURE 7-2 byte cmd = (byte) ((memAddr << 4) | CMD_WRITE | firstBit); // 7 bits of value byte data = (byte) (value & 0x00FF); // write sequence of cmd and data to the device byte[] sequence = new byte[] { cmd, data }; i2cDevice.write(sequence, 0, sequence.length); }
java
private void write(final byte memAddr, final int value) throws IOException { // bit 8 of value byte firstBit = (byte) ((value >> 8) & 0x000001); // ask device for setting a value - see FIGURE 7-2 byte cmd = (byte) ((memAddr << 4) | CMD_WRITE | firstBit); // 7 bits of value byte data = (byte) (value & 0x00FF); // write sequence of cmd and data to the device byte[] sequence = new byte[] { cmd, data }; i2cDevice.write(sequence, 0, sequence.length); }
[ "private", "void", "write", "(", "final", "byte", "memAddr", ",", "final", "int", "value", ")", "throws", "IOException", "{", "// bit 8 of value", "byte", "firstBit", "=", "(", "byte", ")", "(", "(", "value", ">>", "8", ")", "&", "0x000001", ")", ";", "// ask device for setting a value - see FIGURE 7-2", "byte", "cmd", "=", "(", "byte", ")", "(", "(", "memAddr", "<<", "4", ")", "|", "CMD_WRITE", "|", "firstBit", ")", ";", "// 7 bits of value", "byte", "data", "=", "(", "byte", ")", "(", "value", "&", "0x00FF", ")", ";", "// write sequence of cmd and data to the device", "byte", "[", "]", "sequence", "=", "new", "byte", "[", "]", "{", "cmd", ",", "data", "}", ";", "i2cDevice", ".", "write", "(", "sequence", ",", "0", ",", "sequence", ".", "length", ")", ";", "}" ]
Writes 9 bits of the given value to the device. @param memAddr The memory-address to write to @param value The value to be written @throws IOException Thrown if communication fails or device returned a malformed result
[ "Writes", "9", "bits", "of", "the", "given", "value", "to", "the", "device", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerDeviceController.java#L425-L440
28,731
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/i2c/impl/I2CBusImpl.java
I2CBusImpl.selectBusSlave
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); } }
java
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); } }
[ "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. @param device Device to select
[ "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", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/i2c/impl/I2CBusImpl.java#L285-L293
28,732
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/gpio/PinProvider.java
PinProvider.allPins
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]); }
java
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]); }
[ "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. @param mode one or more pin modes that you wish to include in the result set @return pin instances that support the provided pin modes
[ "Get", "all", "pin", "instances", "from", "this", "provider", "that", "support", "one", "of", "the", "provided", "pin", "modes", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/gpio/PinProvider.java#L119-L131
28,733
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/sensor/impl/GpioSensorComponent.java
GpioSensorComponent.getState
@Override public SensorState getState() { if(pin.isState(openState)) return SensorState.OPEN; else return SensorState.CLOSED; }
java
@Override public SensorState getState() { if(pin.isState(openState)) return SensorState.OPEN; else return SensorState.CLOSED; }
[ "@", "Override", "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. @return PowerState
[ "Return", "the", "current", "sensor", "state", "based", "on", "the", "GPIO", "digital", "output", "pin", "state", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/sensor/impl/GpioSensorComponent.java#L97-L103
28,734
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/spi/SpiFactory.java
SpiFactory.getInstance
public static SpiDevice getInstance(SpiChannel channel, SpiMode mode) throws IOException { return new SpiDeviceImpl(channel, mode); }
java
public static SpiDevice getInstance(SpiChannel channel, SpiMode mode) throws IOException { return new SpiDeviceImpl(channel, mode); }
[ "public", "static", "SpiDevice", "getInstance", "(", "SpiChannel", "channel", ",", "SpiMode", "mode", ")", "throws", "IOException", "{", "return", "new", "SpiDeviceImpl", "(", "channel", ",", "mode", ")", ";", "}" ]
Create new SpiDevice instance @param channel spi channel to use @param mode spi mode (see http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Mode_numbers) @return Return a new SpiDevice impl instance. @throws java.io.IOException
[ "Create", "new", "SpiDevice", "instance" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/spi/SpiFactory.java#L75-L77
28,735
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/mcp/MCP4725GpioProvider.java
MCP4725GpioProvider.setValue
@Override public void setValue(Pin pin, double value) { // validate range if(value <= getMinSupportedValue()){ value = getMinSupportedValue(); } else if(value >= getMaxSupportedValue()){ value = getMaxSupportedValue(); } // the DAC only supports integer values between 0..4095 int write_value = (int)value; try { // create data packet and seed targeted value byte packet[] = new byte[3]; packet[0] = (byte) MCP4725_REG_WRITEDAC; packet[1] = (byte) (write_value >> 4); // Upper data bits (D11.D10.D9.D8.D7.D6.D5.D4) packet[2] = (byte) (write_value << 4); // Lower data bits (D3.D2.D1.D0.x.x.x.x) // write packet of data to the I2C bus device.write(packet, 0, 3); // update the pin cache and dispatch any events super.setValue(pin, value); } catch (IOException e) { throw new RuntimeException("Unable to write DAC output value.", e); } }
java
@Override public void setValue(Pin pin, double value) { // validate range if(value <= getMinSupportedValue()){ value = getMinSupportedValue(); } else if(value >= getMaxSupportedValue()){ value = getMaxSupportedValue(); } // the DAC only supports integer values between 0..4095 int write_value = (int)value; try { // create data packet and seed targeted value byte packet[] = new byte[3]; packet[0] = (byte) MCP4725_REG_WRITEDAC; packet[1] = (byte) (write_value >> 4); // Upper data bits (D11.D10.D9.D8.D7.D6.D5.D4) packet[2] = (byte) (write_value << 4); // Lower data bits (D3.D2.D1.D0.x.x.x.x) // write packet of data to the I2C bus device.write(packet, 0, 3); // update the pin cache and dispatch any events super.setValue(pin, value); } catch (IOException e) { throw new RuntimeException("Unable to write DAC output value.", e); } }
[ "@", "Override", "public", "void", "setValue", "(", "Pin", "pin", ",", "double", "value", ")", "{", "// validate range", "if", "(", "value", "<=", "getMinSupportedValue", "(", ")", ")", "{", "value", "=", "getMinSupportedValue", "(", ")", ";", "}", "else", "if", "(", "value", ">=", "getMaxSupportedValue", "(", ")", ")", "{", "value", "=", "getMaxSupportedValue", "(", ")", ";", "}", "// the DAC only supports integer values between 0..4095", "int", "write_value", "=", "(", "int", ")", "value", ";", "try", "{", "// create data packet and seed targeted value", "byte", "packet", "[", "]", "=", "new", "byte", "[", "3", "]", ";", "packet", "[", "0", "]", "=", "(", "byte", ")", "MCP4725_REG_WRITEDAC", ";", "packet", "[", "1", "]", "=", "(", "byte", ")", "(", "write_value", ">>", "4", ")", ";", "// Upper data bits (D11.D10.D9.D8.D7.D6.D5.D4)", "packet", "[", "2", "]", "=", "(", "byte", ")", "(", "write_value", "<<", "4", ")", ";", "// Lower data bits (D3.D2.D1.D0.x.x.x.x)", "// write packet of data to the I2C bus", "device", ".", "write", "(", "packet", ",", "0", ",", "3", ")", ";", "// update the pin cache and dispatch any events", "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. @param pin analog output pin @param value raw value to send to the DAC. (Between: 0..4095)
[ "Set", "the", "analog", "output", "value", "to", "an", "output", "pin", "on", "the", "DAC", "immediately", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/mcp/MCP4725GpioProvider.java#L135-L164
28,736
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java
MicrochipPotentiometerBase.initialize
protected void initialize(final int initialValueForVolatileWipers) throws IOException { if (isCapableOfNonVolatileWiper()) { // the device's volatile-wiper will be set to the value stored // in the non-volatile memory. so for those devices the wiper's // current value has to be retrieved currentValue = controller.getValue( DeviceControllerChannel.valueOf(channel), false); } else { // check boundaries final int newInitialValueForVolatileWipers = getValueAccordingBoundaries(initialValueForVolatileWipers); controller.setValue(DeviceControllerChannel.valueOf(channel), newInitialValueForVolatileWipers, MicrochipPotentiometerDeviceController.VOLATILE_WIPER); currentValue = newInitialValueForVolatileWipers; } }
java
protected void initialize(final int initialValueForVolatileWipers) throws IOException { if (isCapableOfNonVolatileWiper()) { // the device's volatile-wiper will be set to the value stored // in the non-volatile memory. so for those devices the wiper's // current value has to be retrieved currentValue = controller.getValue( DeviceControllerChannel.valueOf(channel), false); } else { // check boundaries final int newInitialValueForVolatileWipers = getValueAccordingBoundaries(initialValueForVolatileWipers); controller.setValue(DeviceControllerChannel.valueOf(channel), newInitialValueForVolatileWipers, MicrochipPotentiometerDeviceController.VOLATILE_WIPER); currentValue = newInitialValueForVolatileWipers; } }
[ "protected", "void", "initialize", "(", "final", "int", "initialValueForVolatileWipers", ")", "throws", "IOException", "{", "if", "(", "isCapableOfNonVolatileWiper", "(", ")", ")", "{", "// the device's volatile-wiper will be set to the value stored", "// in the non-volatile memory. so for those devices the wiper's", "// current value has to be retrieved", "currentValue", "=", "controller", ".", "getValue", "(", "DeviceControllerChannel", ".", "valueOf", "(", "channel", ")", ",", "false", ")", ";", "}", "else", "{", "// check boundaries", "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. @param initialValueForVolatileWipers The initial value for devices not capable @throws IOException Thrown if communication fails or device returned a malformed result
[ "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", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java#L208-L232
28,737
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java
MicrochipPotentiometerBase.updateCacheFromDevice
@Override public int updateCacheFromDevice() throws IOException { currentValue = controller.getValue(DeviceControllerChannel.valueOf(channel), false); return currentValue; }
java
@Override public int updateCacheFromDevice() throws IOException { currentValue = controller.getValue(DeviceControllerChannel.valueOf(channel), false); return currentValue; }
[ "@", "Override", "public", "int", "updateCacheFromDevice", "(", ")", "throws", "IOException", "{", "currentValue", "=", "controller", ".", "getValue", "(", "DeviceControllerChannel", ".", "valueOf", "(", "channel", ")", ",", "false", ")", ";", "return", "currentValue", ";", "}" ]
Updates the cache to the wiper's value. @return The wiper's current value @throws IOException Thrown if communication fails or device returned a malformed result
[ "Updates", "the", "cache", "to", "the", "wiper", "s", "value", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java#L327-L333
28,738
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java
MicrochipPotentiometerBase.decrease
@Override 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!"); } // check boundaries final int actualSteps; if (steps > currentValue) { actualSteps = currentValue; } else { actualSteps = steps; } int newValue = currentValue - actualSteps; // if lower-boundary then set value in device to ensure sync // and for a large number of steps it is better to set a new value if ((newValue == 0) || (steps > 5)) { setCurrentValue(newValue); } // for a small number of steps use 'decrease'-method else { controller.decrease(DeviceControllerChannel.valueOf(channel), actualSteps); currentValue = newValue; } }
java
@Override 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!"); } // check boundaries final int actualSteps; if (steps > currentValue) { actualSteps = currentValue; } else { actualSteps = steps; } int newValue = currentValue - actualSteps; // if lower-boundary then set value in device to ensure sync // and for a large number of steps it is better to set a new value if ((newValue == 0) || (steps > 5)) { setCurrentValue(newValue); } // for a small number of steps use 'decrease'-method else { controller.decrease(DeviceControllerChannel.valueOf(channel), actualSteps); currentValue = newValue; } }
[ "@", "Override", "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!\"", ")", ";", "}", "// check boundaries", "final", "int", "actualSteps", ";", "if", "(", "steps", ">", "currentValue", ")", "{", "actualSteps", "=", "currentValue", ";", "}", "else", "{", "actualSteps", "=", "steps", ";", "}", "int", "newValue", "=", "currentValue", "-", "actualSteps", ";", "// if lower-boundary then set value in device to ensure sync", "// and for a large number of steps it is better to set a new value", "if", "(", "(", "newValue", "==", "0", ")", "||", "(", "steps", ">", "5", ")", ")", "{", "setCurrentValue", "(", "newValue", ")", ";", "}", "// for a small number of steps use 'decrease'-method", "else", "{", "controller", ".", "decrease", "(", "DeviceControllerChannel", ".", "valueOf", "(", "channel", ")", ",", "actualSteps", ")", ";", "currentValue", "=", "newValue", ";", "}", "}" ]
Decreases the wiper's value for n steps. @param steps The number of steps to decrease @throws IOException Thrown if communication fails or device returned a malformed result
[ "Decreases", "the", "wiper", "s", "value", "for", "n", "steps", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java#L444-L484
28,739
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java
MicrochipPotentiometerBase.increase
@Override 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!"); } // check boundaries final int actualSteps; if ((steps + currentValue) > maxValue) { actualSteps = maxValue - currentValue; } else { actualSteps = steps; } int newValue = currentValue + actualSteps; // if upper-boundary then set value in device to ensure sync // and for a large number of steps it is better to set a new value if ((newValue == maxValue) || (steps > 5)) { setCurrentValue(newValue); } // for a small number of step simply repeat 'increase'-commands else { controller.increase(DeviceControllerChannel.valueOf(channel), actualSteps); currentValue = newValue; } }
java
@Override 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!"); } // check boundaries final int actualSteps; if ((steps + currentValue) > maxValue) { actualSteps = maxValue - currentValue; } else { actualSteps = steps; } int newValue = currentValue + actualSteps; // if upper-boundary then set value in device to ensure sync // and for a large number of steps it is better to set a new value if ((newValue == maxValue) || (steps > 5)) { setCurrentValue(newValue); } // for a small number of step simply repeat 'increase'-commands else { controller.increase(DeviceControllerChannel.valueOf(channel), actualSteps); currentValue = newValue; } }
[ "@", "Override", "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!\"", ")", ";", "}", "// check boundaries", "final", "int", "actualSteps", ";", "if", "(", "(", "steps", "+", "currentValue", ")", ">", "maxValue", ")", "{", "actualSteps", "=", "maxValue", "-", "currentValue", ";", "}", "else", "{", "actualSteps", "=", "steps", ";", "}", "int", "newValue", "=", "currentValue", "+", "actualSteps", ";", "// if upper-boundary then set value in device to ensure sync", "// and for a large number of steps it is better to set a new value", "if", "(", "(", "newValue", "==", "maxValue", ")", "||", "(", "steps", ">", "5", ")", ")", "{", "setCurrentValue", "(", "newValue", ")", ";", "}", "// for a small number of step simply repeat 'increase'-commands", "else", "{", "controller", ".", "increase", "(", "DeviceControllerChannel", ".", "valueOf", "(", "channel", ")", ",", "actualSteps", ")", ";", "currentValue", "=", "newValue", ";", "}", "}" ]
Increases the wiper's value for n steps. @param steps The number of steps to increase @throws IOException Thrown if communication fails or device returned a malformed result
[ "Increases", "the", "wiper", "s", "value", "for", "n", "steps", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java#L504-L546
28,740
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java
MicrochipPotentiometerBase.setWiperLock
@Override public void setWiperLock(final boolean enabled) throws IOException { controller.setWiperLock(DeviceControllerChannel.valueOf(channel), enabled); }
java
@Override public void setWiperLock(final boolean enabled) throws IOException { controller.setWiperLock(DeviceControllerChannel.valueOf(channel), enabled); }
[ "@", "Override", "public", "void", "setWiperLock", "(", "final", "boolean", "enabled", ")", "throws", "IOException", "{", "controller", ".", "setWiperLock", "(", "DeviceControllerChannel", ".", "valueOf", "(", "channel", ")", ",", "enabled", ")", ";", "}" ]
Enables or disables wiper-lock. See chapter 5.3. @param enabled wiper-lock for the poti's channel has to be enabled @throws IOException Thrown if communication fails or device returned a malformed result
[ "Enables", "or", "disables", "wiper", "-", "lock", ".", "See", "chapter", "5", ".", "3", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java#L620-L625
28,741
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java
MicrochipPotentiometerBase.doWiperAction
private void doWiperAction(final WiperAction wiperAction) throws IOException { // for volatile-wiper switch (nonVolatileMode) { case VOLATILE_ONLY: case VOLATILE_AND_NONVOLATILE: wiperAction.run(MicrochipPotentiometerDeviceController.VOLATILE_WIPER); break; case NONVOLATILE_ONLY: // do nothing } // for non-volatile-wiper switch (nonVolatileMode) { case NONVOLATILE_ONLY: case VOLATILE_AND_NONVOLATILE: wiperAction.run(MicrochipPotentiometerDeviceController.NONVOLATILE_WIPER); break; case VOLATILE_ONLY: // do nothing } }
java
private void doWiperAction(final WiperAction wiperAction) throws IOException { // for volatile-wiper switch (nonVolatileMode) { case VOLATILE_ONLY: case VOLATILE_AND_NONVOLATILE: wiperAction.run(MicrochipPotentiometerDeviceController.VOLATILE_WIPER); break; case NONVOLATILE_ONLY: // do nothing } // for non-volatile-wiper switch (nonVolatileMode) { case NONVOLATILE_ONLY: case VOLATILE_AND_NONVOLATILE: wiperAction.run(MicrochipPotentiometerDeviceController.NONVOLATILE_WIPER); break; case VOLATILE_ONLY: // do nothing } }
[ "private", "void", "doWiperAction", "(", "final", "WiperAction", "wiperAction", ")", "throws", "IOException", "{", "// for volatile-wiper", "switch", "(", "nonVolatileMode", ")", "{", "case", "VOLATILE_ONLY", ":", "case", "VOLATILE_AND_NONVOLATILE", ":", "wiperAction", ".", "run", "(", "MicrochipPotentiometerDeviceController", ".", "VOLATILE_WIPER", ")", ";", "break", ";", "case", "NONVOLATILE_ONLY", ":", "// do nothing", "}", "// for non-volatile-wiper", "switch", "(", "nonVolatileMode", ")", "{", "case", "NONVOLATILE_ONLY", ":", "case", "VOLATILE_AND_NONVOLATILE", ":", "wiperAction", ".", "run", "(", "MicrochipPotentiometerDeviceController", ".", "NONVOLATILE_WIPER", ")", ";", "break", ";", "case", "VOLATILE_ONLY", ":", "// do nothing", "}", "}" ]
Runs a given 'wiperAction' for the volatile-wiper, the non-volatile-wiper or both according the current nonVolatileMode. @param wiperAction The action to be run @throws IOException Thrown if communication fails or device returned a malformed result @see MicrochipPotentiometerBase#nonVolatileMode
[ "Runs", "a", "given", "wiperAction", "for", "the", "volatile", "-", "wiper", "the", "non", "-", "volatile", "-", "wiper", "or", "both", "according", "the", "current", "nonVolatileMode", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/potentiometer/microchip/impl/MicrochipPotentiometerBase.java#L699-L721
28,742
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/power/impl/GpioPowerComponent.java
GpioPowerComponent.getState
@Override public PowerState getState() { if(pin.isState(onState)) return PowerState.ON; else if(pin.isState(offState)) return PowerState.OFF; else return PowerState.UNKNOWN; }
java
@Override public PowerState getState() { if(pin.isState(onState)) return PowerState.ON; else if(pin.isState(offState)) return PowerState.OFF; else return PowerState.UNKNOWN; }
[ "@", "Override", "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. @return PowerState
[ "Return", "the", "current", "power", "state", "based", "on", "the", "GPIO", "digital", "output", "pin", "state", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/power/impl/GpioPowerComponent.java#L95-L103
28,743
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/gpio/RaspiPin.java
RaspiPin.createDigitalPinNoPullDown
protected static Pin createDigitalPinNoPullDown(int address, String name) { return createDigitalPin(RaspiGpioProvider.NAME, address, name, EnumSet.of(PinPullResistance.OFF, PinPullResistance.PULL_UP), PinEdge.all()); }
java
protected static Pin createDigitalPinNoPullDown(int address, String name) { return createDigitalPin(RaspiGpioProvider.NAME, address, name, EnumSet.of(PinPullResistance.OFF, PinPullResistance.PULL_UP), PinEdge.all()); }
[ "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
[ "SDC", ".", "0", "pin", "has", "a", "physical", "pull", "-", "up", "resistor" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/gpio/RaspiPin.java#L84-L88
28,744
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/gpio/RaspiPin.java
RaspiPin.allPins
public static Pin[] allPins(SystemInfo.BoardType board) { List<Pin> pins = new ArrayList<>(); // pins for all Raspberry Pi models 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); // no further pins to add for Model B Rev 1 boards if(board == SystemInfo.BoardType.RaspberryPi_B_Rev1){ // return pins collection return pins.toArray(new Pin[0]); } // add pins exclusive to Model A and Model B (Rev2) 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); } // add pins exclusive to Models A+, B+, 2B, 3B, and Zero 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 collection return pins.toArray(new Pin[0]); }
java
public static Pin[] allPins(SystemInfo.BoardType board) { List<Pin> pins = new ArrayList<>(); // pins for all Raspberry Pi models 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); // no further pins to add for Model B Rev 1 boards if(board == SystemInfo.BoardType.RaspberryPi_B_Rev1){ // return pins collection return pins.toArray(new Pin[0]); } // add pins exclusive to Model A and Model B (Rev2) 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); } // add pins exclusive to Models A+, B+, 2B, 3B, and Zero 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 collection return pins.toArray(new Pin[0]); }
[ "public", "static", "Pin", "[", "]", "allPins", "(", "SystemInfo", ".", "BoardType", "board", ")", "{", "List", "<", "Pin", ">", "pins", "=", "new", "ArrayList", "<>", "(", ")", ";", "// pins for all Raspberry Pi models", "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", ")", ";", "// no further pins to add for Model B Rev 1 boards", "if", "(", "board", "==", "SystemInfo", ".", "BoardType", ".", "RaspberryPi_B_Rev1", ")", "{", "// return pins collection", "return", "pins", ".", "toArray", "(", "new", "Pin", "[", "0", "]", ")", ";", "}", "// add pins exclusive to Model A and Model B (Rev2)", "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", ")", ";", "}", "// add pins exclusive to Models A+, B+, 2B, 3B, and Zero", "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 collection", "return", "pins", ".", "toArray", "(", "new", "Pin", "[", "0", "]", ")", ";", "}" ]
so this method definition will hide the subclass static method)
[ "so", "this", "method", "definition", "will", "hide", "the", "subclass", "static", "method", ")" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/gpio/RaspiPin.java#L125-L179
28,745
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/jni/Serial.java
Serial.write
public synchronized static void write(int fd, InputStream input) throws IOException { // ensure bytes are available 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 bytes to serial port write(fd, buffer.toByteArray(), buffer.size()); }
java
public synchronized static void write(int fd, InputStream input) throws IOException { // ensure bytes are available 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 bytes to serial port write(fd, buffer.toByteArray(), buffer.size()); }
[ "public", "synchronized", "static", "void", "write", "(", "int", "fd", ",", "InputStream", "input", ")", "throws", "IOException", "{", "// ensure bytes are available", "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 bytes to serial port", "write", "(", "fd", ",", "buffer", ".", "toByteArray", "(", ")", ",", "buffer", ".", "size", "(", ")", ")", ";", "}" ]
Read content from an input stream of data and write it to the serial port transmit buffer. @param fd The file descriptor of the serial port/device. @param input An InputStream of data to be transmitted
[ "Read", "content", "from", "an", "input", "stream", "of", "data", "and", "write", "it", "to", "the", "serial", "port", "transmit", "buffer", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/jni/Serial.java#L747-L764
28,746
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/DacGpioProviderBase.java
DacGpioProviderBase.setPercentValue
public void setPercentValue(Pin pin, Number percent){ // validate range 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); } }
java
public void setPercentValue(Pin pin, Number percent){ // validate range 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); } }
[ "public", "void", "setPercentValue", "(", "Pin", "pin", ",", "Number", "percent", ")", "{", "// validate range", "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. @param pin @param percent percentage value between 0 and 100.
[ "Set", "the", "current", "value", "in", "a", "percentage", "of", "the", "available", "range", "instead", "of", "a", "raw", "value", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/DacGpioProviderBase.java#L80-L92
28,747
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/DacGpioProviderBase.java
DacGpioProviderBase.setPercentValue
@Override public void setPercentValue(GpioPinAnalogOutput pin, Number percent){ setPercentValue(pin.getPin(), percent); }
java
@Override public void setPercentValue(GpioPinAnalogOutput pin, Number percent){ setPercentValue(pin.getPin(), percent); }
[ "@", "Override", "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. @return percentage value between 0 and 100.
[ "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", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/DacGpioProviderBase.java#L100-L103
28,748
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/DacGpioProviderBase.java
DacGpioProviderBase.setValue
@Override public void setValue(Pin pin, Number value) { super.setValue(pin, value.doubleValue()); }
java
@Override public void setValue(Pin pin, Number value) { super.setValue(pin, value.doubleValue()); }
[ "@", "Override", "public", "void", "setValue", "(", "Pin", "pin", ",", "Number", "value", ")", "{", "super", ".", "setValue", "(", "pin", ",", "value", ".", "doubleValue", "(", ")", ")", ";", "}" ]
Set the requested analog output pin's conversion value. @param pin to get conversion values for @param value analog output pin conversion value
[ "Set", "the", "requested", "analog", "output", "pin", "s", "conversion", "value", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/DacGpioProviderBase.java#L111-L114
28,749
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/DacGpioProviderBase.java
DacGpioProviderBase.shutdown
@Override public void shutdown() { // prevent reentrant invocation if(isShutdown()) return; // perform shutdown login in base super.shutdown(); try { // iterate over all pins and apply shutdown values if configured for the pin instance for(Pin pin : allPins){ Double value = getShutdownValue(pin).doubleValue(); if(value != null){ setValue(pin, value); } } } catch (Exception e) { throw new RuntimeException(e); } }
java
@Override public void shutdown() { // prevent reentrant invocation if(isShutdown()) return; // perform shutdown login in base super.shutdown(); try { // iterate over all pins and apply shutdown values if configured for the pin instance for(Pin pin : allPins){ Double value = getShutdownValue(pin).doubleValue(); if(value != null){ setValue(pin, value); } } } catch (Exception e) { throw new RuntimeException(e); } }
[ "@", "Override", "public", "void", "shutdown", "(", ")", "{", "// prevent reentrant invocation", "if", "(", "isShutdown", "(", ")", ")", "return", ";", "// perform shutdown login in base", "super", ".", "shutdown", "(", ")", ";", "try", "{", "// iterate over all pins and apply shutdown values if configured for the pin instance", "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.
[ "This", "method", "is", "used", "by", "the", "framework", "to", "shutdown", "the", "DAC", "instance", "and", "apply", "any", "configured", "shutdown", "values", "to", "the", "DAC", "pins", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/DacGpioProviderBase.java#L120-L141
28,750
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/util/NativeLibraryLoader.java
NativeLibraryLoader.loadLibraryFromClasspath
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); } // Finally, load the library System.load(target.toAbsolutePath().toString()); }
java
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); } // Finally, load the library System.load(target.toAbsolutePath().toString()); }
[ "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", ")", ";", "}", "// Finally, load the library", "System", ".", "load", "(", "target", ".", "toAbsolutePath", "(", ")", ".", "toString", "(", ")", ")", ";", "}" ]
Loads library from classpath The file from classpath is copied into system temporary directory and then loaded. The temporary file is deleted after exiting. Method uses String as filename because the pathname is "abstract", not system-dependent. @param path The file path in classpath as an absolute path, e.g. /package/File.ext (could be inside jar) @throws IOException If temporary file creation or read/write operation fails @throws IllegalArgumentException If source file (param path) does not exist @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters (restriction of {@see File#createTempFile(java.lang.String, java.lang.String)}).
[ "Loads", "library", "from", "classpath" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/util/NativeLibraryLoader.java#L132-L160
28,751
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/serial/SerialDataEvent.java
SerialDataEvent.getHexByteString
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(); }
java
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(); }
[ "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 @param prefix optional prefix string to append before each data byte @param separator optional separator string to append in between each data byte sequence @param suffix optional suffix string to append after each data byte @return HEX string of data bytes from serial data receive buffer @throws IOException
[ "Get", "a", "HEX", "string", "representation", "of", "the", "bytes", "available", "in", "the", "serial", "data", "receive", "buffer" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/serial/SerialDataEvent.java#L187-L200
28,752
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java
TemperatureConversion.convert
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")); } }
java
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")); } }
[ "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. @param from TemperatureScale @param to TemperatureScale @param temperature value @return converted temperature value in the requested to scale
[ "Convert", "a", "temperature", "value", "from", "one", "temperature", "scale", "to", "another", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L48-L63
28,753
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java
TemperatureConversion.convertFromFarenheit
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")); } }
java
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")); } }
[ "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. @param to TemperatureScale @param temperature value in degrees Farenheit @return converted temperature value in the requested to scale
[ "Convert", "a", "temperature", "value", "from", "the", "Farenheit", "temperature", "scale", "to", "another", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L73-L88
28,754
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java
TemperatureConversion.convertToFarenheit
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")); } }
java
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")); } }
[ "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. @param from TemperatureScale @param temperature value from other scale @return converted temperature value in degrees Farenheit
[ "Convert", "a", "temperature", "value", "from", "another", "temperature", "scale", "into", "the", "Farenheit", "temperature", "scale", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L97-L112
28,755
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java
TemperatureConversion.convertFromCelsius
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")); } }
java
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")); } }
[ "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. @param to TemperatureScale @param temperature value in degrees centigrade @return converted temperature value in the requested to scale
[ "Convert", "a", "temperature", "value", "from", "the", "Celsius", "temperature", "scale", "to", "another", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L121-L136
28,756
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java
TemperatureConversion.convertToCelsius
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")); } }
java
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")); } }
[ "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. @param from TemperatureScale @param temperature value from other scale @return converted temperature value in degrees centigrade
[ "Convert", "a", "temperature", "value", "from", "another", "temperature", "scale", "into", "the", "Celsius", "temperature", "scale", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L145-L160
28,757
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java
TemperatureConversion.convertFromKelvin
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")); } }
java
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")); } }
[ "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. @param to TemperatureScale @param temperature value in Kelvin @return converted temperature value in the requested to scale
[ "Convert", "a", "temperature", "value", "from", "the", "Kelvin", "temperature", "scale", "to", "another", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L169-L184
28,758
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java
TemperatureConversion.convertToKelvin
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")); } }
java
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")); } }
[ "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. @param from TemperatureScale @param temperature value from other scale @return converted temperature value in Kelvin
[ "Convert", "a", "temperature", "value", "from", "another", "temperature", "scale", "into", "the", "Kelvin", "temperature", "scale", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L193-L208
28,759
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java
TemperatureConversion.convertFromRankine
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")); } }
java
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")); } }
[ "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. @param to TemperatureScale @param temperature value in degrees Rankine @return converted temperature value in the requested to scale
[ "Convert", "a", "temperature", "value", "from", "the", "Rankine", "temperature", "scale", "to", "another", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L217-L232
28,760
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java
TemperatureConversion.convertToRankine
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")); } }
java
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")); } }
[ "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. @param from TemperatureScale @param temperature value from other scale @return converted temperature value in degrees Rankine
[ "Convert", "a", "temperature", "value", "from", "another", "temperature", "scale", "into", "the", "Rankine", "temperature", "scale", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/temperature/TemperatureConversion.java#L241-L256
28,761
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/AdcGpioProviderBase.java
AdcGpioProviderBase.getPercentValue
public float getPercentValue(Pin pin){ double value = getValue(pin); if(value > INVALID_VALUE) { return (float) (value / (getMaxSupportedValue() - getMinSupportedValue())) * 100f; } return INVALID_VALUE; }
java
public float getPercentValue(Pin pin){ double value = getValue(pin); if(value > INVALID_VALUE) { return (float) (value / (getMaxSupportedValue() - getMinSupportedValue())) * 100f; } return INVALID_VALUE; }
[ "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. @return percentage value between 0 and 100.
[ "Get", "the", "current", "value", "in", "a", "percentage", "of", "the", "available", "range", "instead", "of", "a", "raw", "value", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/AdcGpioProviderBase.java#L125-L131
28,762
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/AdcGpioProviderBase.java
AdcGpioProviderBase.shutdown
@Override public void shutdown() { // prevent reentrant invocation if(isShutdown()) return; // perform shutdown login in base super.shutdown(); try { // if a monitor is running, then shut it down now if (monitor != null) { // shutdown monitoring thread monitor.shutdown(); monitor = null; } } catch (Exception e) { throw new RuntimeException(e); } }
java
@Override public void shutdown() { // prevent reentrant invocation if(isShutdown()) return; // perform shutdown login in base super.shutdown(); try { // if a monitor is running, then shut it down now if (monitor != null) { // shutdown monitoring thread monitor.shutdown(); monitor = null; } } catch (Exception e) { throw new RuntimeException(e); } }
[ "@", "Override", "public", "void", "shutdown", "(", ")", "{", "// prevent reentrant invocation", "if", "(", "isShutdown", "(", ")", ")", "return", ";", "// perform shutdown login in base", "super", ".", "shutdown", "(", ")", ";", "try", "{", "// if a monitor is running, then shut it down now", "if", "(", "monitor", "!=", "null", ")", "{", "// shutdown monitoring thread", "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.
[ "This", "method", "is", "used", "by", "the", "framework", "to", "shutdown", "the", "background", "monitoring", "thread", "if", "needed", "when", "the", "program", "exits", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/AdcGpioProviderBase.java#L159-L179
28,763
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/AdcGpioProviderBase.java
AdcGpioProviderBase.setEventThreshold
@Override public void setEventThreshold(double threshold, GpioPinAnalogInput...pin){ for(GpioPin p : pin){ setEventThreshold(threshold, p.getPin()); } }
java
@Override public void setEventThreshold(double threshold, GpioPinAnalogInput...pin){ for(GpioPin p : pin){ setEventThreshold(threshold, p.getPin()); } }
[ "@", "Override", "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. The event threshold value determines how much change in the analog input pin's conversion value must occur before the framework issues an analog input pin change event. A threshold is necessary to prevent a significant number of analog input change events from getting propagated and dispatched for input values that may have an expected range of drift. see the DEFAULT_THRESHOLD constant for the default threshold value. @param threshold threshold value for requested analog input pin. @param pin analog input pin (vararg, one or more inputs can be defined.)
[ "Set", "the", "event", "threshold", "value", "for", "a", "given", "analog", "input", "pin", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/AdcGpioProviderBase.java#L258-L263
28,764
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/AdcGpioProviderBase.java
AdcGpioProviderBase.setMonitorEnabled
@Override public void setMonitorEnabled(boolean enabled) { if(enabled) { // create and start background monitor if (monitor == null) { monitor = new AdcGpioProviderBase.ADCMonitor(); monitor.start(); } } else{ try { // if a monitor is running, then shut it down now if (monitor != null) { // shutdown monitoring thread monitor.shutdown(); monitor = null; } } catch (Exception e) { throw new RuntimeException(e); } } }
java
@Override public void setMonitorEnabled(boolean enabled) { if(enabled) { // create and start background monitor if (monitor == null) { monitor = new AdcGpioProviderBase.ADCMonitor(); monitor.start(); } } else{ try { // if a monitor is running, then shut it down now if (monitor != null) { // shutdown monitoring thread monitor.shutdown(); monitor = null; } } catch (Exception e) { throw new RuntimeException(e); } } }
[ "@", "Override", "public", "void", "setMonitorEnabled", "(", "boolean", "enabled", ")", "{", "if", "(", "enabled", ")", "{", "// create and start background monitor", "if", "(", "monitor", "==", "null", ")", "{", "monitor", "=", "new", "AdcGpioProviderBase", ".", "ADCMonitor", "(", ")", ";", "monitor", ".", "start", "(", ")", ";", "}", "}", "else", "{", "try", "{", "// if a monitor is running, then shut it down now", "if", "(", "monitor", "!=", "null", ")", "{", "// shutdown monitoring thread", "monitor", ".", "shutdown", "(", ")", ";", "monitor", "=", "null", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "}" ]
Set the background monitoring thread's enabled state. @param enabled monitoring enabled or disabled state
[ "Set", "the", "background", "monitoring", "thread", "s", "enabled", "state", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/base/AdcGpioProviderBase.java#L310-L331
28,765
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/file/LinuxFile.java
LinuxFile.ioctl
public void ioctl(long command, int value) throws IOException { final int response = directIOCTL(getFileDescriptor(), command, value); if(response < 0) throw new LinuxFileException(); }
java
public void ioctl(long command, int value) throws IOException { final int response = directIOCTL(getFileDescriptor(), command, value); if(response < 0) throw new LinuxFileException(); }
[ "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. @param command ioctl command @param value int ioctl value @return result of operation. Zero if everything is OK, less than zero if there was an error.
[ "Runs", "an", "ioctl", "value", "command", "on", "a", "file", "descriptor", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/file/LinuxFile.java#L102-L107
28,766
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/file/LinuxFile.java
LinuxFile.ioctl
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!"); //buffers must be direct try { if(!data.isDirect()) { ByteBuffer newBuf = getDataBuffer(data.limit()); int pos = data.position(); //keep position data.rewind(); newBuf.clear(); newBuf.put(data); newBuf.position(pos); //restore position 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(); //fast forward positions offsets.position(offsets.limit()); data.rewind(); //if original data wasnt direct, copy it back in. if(originalData != data) { originalData.rewind(); originalData.put(data); originalData.rewind(); } }
java
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!"); //buffers must be direct try { if(!data.isDirect()) { ByteBuffer newBuf = getDataBuffer(data.limit()); int pos = data.position(); //keep position data.rewind(); newBuf.clear(); newBuf.put(data); newBuf.position(pos); //restore position 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(); //fast forward positions offsets.position(offsets.limit()); data.rewind(); //if original data wasnt direct, copy it back in. if(originalData != data) { originalData.rewind(); originalData.put(data); originalData.rewind(); } }
[ "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!\"", ")", ";", "//buffers must be direct", "try", "{", "if", "(", "!", "data", ".", "isDirect", "(", ")", ")", "{", "ByteBuffer", "newBuf", "=", "getDataBuffer", "(", "data", ".", "limit", "(", ")", ")", ";", "int", "pos", "=", "data", ".", "position", "(", ")", ";", "//keep position", "data", ".", "rewind", "(", ")", ";", "newBuf", ".", "clear", "(", ")", ";", "newBuf", ".", "put", "(", "data", ")", ";", "newBuf", ".", "position", "(", "pos", ")", ";", "//restore position", "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", "(", ")", ";", "//fast forward positions", "offsets", ".", "position", "(", "offsets", ".", "limit", "(", ")", ")", ";", "data", ".", "rewind", "(", ")", ";", "//if original data wasnt direct, copy it back in.", "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. The data ByteBuffer uses the current position to determine the head point of data passed to the ioctl. This is useful for appending entry-point data structures at the end of the buffer, while referring to other structures/data that come before them in the buffer. <I NEED A BETTER EXPL OF BUFFERS HERE> When assembling the structured data, use {@link LinuxFile#wordSize} to determine the size in bytes needed for a pointer. Also be sure to consider GCC padding and structure alignment. GCC will try a field to its word size (32b ints align at 4-byte, etc), and will align the structure size with the native word size (4-byte for 32b, 8-byte for 64b). Provided IntBuffer offsets must use native byte order (endianness). <pre> {@code <NEED BETTER EXAMPLE HERE> } </pre> DANGER: check your buffer length! The possible length varies depending on the ioctl call. Overruns are very possible. ioctl tries to determine EFAULTs, but sometimes you might trample JVM data if you are not careful. @param command ioctl command @param data values in bytes for all structures, with 4 or 8 byte size holes for pointers @param offsets byte offsets of pointer at given index @throws IOException
[ "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", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/file/LinuxFile.java#L143-L209
28,767
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/file/LinuxFile.java
LinuxFile.getFileDescriptor
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; }
java
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; }
[ "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.
[ "Gets", "the", "real", "POSIX", "file", "descriptor", "for", "use", "by", "custom", "jni", "calls", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/file/LinuxFile.java#L214-L221
28,768
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/file/LinuxFile.java
LinuxFile.mmap
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); }); }
java
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); }); }
[ "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. @param length length of desired mapping @param prot protocol used for mapping @param flags flags for mapping @param offset offset in file for mapping @return direct mapped ByteBuffer @throws IOException
[ "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", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/file/LinuxFile.java#L284-L293
28,769
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/relay/impl/GpioRelayComponent.java
GpioRelayComponent.getState
@Override public RelayState getState() { if(pin.isState(openState)) return RelayState.OPEN; else return RelayState.CLOSED; }
java
@Override public RelayState getState() { if(pin.isState(openState)) return RelayState.OPEN; else return RelayState.CLOSED; }
[ "@", "Override", "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. @return PowerState
[ "Return", "the", "current", "relay", "state", "based", "on", "the", "GPIO", "digital", "output", "pin", "state", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/relay/impl/GpioRelayComponent.java#L96-L102
28,770
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/motor/impl/GpioStepperMotorComponent.java
GpioStepperMotorComponent.setState
@Override public void setState(MotorState state) { switch(state) { case STOP: { // set internal tracking state currentState = MotorState.STOP; // turn all GPIO pins to OFF state for(GpioPinDigitalOutput pin : pins) pin.setState(offState); break; } case FORWARD: { // set internal tracking state currentState = MotorState.FORWARD; // start control thread if not already running if(!controlThread.isAlive()) { controlThread = new GpioStepperMotorControl(); controlThread.start(); } break; } case REVERSE: { // set internal tracking state currentState = MotorState.REVERSE; // start control thread if not already running if(!controlThread.isAlive()) { controlThread = new GpioStepperMotorControl(); controlThread.start(); } break; } default: { throw new UnsupportedOperationException("Cannot set motor state: " + state.toString()); } } }
java
@Override public void setState(MotorState state) { switch(state) { case STOP: { // set internal tracking state currentState = MotorState.STOP; // turn all GPIO pins to OFF state for(GpioPinDigitalOutput pin : pins) pin.setState(offState); break; } case FORWARD: { // set internal tracking state currentState = MotorState.FORWARD; // start control thread if not already running if(!controlThread.isAlive()) { controlThread = new GpioStepperMotorControl(); controlThread.start(); } break; } case REVERSE: { // set internal tracking state currentState = MotorState.REVERSE; // start control thread if not already running if(!controlThread.isAlive()) { controlThread = new GpioStepperMotorControl(); controlThread.start(); } break; } default: { throw new UnsupportedOperationException("Cannot set motor state: " + state.toString()); } } }
[ "@", "Override", "public", "void", "setState", "(", "MotorState", "state", ")", "{", "switch", "(", "state", ")", "{", "case", "STOP", ":", "{", "// set internal tracking state", "currentState", "=", "MotorState", ".", "STOP", ";", "// turn all GPIO pins to OFF state", "for", "(", "GpioPinDigitalOutput", "pin", ":", "pins", ")", "pin", ".", "setState", "(", "offState", ")", ";", "break", ";", "}", "case", "FORWARD", ":", "{", "// set internal tracking state", "currentState", "=", "MotorState", ".", "FORWARD", ";", "// start control thread if not already running", "if", "(", "!", "controlThread", ".", "isAlive", "(", ")", ")", "{", "controlThread", "=", "new", "GpioStepperMotorControl", "(", ")", ";", "controlThread", ".", "start", "(", ")", ";", "}", "break", ";", "}", "case", "REVERSE", ":", "{", "// set internal tracking state", "currentState", "=", "MotorState", ".", "REVERSE", ";", "// start control thread if not already running", "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 @param state new motor state to apply
[ "change", "the", "current", "stepper", "motor", "state" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/motor/impl/GpioStepperMotorComponent.java#L87-L129
28,771
Pi4J/pi4j
pi4j-device/src/main/java/com/pi4j/component/motor/impl/GpioStepperMotorComponent.java
GpioStepperMotorComponent.doStep
private void doStep(boolean forward) { // increment or decrement sequence if(forward) sequenceIndex++; else sequenceIndex--; // check sequence bounds; rollover if needed if(sequenceIndex >= stepSequence.length) sequenceIndex = 0; else if(sequenceIndex < 0) sequenceIndex = (stepSequence.length - 1); // start cycling GPIO pins to move the motor forward or reverse for(int pinIndex = 0; pinIndex < pins.length; pinIndex++) { // apply step sequence 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) {} }
java
private void doStep(boolean forward) { // increment or decrement sequence if(forward) sequenceIndex++; else sequenceIndex--; // check sequence bounds; rollover if needed if(sequenceIndex >= stepSequence.length) sequenceIndex = 0; else if(sequenceIndex < 0) sequenceIndex = (stepSequence.length - 1); // start cycling GPIO pins to move the motor forward or reverse for(int pinIndex = 0; pinIndex < pins.length; pinIndex++) { // apply step sequence 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) {} }
[ "private", "void", "doStep", "(", "boolean", "forward", ")", "{", "// increment or decrement sequence", "if", "(", "forward", ")", "sequenceIndex", "++", ";", "else", "sequenceIndex", "--", ";", "// check sequence bounds; rollover if needed", "if", "(", "sequenceIndex", ">=", "stepSequence", ".", "length", ")", "sequenceIndex", "=", "0", ";", "else", "if", "(", "sequenceIndex", "<", "0", ")", "sequenceIndex", "=", "(", "stepSequence", ".", "length", "-", "1", ")", ";", "// start cycling GPIO pins to move the motor forward or reverse", "for", "(", "int", "pinIndex", "=", "0", ";", "pinIndex", "<", "pins", ".", "length", ";", "pinIndex", "++", ")", "{", "// apply step sequence", "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 @param forward
[ "this", "method", "performs", "the", "calculations", "and", "work", "to", "control", "the", "GPIO", "pins", "to", "move", "the", "stepper", "motor", "forward", "or", "reverse" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-device/src/main/java/com/pi4j/component/motor/impl/GpioStepperMotorComponent.java#L178-L205
28,772
Pi4J/pi4j
pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/pca/PCA9685GpioProvider.java
PCA9685GpioProvider.calculateOffPositionForPulseDuration
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; }
java
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; }
[ "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. @param duration pulse duration in microseconds @return OFF position(value between 1 and 4095)
[ "Calculates", "the", "OFF", "position", "for", "a", "certain", "pulse", "duration", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-gpio-extension/src/main/java/com/pi4j/gpio/extension/pca/PCA9685GpioProvider.java#L264-L273
28,773
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/i2c/I2CFactory.java
I2CFactory.getInstance
public static I2CBus getInstance(int busNumber, long lockAquireTimeout, TimeUnit lockAquireTimeoutUnit) throws UnsupportedBusNumberException, IOException { return provider.getBus(busNumber, lockAquireTimeout, lockAquireTimeoutUnit); }
java
public static I2CBus getInstance(int busNumber, long lockAquireTimeout, TimeUnit lockAquireTimeoutUnit) throws UnsupportedBusNumberException, IOException { return provider.getBus(busNumber, lockAquireTimeout, lockAquireTimeoutUnit); }
[ "public", "static", "I2CBus", "getInstance", "(", "int", "busNumber", ",", "long", "lockAquireTimeout", ",", "TimeUnit", "lockAquireTimeoutUnit", ")", "throws", "UnsupportedBusNumberException", ",", "IOException", "{", "return", "provider", ".", "getBus", "(", "busNumber", ",", "lockAquireTimeout", ",", "lockAquireTimeoutUnit", ")", ";", "}" ]
Create new I2CBus instance. @param busNumber The bus number @param lockAquireTimeout The timeout for locking the bus for exclusive communication @param lockAquireTimeoutUnit The units of lockAquireTimeout @return Return a new I2CBus instance @throws UnsupportedBusNumberException If the given bus-number is not supported by the underlying system @throws IOException If communication to i2c-bus fails
[ "Create", "new", "I2CBus", "instance", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/i2c/I2CFactory.java#L94-L96
28,774
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/i2c/I2CFactory.java
I2CFactory.getBusIds
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; }
java
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; }
[ "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. @return Return found I2C bus numbers or null @throws IOException If fetching from sysfs interface fails
[ "Fetch", "all", "available", "I2C", "bus", "numbers", "from", "sysfs", ".", "Returns", "null", "if", "nothing", "was", "found", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/i2c/I2CFactory.java#L114-L136
28,775
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/serial/impl/SerialImpl.java
SerialImpl.close
@Override public void close() throws IllegalStateException, IOException { // validate state if (isClosed()) throw new IllegalStateException("Serial connection is not open; cannot 'close()'."); // remove serial port listener SerialInterrupt.removeListener(fileDescriptor); // close serial port now com.pi4j.jni.Serial.close(fileDescriptor); // reset file descriptor fileDescriptor = -1; }
java
@Override public void close() throws IllegalStateException, IOException { // validate state if (isClosed()) throw new IllegalStateException("Serial connection is not open; cannot 'close()'."); // remove serial port listener SerialInterrupt.removeListener(fileDescriptor); // close serial port now com.pi4j.jni.Serial.close(fileDescriptor); // reset file descriptor fileDescriptor = -1; }
[ "@", "Override", "public", "void", "close", "(", ")", "throws", "IllegalStateException", ",", "IOException", "{", "// validate state", "if", "(", "isClosed", "(", ")", ")", "throw", "new", "IllegalStateException", "(", "\"Serial connection is not open; cannot 'close()'.\"", ")", ";", "// remove serial port listener", "SerialInterrupt", ".", "removeListener", "(", "fileDescriptor", ")", ";", "// close serial port now", "com", ".", "pi4j", ".", "jni", ".", "Serial", ".", "close", "(", "fileDescriptor", ")", ";", "// reset file descriptor", "fileDescriptor", "=", "-", "1", ";", "}" ]
This method is called to close a currently open open serial port. @throws IllegalStateException thrown if the serial port is not already open. @throws IOException thrown on any error.
[ "This", "method", "is", "called", "to", "close", "a", "currently", "open", "open", "serial", "port", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/serial/impl/SerialImpl.java#L348-L363
28,776
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/wdt/impl/WDTimerImpl.java
WDTimerImpl.open
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."); } }
java
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."); } }
[ "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 @param file @throws IOException
[ "Open", "custom", "Watchdog" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/wdt/impl/WDTimerImpl.java#L76-L85
28,777
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/wdt/impl/WDTimerImpl.java
WDTimerImpl.setTimeOut
@Override 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."); } }
java
@Override 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."); } }
[ "@", "Override", "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 @param timeout @throws IOException
[ "Set", "new", "timeout" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/wdt/impl/WDTimerImpl.java#L93-L100
28,778
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/wdt/impl/WDTimerImpl.java
WDTimerImpl.heartbeat
@Override public void heartbeat() throws IOException { isOpen(); int ret = WDT.ping(fd); if(ret<0) { throw new IOException("Heartbeat error. File " + filename + " got " + ret + " back."); } }
java
@Override public void heartbeat() throws IOException { isOpen(); int ret = WDT.ping(fd); if(ret<0) { throw new IOException("Heartbeat error. File " + filename + " got " + ret + " back."); } }
[ "@", "Override", "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. @throws IOException
[ "Ping", "a", "watchdog", "." ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/wdt/impl/WDTimerImpl.java#L123-L130
28,779
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/io/wdt/impl/WDTimerImpl.java
WDTimerImpl.disable
@Override 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."); } }
java
@Override 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."); } }
[ "@", "Override", "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! @throws IOException
[ "Disable", "watchdog", "with", "Magic", "Close", ".", "Now", "watchdog", "not", "working", ".", "Close", "watchdog", "without", "call", "disable", "causes", "RaspberryPi", "reboot!" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/io/wdt/impl/WDTimerImpl.java#L137-L144
28,780
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/concurrent/DefaultExecutorServiceFactory.java
DefaultExecutorServiceFactory.getThreadFactory
private static ThreadFactory getThreadFactory(final String nameFormat) { final ThreadFactory defaultThreadFactory = Executors.privilegedThreadFactory(); return new ThreadFactory() { final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null; @Override public Thread newThread(Runnable runnable) { Thread thread = defaultThreadFactory.newThread(runnable); if (nameFormat != null) { thread.setName(String.format(nameFormat, count.getAndIncrement())); } return thread; } }; }
java
private static ThreadFactory getThreadFactory(final String nameFormat) { final ThreadFactory defaultThreadFactory = Executors.privilegedThreadFactory(); return new ThreadFactory() { final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null; @Override public Thread newThread(Runnable runnable) { Thread thread = defaultThreadFactory.newThread(runnable); if (nameFormat != null) { thread.setName(String.format(nameFormat, count.getAndIncrement())); } return thread; } }; }
[ "private", "static", "ThreadFactory", "getThreadFactory", "(", "final", "String", "nameFormat", ")", "{", "final", "ThreadFactory", "defaultThreadFactory", "=", "Executors", ".", "privilegedThreadFactory", "(", ")", ";", "return", "new", "ThreadFactory", "(", ")", "{", "final", "AtomicLong", "count", "=", "(", "nameFormat", "!=", "null", ")", "?", "new", "AtomicLong", "(", "0", ")", ":", "null", ";", "@", "Override", "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
[ "return", "an", "instance", "to", "the", "thread", "factory", "used", "to", "create", "new", "executor", "services" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/concurrent/DefaultExecutorServiceFactory.java#L81-L95
28,781
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/concurrent/DefaultExecutorServiceFactory.java
DefaultExecutorServiceFactory.newSingleThreadExecutorService
@Override public ExecutorService newSingleThreadExecutorService() { // create new single thread executor service ExecutorService singleThreadExecutorService = Executors.newSingleThreadExecutor(getThreadFactory("pi4j-single-executor-%d")); // add new instance to managed collection singleThreadExecutorServices.add(singleThreadExecutorService); // return new executor service return singleThreadExecutorService; }
java
@Override public ExecutorService newSingleThreadExecutorService() { // create new single thread executor service ExecutorService singleThreadExecutorService = Executors.newSingleThreadExecutor(getThreadFactory("pi4j-single-executor-%d")); // add new instance to managed collection singleThreadExecutorServices.add(singleThreadExecutorService); // return new executor service return singleThreadExecutorService; }
[ "@", "Override", "public", "ExecutorService", "newSingleThreadExecutorService", "(", ")", "{", "// create new single thread executor service", "ExecutorService", "singleThreadExecutorService", "=", "Executors", ".", "newSingleThreadExecutor", "(", "getThreadFactory", "(", "\"pi4j-single-executor-%d\"", ")", ")", ";", "// add new instance to managed collection", "singleThreadExecutorServices", ".", "add", "(", "singleThreadExecutorService", ")", ";", "// return new executor service", "return", "singleThreadExecutorService", ";", "}" ]
return a new instance of a single thread executor service This method is deprecated in favor of the getGpioEventExecutorService - which provides better guarantees around resource management
[ "return", "a", "new", "instance", "of", "a", "single", "thread", "executor", "service" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/concurrent/DefaultExecutorServiceFactory.java#L119-L130
28,782
Pi4J/pi4j
pi4j-core/src/main/java/com/pi4j/concurrent/DefaultExecutorServiceFactory.java
DefaultExecutorServiceFactory.shutdown
public void shutdown() { // shutdown each single thread executor in the managed collection for (ExecutorService singleThreadExecutorService : singleThreadExecutorServices) { shutdownExecutor(singleThreadExecutorService); } // shutdown scheduled executor instance shutdownExecutor(getInternalScheduledExecutorService()); shutdownExecutor(getInternalGpioExecutorService()); }
java
public void shutdown() { // shutdown each single thread executor in the managed collection for (ExecutorService singleThreadExecutorService : singleThreadExecutorServices) { shutdownExecutor(singleThreadExecutorService); } // shutdown scheduled executor instance shutdownExecutor(getInternalScheduledExecutorService()); shutdownExecutor(getInternalGpioExecutorService()); }
[ "public", "void", "shutdown", "(", ")", "{", "// shutdown each single thread executor in the managed collection", "for", "(", "ExecutorService", "singleThreadExecutorService", ":", "singleThreadExecutorServices", ")", "{", "shutdownExecutor", "(", "singleThreadExecutorService", ")", ";", "}", "// shutdown scheduled executor instance", "shutdownExecutor", "(", "getInternalScheduledExecutorService", "(", ")", ")", ";", "shutdownExecutor", "(", "getInternalGpioExecutorService", "(", ")", ")", ";", "}" ]
shutdown executor threads
[ "shutdown", "executor", "threads" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-core/src/main/java/com/pi4j/concurrent/DefaultExecutorServiceFactory.java#L135-L145
28,783
Pi4J/pi4j
pi4j-example/src/main/java/PibrellaExample.java
PibrellaExample.main
public static void main(String args[]) throws InterruptedException, IOException { System.out.println("<--Pi4J--> Pibrella Example ... started."); // ----------------------------------------------------------------- // create a button listener // ----------------------------------------------------------------- pibrella.button().addListener(new ButtonPressedListener() { @Override public void onButtonPressed(ButtonEvent event) { System.out.println("[BUTTON PRESSED]"); pulseRate = 30; // START or STOP sample tune if(sampleTuneThread.isAlive()) stopSampleTune(); else playSampleTune(); } }); pibrella.button().addListener(new ButtonReleasedListener() { @Override public void onButtonReleased(ButtonEvent event) { System.out.println("[BUTTON RELEASED]"); pulseRate = 100; } }); // run continuously until user aborts with CTRL-C while(true) { // step up the ladder for(int index = PibrellaLed.RED.getIndex(); index <= PibrellaLed.GREEN.getIndex(); index++) { pibrella.getLed(index).pulse(pulseRate, true); //Thread.sleep(pulseRate); } // step down the ladder for(int index = PibrellaLed.GREEN.getIndex(); index >= PibrellaLed.RED.getIndex(); index--) { pibrella.getLed(index).pulse(pulseRate, true); //Thread.sleep(pulseRate); } } // stop all GPIO activity/threads by shutting down the GPIO controller // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks) //gpio.shutdown(); // <-- uncomment if your program terminates }
java
public static void main(String args[]) throws InterruptedException, IOException { System.out.println("<--Pi4J--> Pibrella Example ... started."); // ----------------------------------------------------------------- // create a button listener // ----------------------------------------------------------------- pibrella.button().addListener(new ButtonPressedListener() { @Override public void onButtonPressed(ButtonEvent event) { System.out.println("[BUTTON PRESSED]"); pulseRate = 30; // START or STOP sample tune if(sampleTuneThread.isAlive()) stopSampleTune(); else playSampleTune(); } }); pibrella.button().addListener(new ButtonReleasedListener() { @Override public void onButtonReleased(ButtonEvent event) { System.out.println("[BUTTON RELEASED]"); pulseRate = 100; } }); // run continuously until user aborts with CTRL-C while(true) { // step up the ladder for(int index = PibrellaLed.RED.getIndex(); index <= PibrellaLed.GREEN.getIndex(); index++) { pibrella.getLed(index).pulse(pulseRate, true); //Thread.sleep(pulseRate); } // step down the ladder for(int index = PibrellaLed.GREEN.getIndex(); index >= PibrellaLed.RED.getIndex(); index--) { pibrella.getLed(index).pulse(pulseRate, true); //Thread.sleep(pulseRate); } } // stop all GPIO activity/threads by shutting down the GPIO controller // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks) //gpio.shutdown(); // <-- uncomment if your program terminates }
[ "public", "static", "void", "main", "(", "String", "args", "[", "]", ")", "throws", "InterruptedException", ",", "IOException", "{", "System", ".", "out", ".", "println", "(", "\"<--Pi4J--> Pibrella Example ... started.\"", ")", ";", "// -----------------------------------------------------------------", "// create a button listener", "// -----------------------------------------------------------------", "pibrella", ".", "button", "(", ")", ".", "addListener", "(", "new", "ButtonPressedListener", "(", ")", "{", "@", "Override", "public", "void", "onButtonPressed", "(", "ButtonEvent", "event", ")", "{", "System", ".", "out", ".", "println", "(", "\"[BUTTON PRESSED]\"", ")", ";", "pulseRate", "=", "30", ";", "// START or STOP sample tune", "if", "(", "sampleTuneThread", ".", "isAlive", "(", ")", ")", "stopSampleTune", "(", ")", ";", "else", "playSampleTune", "(", ")", ";", "}", "}", ")", ";", "pibrella", ".", "button", "(", ")", ".", "addListener", "(", "new", "ButtonReleasedListener", "(", ")", "{", "@", "Override", "public", "void", "onButtonReleased", "(", "ButtonEvent", "event", ")", "{", "System", ".", "out", ".", "println", "(", "\"[BUTTON RELEASED]\"", ")", ";", "pulseRate", "=", "100", ";", "}", "}", ")", ";", "// run continuously until user aborts with CTRL-C", "while", "(", "true", ")", "{", "// step up the ladder", "for", "(", "int", "index", "=", "PibrellaLed", ".", "RED", ".", "getIndex", "(", ")", ";", "index", "<=", "PibrellaLed", ".", "GREEN", ".", "getIndex", "(", ")", ";", "index", "++", ")", "{", "pibrella", ".", "getLed", "(", "index", ")", ".", "pulse", "(", "pulseRate", ",", "true", ")", ";", "//Thread.sleep(pulseRate);", "}", "// step down the ladder", "for", "(", "int", "index", "=", "PibrellaLed", ".", "GREEN", ".", "getIndex", "(", ")", ";", "index", ">=", "PibrellaLed", ".", "RED", ".", "getIndex", "(", ")", ";", "index", "--", ")", "{", "pibrella", ".", "getLed", "(", "index", ")", ".", "pulse", "(", "pulseRate", ",", "true", ")", ";", "//Thread.sleep(pulseRate);", "}", "}", "// stop all GPIO activity/threads by shutting down the GPIO controller", "// (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)", "//gpio.shutdown(); // <-- uncomment if your program terminates", "}" ]
Start Pibrella Example @param args @throws InterruptedException @throws IOException
[ "Start", "Pibrella", "Example" ]
03cacc62223cc59b3118bfcefadabab979fd84c7
https://github.com/Pi4J/pi4j/blob/03cacc62223cc59b3118bfcefadabab979fd84c7/pi4j-example/src/main/java/PibrellaExample.java#L56-L104
28,784
Waikato/moa
moa/src/main/java/moa/clusterers/dstream/CharacteristicVector.java
CharacteristicVector.updateGridDensity
public void updateGridDensity(int currTime, double decayFactor, double dl, double dm) { // record the last attribute int lastAtt = this.getAttribute(); // Update the density grid's density double densityOfG = (Math.pow(decayFactor, (currTime-this.getDensityTimeStamp())) * this.getGridDensity()); this.setGridDensity(densityOfG, currTime); // Evaluate whether or not the density grid is now SPARSE, DENSE or TRANSITIONAL if (this.isSparse(dl)) this.attribute = SPARSE; else if (this.isDense(dm)) this.attribute = DENSE; else this.attribute = TRANSITIONAL; // Evaluate whether or not the density grid attribute has changed and set the attChange flag accordingly if (this.getAttribute() == lastAtt) this.attChange = false; else this.attChange = true; }
java
public void updateGridDensity(int currTime, double decayFactor, double dl, double dm) { // record the last attribute int lastAtt = this.getAttribute(); // Update the density grid's density double densityOfG = (Math.pow(decayFactor, (currTime-this.getDensityTimeStamp())) * this.getGridDensity()); this.setGridDensity(densityOfG, currTime); // Evaluate whether or not the density grid is now SPARSE, DENSE or TRANSITIONAL if (this.isSparse(dl)) this.attribute = SPARSE; else if (this.isDense(dm)) this.attribute = DENSE; else this.attribute = TRANSITIONAL; // Evaluate whether or not the density grid attribute has changed and set the attChange flag accordingly if (this.getAttribute() == lastAtt) this.attChange = false; else this.attChange = true; }
[ "public", "void", "updateGridDensity", "(", "int", "currTime", ",", "double", "decayFactor", ",", "double", "dl", ",", "double", "dm", ")", "{", "// record the last attribute", "int", "lastAtt", "=", "this", ".", "getAttribute", "(", ")", ";", "// Update the density grid's density", "double", "densityOfG", "=", "(", "Math", ".", "pow", "(", "decayFactor", ",", "(", "currTime", "-", "this", ".", "getDensityTimeStamp", "(", ")", ")", ")", "*", "this", ".", "getGridDensity", "(", ")", ")", ";", "this", ".", "setGridDensity", "(", "densityOfG", ",", "currTime", ")", ";", "// Evaluate whether or not the density grid is now SPARSE, DENSE or TRANSITIONAL", "if", "(", "this", ".", "isSparse", "(", "dl", ")", ")", "this", ".", "attribute", "=", "SPARSE", ";", "else", "if", "(", "this", ".", "isDense", "(", "dm", ")", ")", "this", ".", "attribute", "=", "DENSE", ";", "else", "this", ".", "attribute", "=", "TRANSITIONAL", ";", "// Evaluate whether or not the density grid attribute has changed and set the attChange flag accordingly", "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. @param currTime the data stream's current internal time @param decayFactor the value of lambda @param dl the threshold for sparse grids @param dm the threshold for dense grids @param addRecord TRUE if a record has been added to the density grid, FALSE otherwise
[ "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", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/dstream/CharacteristicVector.java#L235-L258
28,785
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/SamoaToWekaInstanceConverter.java
SamoaToWekaInstanceConverter.wekaInstance
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()); /*if (this.wekaInstanceInformation == null) { this.wekaInstanceInformation = this.wekaInstancesInformation(inst.dataset()); } wekaInstance.insertAttributeAt(inst.classIndex()); wekaInstance.setDataset(wekaInstanceInformation); wekaInstance.setClassValue(inst.classValue()); //wekaInstance.setValueSparse(wekaInstance.numAttributes(), inst.classValue());*/ } else { Instance instance = inst; wekaInstance = new weka.core.DenseInstance(instance.weight(), instance.toDoubleArray()); /* if (this.wekaInstanceInformation == null) { this.wekaInstanceInformation = this.wekaInstancesInformation(inst.dataset()); } //We suppose that the class is the last attibute. We should deal when this is not the case wekaInstance.insertAttributeAt(inst.classIndex()); wekaInstance.setDataset(wekaInstanceInformation); wekaInstance.setClassValue(inst.classValue());*/ } if (this.wekaInstanceInformation == null) { this.wekaInstanceInformation = this.wekaInstancesInformation(inst.dataset()); } //wekaInstance.insertAttributeAt(inst.classIndex()); wekaInstance.setDataset(wekaInstanceInformation); if (inst.numOutputAttributes() == 1){ wekaInstance.setClassValue(inst.classValue()); } return wekaInstance; }
java
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()); /*if (this.wekaInstanceInformation == null) { this.wekaInstanceInformation = this.wekaInstancesInformation(inst.dataset()); } wekaInstance.insertAttributeAt(inst.classIndex()); wekaInstance.setDataset(wekaInstanceInformation); wekaInstance.setClassValue(inst.classValue()); //wekaInstance.setValueSparse(wekaInstance.numAttributes(), inst.classValue());*/ } else { Instance instance = inst; wekaInstance = new weka.core.DenseInstance(instance.weight(), instance.toDoubleArray()); /* if (this.wekaInstanceInformation == null) { this.wekaInstanceInformation = this.wekaInstancesInformation(inst.dataset()); } //We suppose that the class is the last attibute. We should deal when this is not the case wekaInstance.insertAttributeAt(inst.classIndex()); wekaInstance.setDataset(wekaInstanceInformation); wekaInstance.setClassValue(inst.classValue());*/ } if (this.wekaInstanceInformation == null) { this.wekaInstanceInformation = this.wekaInstancesInformation(inst.dataset()); } //wekaInstance.insertAttributeAt(inst.classIndex()); wekaInstance.setDataset(wekaInstanceInformation); if (inst.numOutputAttributes() == 1){ wekaInstance.setClassValue(inst.classValue()); } return wekaInstance; }
[ "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", "(", ")", ")", ";", "/*if (this.wekaInstanceInformation == null) {\n this.wekaInstanceInformation = this.wekaInstancesInformation(inst.dataset());\n }\n wekaInstance.insertAttributeAt(inst.classIndex());\n wekaInstance.setDataset(wekaInstanceInformation);\n wekaInstance.setClassValue(inst.classValue());\n //wekaInstance.setValueSparse(wekaInstance.numAttributes(), inst.classValue());*/", "}", "else", "{", "Instance", "instance", "=", "inst", ";", "wekaInstance", "=", "new", "weka", ".", "core", ".", "DenseInstance", "(", "instance", ".", "weight", "(", ")", ",", "instance", ".", "toDoubleArray", "(", ")", ")", ";", "/* if (this.wekaInstanceInformation == null) {\n this.wekaInstanceInformation = this.wekaInstancesInformation(inst.dataset());\n }\n //We suppose that the class is the last attibute. We should deal when this is not the case\n wekaInstance.insertAttributeAt(inst.classIndex());\n wekaInstance.setDataset(wekaInstanceInformation);\n wekaInstance.setClassValue(inst.classValue());*/", "}", "if", "(", "this", ".", "wekaInstanceInformation", "==", "null", ")", "{", "this", ".", "wekaInstanceInformation", "=", "this", ".", "wekaInstancesInformation", "(", "inst", ".", "dataset", "(", ")", ")", ";", "}", "//wekaInstance.insertAttributeAt(inst.classIndex());", "wekaInstance", ".", "setDataset", "(", "wekaInstanceInformation", ")", ";", "if", "(", "inst", ".", "numOutputAttributes", "(", ")", "==", "1", ")", "{", "wekaInstance", ".", "setClassValue", "(", "inst", ".", "classValue", "(", ")", ")", ";", "}", "return", "wekaInstance", ";", "}" ]
Weka instance. @param inst the inst @return the weka.core. instance
[ "Weka", "instance", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/SamoaToWekaInstanceConverter.java#L37-L72
28,786
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/SamoaToWekaInstanceConverter.java
SamoaToWekaInstanceConverter.wekaInstances
public weka.core.Instances wekaInstances(Instances instances) { weka.core.Instances wekaInstances = wekaInstancesInformation(instances); //We assume that we have only one WekaInstanceInformation for SamoaToWekaInstanceConverter this.wekaInstanceInformation = wekaInstances; for (int i = 0; i < instances.numInstances(); i++) { wekaInstances.add(wekaInstance(instances.instance(i))); } return wekaInstances; }
java
public weka.core.Instances wekaInstances(Instances instances) { weka.core.Instances wekaInstances = wekaInstancesInformation(instances); //We assume that we have only one WekaInstanceInformation for SamoaToWekaInstanceConverter this.wekaInstanceInformation = wekaInstances; for (int i = 0; i < instances.numInstances(); i++) { wekaInstances.add(wekaInstance(instances.instance(i))); } return wekaInstances; }
[ "public", "weka", ".", "core", ".", "Instances", "wekaInstances", "(", "Instances", "instances", ")", "{", "weka", ".", "core", ".", "Instances", "wekaInstances", "=", "wekaInstancesInformation", "(", "instances", ")", ";", "//We assume that we have only one WekaInstanceInformation for SamoaToWekaInstanceConverter", "this", ".", "wekaInstanceInformation", "=", "wekaInstances", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "instances", ".", "numInstances", "(", ")", ";", "i", "++", ")", "{", "wekaInstances", ".", "add", "(", "wekaInstance", "(", "instances", ".", "instance", "(", "i", ")", ")", ")", ";", "}", "return", "wekaInstances", ";", "}" ]
Weka instances. @param instances the instances @return the weka.core. instances
[ "Weka", "instances", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/SamoaToWekaInstanceConverter.java#L80-L88
28,787
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/SamoaToWekaInstanceConverter.java
SamoaToWekaInstanceConverter.wekaInstancesInformation
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 { //Assign a classIndex to a MultiLabel instance for compatibility reasons wekaInstances.setClassIndex(instances.instanceInformation.numOutputAttributes()-1); //instances.numAttributes()-1); //Last } //System.out.println(attInfo.get(3).name()); //System.out.println(attInfo.get(3).isNominal()); //System.out.println(wekaInstances.attribute(3).name()); //System.out.println(wekaInstances.attribute(3).isNominal()); return wekaInstances; }
java
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 { //Assign a classIndex to a MultiLabel instance for compatibility reasons wekaInstances.setClassIndex(instances.instanceInformation.numOutputAttributes()-1); //instances.numAttributes()-1); //Last } //System.out.println(attInfo.get(3).name()); //System.out.println(attInfo.get(3).isNominal()); //System.out.println(wekaInstances.attribute(3).name()); //System.out.println(wekaInstances.attribute(3).isNominal()); return wekaInstances; }
[ "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", "{", "//Assign a classIndex to a MultiLabel instance for compatibility reasons", "wekaInstances", ".", "setClassIndex", "(", "instances", ".", "instanceInformation", ".", "numOutputAttributes", "(", ")", "-", "1", ")", ";", "//instances.numAttributes()-1); //Last", "}", "//System.out.println(attInfo.get(3).name());", "//System.out.println(attInfo.get(3).isNominal());", "//System.out.println(wekaInstances.attribute(3).name());", "//System.out.println(wekaInstances.attribute(3).isNominal());", "return", "wekaInstances", ";", "}" ]
Weka instances information. @param instances the instances @return the weka.core. instances
[ "Weka", "instances", "information", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/SamoaToWekaInstanceConverter.java#L96-L115
28,788
Waikato/moa
moa/src/main/java/com/yahoo/labs/samoa/instances/SamoaToWekaInstanceConverter.java
SamoaToWekaInstanceConverter.wekaAttribute
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); } //System.out.println(wekaAttribute.name()); //System.out.println(wekaAttribute.isNominal()); return wekaAttribute; }
java
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); } //System.out.println(wekaAttribute.name()); //System.out.println(wekaAttribute.isNominal()); return wekaAttribute; }
[ "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", ")", ";", "}", "//System.out.println(wekaAttribute.name());", "//System.out.println(wekaAttribute.isNominal());", "return", "wekaAttribute", ";", "}" ]
Weka attribute. @param index the index @param attribute the attribute @return the weka.core. attribute
[ "Weka", "attribute", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/yahoo/labs/samoa/instances/SamoaToWekaInstanceConverter.java#L124-L135
28,789
Waikato/moa
moa/src/main/java/moa/gui/visualization/AbstractGraphPlot.java
AbstractGraphPlot.setGraph
protected void setGraph(MeasureCollection[] measures, MeasureCollection[] stds, Color[] colors) { this.measures = measures; this.measureStds = stds; this.colors = colors; repaint(); }
java
protected void setGraph(MeasureCollection[] measures, MeasureCollection[] stds, Color[] colors) { this.measures = measures; this.measureStds = stds; this.colors = colors; repaint(); }
[ "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. @param measures measure information @param stds standard deviation of the measures @param colors color encoding for the plots
[ "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", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/gui/visualization/AbstractGraphPlot.java#L94-L99
28,790
Waikato/moa
moa/src/main/java/com/github/javacliparser/AbstractClassOption.java
AbstractClassOption.stripPackagePrefix
public static String stripPackagePrefix(String className, Class<?> expectedType) { if (className.startsWith(expectedType.getPackage().getName())) { return className.substring(expectedType.getPackage().getName().length() + 1); } return className; }
java
public static String stripPackagePrefix(String className, Class<?> expectedType) { if (className.startsWith(expectedType.getPackage().getName())) { return className.substring(expectedType.getPackage().getName().length() + 1); } return className; }
[ "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. @param className the name of the class @param expectedType the type of the class @return the class name without its package name prefix
[ "Gets", "the", "class", "name", "without", "its", "package", "name", "prefix", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/com/github/javacliparser/AbstractClassOption.java#L221-L226
28,791
Waikato/moa
moa/src/main/java/moa/clusterers/outliers/AnyOut/util/EMProjectedClustering.java
EMProjectedClustering.getEMClusteringVariances
public int[][] getEMClusteringVariances(double[][] pointArray, int k) { // initialize field and clustering initFields(pointArray, k); setInitialPartitions(pointArray, k); // iterate M and E double currentExpectation, newExpectation = 0.0; double expectationDeviation; int count = 0; do{ currentExpectation = newExpectation; // reassign objects getNewClusterRepresentation(); calculateAllProbabilities(); // calculate new expectation value newExpectation = expectation(); // stop when the deviation is less than minDeviation expectationDeviation = 1.0 - (currentExpectation / newExpectation); count++; } while (expectationDeviation > minDeviation && count < MAXITER); // return the resulting mapping from points to clusters return createProjectedClustering(); }
java
public int[][] getEMClusteringVariances(double[][] pointArray, int k) { // initialize field and clustering initFields(pointArray, k); setInitialPartitions(pointArray, k); // iterate M and E double currentExpectation, newExpectation = 0.0; double expectationDeviation; int count = 0; do{ currentExpectation = newExpectation; // reassign objects getNewClusterRepresentation(); calculateAllProbabilities(); // calculate new expectation value newExpectation = expectation(); // stop when the deviation is less than minDeviation expectationDeviation = 1.0 - (currentExpectation / newExpectation); count++; } while (expectationDeviation > minDeviation && count < MAXITER); // return the resulting mapping from points to clusters return createProjectedClustering(); }
[ "public", "int", "[", "]", "[", "]", "getEMClusteringVariances", "(", "double", "[", "]", "[", "]", "pointArray", ",", "int", "k", ")", "{", "// initialize field and clustering\r", "initFields", "(", "pointArray", ",", "k", ")", ";", "setInitialPartitions", "(", "pointArray", ",", "k", ")", ";", "// iterate M and E\r", "double", "currentExpectation", ",", "newExpectation", "=", "0.0", ";", "double", "expectationDeviation", ";", "int", "count", "=", "0", ";", "do", "{", "currentExpectation", "=", "newExpectation", ";", "// reassign objects\r", "getNewClusterRepresentation", "(", ")", ";", "calculateAllProbabilities", "(", ")", ";", "// calculate new expectation value\r", "newExpectation", "=", "expectation", "(", ")", ";", "// stop when the deviation is less than minDeviation\r", "expectationDeviation", "=", "1.0", "-", "(", "currentExpectation", "/", "newExpectation", ")", ";", "count", "++", ";", "}", "while", "(", "expectationDeviation", ">", "minDeviation", "&&", "count", "<", "MAXITER", ")", ";", "// return the resulting mapping from points to clusters\r", "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 !!! @param pointArray the data set as an array[n][d] of n points with d dimensions @param k the number of requested partitions (!might return less) @return a mapping int[n][k'] of the n given points to the k' resulting clusters
[ "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", "!!!" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/AnyOut/util/EMProjectedClustering.java#L75-L98
28,792
Waikato/moa
moa/src/main/java/moa/clusterers/outliers/AnyOut/util/EMProjectedClustering.java
EMProjectedClustering.setInitialPartitions
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); } // select randomly k initial means // TODO: choose more stable initialization (comment: this is run several times (with different random seeds), i.e. the worst case should not occur) 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]; } } } // set pCgivenX=1 for the closest C for each point 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; } }
java
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); } // select randomly k initial means // TODO: choose more stable initialization (comment: this is run several times (with different random seeds), i.e. the worst case should not occur) 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]; } } } // set pCgivenX=1 for the closest C for each point 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; } }
[ "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", ")", ";", "}", "// select randomly k initial means\r", "// TODO: choose more stable initialization (comment: this is run several times (with different random seeds), i.e. the worst case should not occur)\r", "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", "]", ";", "}", "}", "}", "// set pCgivenX=1 for the closest C for each point\r", "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 @param pointArray @param k
[ "creates", "an", "initial", "partitioning" ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/AnyOut/util/EMProjectedClustering.java#L150-L187
28,793
Waikato/moa
moa/src/main/java/moa/evaluation/ALWindowClassificationPerformanceEvaluator.java
ALWindowClassificationPerformanceEvaluator.doLabelAcqReport
@Override public void doLabelAcqReport(Example<Instance> trainInst, int labelAcquired) { this.acquisitionRateEstimator.add(labelAcquired); this.acquiredInstances += labelAcquired; }
java
@Override public void doLabelAcqReport(Example<Instance> trainInst, int labelAcquired) { this.acquisitionRateEstimator.add(labelAcquired); this.acquiredInstances += labelAcquired; }
[ "@", "Override", "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. @param trainInst the instance that was previously considered @param labelAcquired bool type which indicates if trainInst was acquired by the active learner
[ "Receives", "the", "information", "if", "a", "label", "has", "been", "acquired", "and", "increases", "counters", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/evaluation/ALWindowClassificationPerformanceEvaluator.java#L52-L56
28,794
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.removeSubstring
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(); }
java
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(); }
[ "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. @param inString the string to remove substrings from. @param substring the substring to remove. @return the input string with occurrences of substring removed.
[ "Removes", "all", "occurrences", "of", "a", "string", "from", "another", "string", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L132-L142
28,795
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.replaceSubstring
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(); }
java
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(); }
[ "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. @param inString the string to replace substrings in. @param subString the substring to replace. @param replaceString the replacement substring @return the input string with occurrences of substring replaced.
[ "Replaces", "with", "a", "new", "string", "all", "occurrences", "of", "a", "string", "from", "another", "string", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L153-L165
28,796
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.doubleToString
public static /*@pure@*/ 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); }
java
public static /*@pure@*/ 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); }
[ "public", "static", "/*@pure@*/", "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", ",", "'", "'", ")", ";", "}", "else", "{", "stringBuffer", ".", "insert", "(", "0", ",", "'", "'", ")", ";", "}", "dotPosition", "++", ";", "}", "stringBuffer", ".", "insert", "(", "dotPosition", ",", "'", "'", ")", ";", "if", "(", "(", "precisionValue", "<", "0", ")", "&&", "(", "stringBuffer", ".", "charAt", "(", "1", ")", "==", "'", "'", ")", ")", "{", "stringBuffer", ".", "insert", "(", "1", ",", "'", "'", ")", ";", "}", "else", "if", "(", "stringBuffer", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "stringBuffer", ".", "insert", "(", "0", ",", "'", "'", ")", ";", "}", "int", "currentPos", "=", "stringBuffer", ".", "length", "(", ")", "-", "1", ";", "while", "(", "(", "currentPos", ">", "dotPosition", ")", "&&", "(", "stringBuffer", ".", "charAt", "(", "currentPos", ")", "==", "'", "'", ")", ")", "{", "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. @param value the double value @param afterDecimalPoint the (maximum) number of digits permitted after the decimal point @return the double as a formatted string
[ "Rounds", "a", "double", "and", "converts", "it", "into", "String", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L227-L274
28,797
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.doubleToString
public static /*@pure@*/ String doubleToString(double value, int width, int afterDecimalPoint) { String tempString = doubleToString(value, afterDecimalPoint); char[] result; int dotPosition; if ((afterDecimalPoint >= width) || (tempString.indexOf('E') != -1)) { // Protects sci notation return tempString; } // Initialize result result = new char[width]; for (int i = 0; i < result.length; i++) { result[i] = ' '; } if (afterDecimalPoint > 0) { // Get position of decimal point and insert decimal point 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--; } // Not enough room to decimal align within the supplied width if (offset < 0) { return tempString; } // Copy characters before decimal point for (int i = 0; i < dotPosition; i++) { result[offset + i] = tempString.charAt(i); } // Copy characters after decimal point for (int i = dotPosition + 1; i < tempString.length(); i++) { result[offset + i] = tempString.charAt(i); } return new String(result); }
java
public static /*@pure@*/ String doubleToString(double value, int width, int afterDecimalPoint) { String tempString = doubleToString(value, afterDecimalPoint); char[] result; int dotPosition; if ((afterDecimalPoint >= width) || (tempString.indexOf('E') != -1)) { // Protects sci notation return tempString; } // Initialize result result = new char[width]; for (int i = 0; i < result.length; i++) { result[i] = ' '; } if (afterDecimalPoint > 0) { // Get position of decimal point and insert decimal point 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--; } // Not enough room to decimal align within the supplied width if (offset < 0) { return tempString; } // Copy characters before decimal point for (int i = 0; i < dotPosition; i++) { result[offset + i] = tempString.charAt(i); } // Copy characters after decimal point for (int i = dotPosition + 1; i < tempString.length(); i++) { result[offset + i] = tempString.charAt(i); } return new String(result); }
[ "public", "static", "/*@pure@*/", "String", "doubleToString", "(", "double", "value", ",", "int", "width", ",", "int", "afterDecimalPoint", ")", "{", "String", "tempString", "=", "doubleToString", "(", "value", ",", "afterDecimalPoint", ")", ";", "char", "[", "]", "result", ";", "int", "dotPosition", ";", "if", "(", "(", "afterDecimalPoint", ">=", "width", ")", "||", "(", "tempString", ".", "indexOf", "(", "'", "'", ")", "!=", "-", "1", ")", ")", "{", "// Protects sci notation", "return", "tempString", ";", "}", "// Initialize result", "result", "=", "new", "char", "[", "width", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "length", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "'", "'", ";", "}", "if", "(", "afterDecimalPoint", ">", "0", ")", "{", "// Get position of decimal point and insert decimal point", "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", "--", ";", "}", "// Not enough room to decimal align within the supplied width", "if", "(", "offset", "<", "0", ")", "{", "return", "tempString", ";", "}", "// Copy characters before decimal point", "for", "(", "int", "i", "=", "0", ";", "i", "<", "dotPosition", ";", "i", "++", ")", "{", "result", "[", "offset", "+", "i", "]", "=", "tempString", ".", "charAt", "(", "i", ")", ";", "}", "// Copy characters after decimal point", "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. @param value the double value @param width the width of the string @param afterDecimalPoint the number of digits after the decimal point @return the double as a formatted string
[ "Rounds", "a", "double", "and", "converts", "it", "into", "a", "formatted", "decimal", "-", "justified", "String", ".", "Trailing", "0", "s", "are", "replaced", "with", "spaces", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L285-L337
28,798
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.checkForRemainingOptions
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); } }
java
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); } }
[ "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. @param options an array of strings @exception Exception if there are any non-empty options
[ "Checks", "if", "the", "given", "array", "contains", "any", "non", "-", "empty", "options", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L436-L454
28,799
Waikato/moa
moa/src/main/java/moa/core/Utils.java
Utils.convertNewLines
public static String convertNewLines(String string) { int index; // Replace with \n 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(); // Replace with \r 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(); }
java
public static String convertNewLines(String string) { int index; // Replace with \n 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(); // Replace with \r 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(); }
[ "public", "static", "String", "convertNewLines", "(", "String", "string", ")", "{", "int", "index", ";", "// Replace with \\n", "StringBuffer", "newStringBuffer", "=", "new", "StringBuffer", "(", ")", ";", "while", "(", "(", "index", "=", "string", ".", "indexOf", "(", "'", "'", ")", ")", "!=", "-", "1", ")", "{", "if", "(", "index", ">", "0", ")", "{", "newStringBuffer", ".", "append", "(", "string", ".", "substring", "(", "0", ",", "index", ")", ")", ";", "}", "newStringBuffer", ".", "append", "(", "'", "'", ")", ";", "newStringBuffer", ".", "append", "(", "'", "'", ")", ";", "if", "(", "(", "index", "+", "1", ")", "<", "string", ".", "length", "(", ")", ")", "{", "string", "=", "string", ".", "substring", "(", "index", "+", "1", ")", ";", "}", "else", "{", "string", "=", "\"\"", ";", "}", "}", "newStringBuffer", ".", "append", "(", "string", ")", ";", "string", "=", "newStringBuffer", ".", "toString", "(", ")", ";", "// Replace with \\r", "newStringBuffer", "=", "new", "StringBuffer", "(", ")", ";", "while", "(", "(", "index", "=", "string", ".", "indexOf", "(", "'", "'", ")", ")", "!=", "-", "1", ")", "{", "if", "(", "index", ">", "0", ")", "{", "newStringBuffer", ".", "append", "(", "string", ".", "substring", "(", "0", ",", "index", ")", ")", ";", "}", "newStringBuffer", ".", "append", "(", "'", "'", ")", ";", "newStringBuffer", ".", "append", "(", "'", "'", ")", ";", "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. @param string the string @return the converted string
[ "Converts", "carriage", "returns", "and", "new", "lines", "in", "a", "string", "into", "\\", "r", "and", "\\", "n", "." ]
395982e5100bfe75a3a4d26115462ce2cc74cbb0
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/core/Utils.java#L702-L738