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 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.replace | @Override
public void replace(List list, String resourceVersion) {
lock.writeLock().lock();
try {
Set<String> keys = new HashSet<>();
for (Object obj : list) {
String key = this.keyOf(obj);
keys.add(key);
this.queueActionLocked(DeltaType.Sync, obj);
}
if (this.knownObjects == null) {
for (Map.Entry<String, Deque<MutablePair<DeltaType, Object>>> entry :
this.items.entrySet()) {
if (keys.contains(entry.getKey())) {
continue;
}
Object deletedObj = null;
MutablePair<DeltaType, Object> delta = entry.getValue().peekLast(); // get newest
if (delta != null) {
deletedObj = delta.getRight();
}
this.queueActionLocked(
DeltaType.Deleted, new DeletedFinalStateUnknown(entry.getKey(), deletedObj));
}
if (!this.populated) {
this.populated = true;
this.initialPopulationCount = list.size();
}
return;
}
// Detect deletions not already in the queue.
List<String> knownKeys = this.knownObjects.listKeys();
int queueDeletion = 0;
for (String knownKey : knownKeys) {
if (keys.contains(knownKey)) {
continue;
}
Object deletedObj = this.knownObjects.getByKey(knownKey);
if (deletedObj == null) {
log.warn(
"Key {} does not exist in known objects store, placing DeleteFinalStateUnknown marker without object",
knownKey);
}
queueDeletion++;
this.queueActionLocked(
DeltaType.Deleted, new DeletedFinalStateUnknown<>(knownKey, deletedObj));
}
if (!this.populated) {
this.populated = true;
this.initialPopulationCount = list.size() + queueDeletion;
}
} finally {
lock.writeLock().unlock();
}
} | java | @Override
public void replace(List list, String resourceVersion) {
lock.writeLock().lock();
try {
Set<String> keys = new HashSet<>();
for (Object obj : list) {
String key = this.keyOf(obj);
keys.add(key);
this.queueActionLocked(DeltaType.Sync, obj);
}
if (this.knownObjects == null) {
for (Map.Entry<String, Deque<MutablePair<DeltaType, Object>>> entry :
this.items.entrySet()) {
if (keys.contains(entry.getKey())) {
continue;
}
Object deletedObj = null;
MutablePair<DeltaType, Object> delta = entry.getValue().peekLast(); // get newest
if (delta != null) {
deletedObj = delta.getRight();
}
this.queueActionLocked(
DeltaType.Deleted, new DeletedFinalStateUnknown(entry.getKey(), deletedObj));
}
if (!this.populated) {
this.populated = true;
this.initialPopulationCount = list.size();
}
return;
}
// Detect deletions not already in the queue.
List<String> knownKeys = this.knownObjects.listKeys();
int queueDeletion = 0;
for (String knownKey : knownKeys) {
if (keys.contains(knownKey)) {
continue;
}
Object deletedObj = this.knownObjects.getByKey(knownKey);
if (deletedObj == null) {
log.warn(
"Key {} does not exist in known objects store, placing DeleteFinalStateUnknown marker without object",
knownKey);
}
queueDeletion++;
this.queueActionLocked(
DeltaType.Deleted, new DeletedFinalStateUnknown<>(knownKey, deletedObj));
}
if (!this.populated) {
this.populated = true;
this.initialPopulationCount = list.size() + queueDeletion;
}
} finally {
lock.writeLock().unlock();
}
} | [
"@",
"Override",
"public",
"void",
"replace",
"(",
"List",
"list",
",",
"String",
"resourceVersion",
")",
"{",
"lock",
".",
"writeLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"try",
"{",
"Set",
"<",
"String",
">",
"keys",
"=",
"new",
"HashSet",
"<>",... | Replace the item forcibly.
@param list the list
@param resourceVersion the resource version | [
"Replace",
"the",
"item",
"forcibly",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L130-L190 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.resync | @Override
public void resync() {
lock.writeLock().lock();
try {
if (this.knownObjects == null) {
return;
}
List<String> keys = this.knownObjects.listKeys();
for (String key : keys) {
syncKeyLocked(key);
}
} finally {
lock.writeLock().unlock();
}
} | java | @Override
public void resync() {
lock.writeLock().lock();
try {
if (this.knownObjects == null) {
return;
}
List<String> keys = this.knownObjects.listKeys();
for (String key : keys) {
syncKeyLocked(key);
}
} finally {
lock.writeLock().unlock();
}
} | [
"@",
"Override",
"public",
"void",
"resync",
"(",
")",
"{",
"lock",
".",
"writeLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"this",
".",
"knownObjects",
"==",
"null",
")",
"{",
"return",
";",
"}",
"List",
"<",
"String",
">"... | Re-sync the delta FIFO. First, It locks the queue to block any more write operation until it
finishes processing all the pending items in the queue. | [
"Re",
"-",
"sync",
"the",
"delta",
"FIFO",
".",
"First",
"It",
"locks",
"the",
"queue",
"to",
"block",
"any",
"more",
"write",
"operation",
"until",
"it",
"finishes",
"processing",
"all",
"the",
"pending",
"items",
"in",
"the",
"queue",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L196-L211 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.listKeys | @Override
public List<String> listKeys() {
lock.readLock().lock();
try {
List<String> keyList = new ArrayList<>(items.size());
for (Map.Entry<String, Deque<MutablePair<DeltaType, Object>>> entry : items.entrySet()) {
keyList.add(entry.getKey());
}
return keyList;
} finally {
lock.readLock().unlock();
}
} | java | @Override
public List<String> listKeys() {
lock.readLock().lock();
try {
List<String> keyList = new ArrayList<>(items.size());
for (Map.Entry<String, Deque<MutablePair<DeltaType, Object>>> entry : items.entrySet()) {
keyList.add(entry.getKey());
}
return keyList;
} finally {
lock.readLock().unlock();
}
} | [
"@",
"Override",
"public",
"List",
"<",
"String",
">",
"listKeys",
"(",
")",
"{",
"lock",
".",
"readLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"try",
"{",
"List",
"<",
"String",
">",
"keyList",
"=",
"new",
"ArrayList",
"<>",
"(",
"items",
".",
... | List keys list.
@return the list | [
"List",
"keys",
"list",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L218-L230 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.get | @Override
public Object get(Object obj) {
String key = this.keyOf(obj);
return this.getByKey(key);
} | java | @Override
public Object get(Object obj) {
String key = this.keyOf(obj);
return this.getByKey(key);
} | [
"@",
"Override",
"public",
"Object",
"get",
"(",
"Object",
"obj",
")",
"{",
"String",
"key",
"=",
"this",
".",
"keyOf",
"(",
"obj",
")",
";",
"return",
"this",
".",
"getByKey",
"(",
"key",
")",
";",
"}"
] | Get object.
@param obj the obj
@return the object | [
"Get",
"object",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L238-L242 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.list | @Override
public List<Object> list() {
lock.readLock().lock();
List<Object> objects = new ArrayList<>();
try {
// TODO: make a generic deep copy utility
for (Map.Entry<String, Deque<MutablePair<DeltaType, Object>>> entry : items.entrySet()) {
Deque<MutablePair<DeltaType, Object>> copiedDeltas = new LinkedList<>(entry.getValue());
objects.add(copiedDeltas);
}
} finally {
lock.readLock().unlock();
}
return objects;
} | java | @Override
public List<Object> list() {
lock.readLock().lock();
List<Object> objects = new ArrayList<>();
try {
// TODO: make a generic deep copy utility
for (Map.Entry<String, Deque<MutablePair<DeltaType, Object>>> entry : items.entrySet()) {
Deque<MutablePair<DeltaType, Object>> copiedDeltas = new LinkedList<>(entry.getValue());
objects.add(copiedDeltas);
}
} finally {
lock.readLock().unlock();
}
return objects;
} | [
"@",
"Override",
"public",
"List",
"<",
"Object",
">",
"list",
"(",
")",
"{",
"lock",
".",
"readLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"List",
"<",
"Object",
">",
"objects",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"try",
"{",
"// TODO... | List list.
@return the list | [
"List",
"list",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L270-L284 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.pop | public Deque<MutablePair<DeltaType, Object>> pop(
Consumer<Deque<MutablePair<DeltaType, Object>>> func) throws InterruptedException {
lock.writeLock().lock();
try {
while (true) {
while (queue.isEmpty()) {
notEmpty.await();
}
// there should have data now
String id = this.queue.removeFirst();
if (this.initialPopulationCount > 0) {
this.initialPopulationCount--;
}
if (!this.items.containsKey(id)) {
// Item may have been deleted subsequently.
continue;
}
Deque<MutablePair<DeltaType, Object>> deltas = this.items.get(id);
this.items.remove(id);
func.accept(deltas);
// Don't make any copyDeltas here
return deltas;
}
} finally {
lock.writeLock().unlock();
}
} | java | public Deque<MutablePair<DeltaType, Object>> pop(
Consumer<Deque<MutablePair<DeltaType, Object>>> func) throws InterruptedException {
lock.writeLock().lock();
try {
while (true) {
while (queue.isEmpty()) {
notEmpty.await();
}
// there should have data now
String id = this.queue.removeFirst();
if (this.initialPopulationCount > 0) {
this.initialPopulationCount--;
}
if (!this.items.containsKey(id)) {
// Item may have been deleted subsequently.
continue;
}
Deque<MutablePair<DeltaType, Object>> deltas = this.items.get(id);
this.items.remove(id);
func.accept(deltas);
// Don't make any copyDeltas here
return deltas;
}
} finally {
lock.writeLock().unlock();
}
} | [
"public",
"Deque",
"<",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
">",
"pop",
"(",
"Consumer",
"<",
"Deque",
"<",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
">",
">",
"func",
")",
"throws",
"InterruptedException",
"{",
"lock",
".",
"... | Pop deltas.
@param func the func
@return the deltas
@throws Exception the exception | [
"Pop",
"deltas",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L293-L320 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.queueActionLocked | private void queueActionLocked(DeltaType actionType, Object obj) {
String id = this.keyOf(obj);
// If object is supposed to be deleted (last event is Deleted),
// then we should ignore Sync events, because it would result in
// recreation of this object.
if (actionType == DeltaType.Sync && this.willObjectBeDeletedLocked(id)) {
return;
}
Deque<MutablePair<DeltaType, Object>> deltas = items.get(id);
if (deltas == null) {
Deque<MutablePair<DeltaType, Object>> deltaList = new LinkedList<>();
deltaList.add(new MutablePair(actionType, obj));
deltas = new LinkedList<>(deltaList);
} else {
deltas.add(new MutablePair<DeltaType, Object>(actionType, obj));
}
// TODO(yue9944882): Eliminate the force class casting here
Deque<MutablePair<DeltaType, Object>> combinedDeltaList =
combineDeltas((LinkedList<MutablePair<DeltaType, Object>>) deltas);
boolean exist = items.containsKey(id);
if (combinedDeltaList != null && combinedDeltaList.size() > 0) {
if (!exist) {
this.queue.add(id);
}
this.items.put(id, new LinkedList<>(combinedDeltaList));
notEmpty.signalAll();
} else {
this.items.remove(id);
}
} | java | private void queueActionLocked(DeltaType actionType, Object obj) {
String id = this.keyOf(obj);
// If object is supposed to be deleted (last event is Deleted),
// then we should ignore Sync events, because it would result in
// recreation of this object.
if (actionType == DeltaType.Sync && this.willObjectBeDeletedLocked(id)) {
return;
}
Deque<MutablePair<DeltaType, Object>> deltas = items.get(id);
if (deltas == null) {
Deque<MutablePair<DeltaType, Object>> deltaList = new LinkedList<>();
deltaList.add(new MutablePair(actionType, obj));
deltas = new LinkedList<>(deltaList);
} else {
deltas.add(new MutablePair<DeltaType, Object>(actionType, obj));
}
// TODO(yue9944882): Eliminate the force class casting here
Deque<MutablePair<DeltaType, Object>> combinedDeltaList =
combineDeltas((LinkedList<MutablePair<DeltaType, Object>>) deltas);
boolean exist = items.containsKey(id);
if (combinedDeltaList != null && combinedDeltaList.size() > 0) {
if (!exist) {
this.queue.add(id);
}
this.items.put(id, new LinkedList<>(combinedDeltaList));
notEmpty.signalAll();
} else {
this.items.remove(id);
}
} | [
"private",
"void",
"queueActionLocked",
"(",
"DeltaType",
"actionType",
",",
"Object",
"obj",
")",
"{",
"String",
"id",
"=",
"this",
".",
"keyOf",
"(",
"obj",
")",
";",
"// If object is supposed to be deleted (last event is Deleted),",
"// then we should ignore Sync event... | queueActionLocked appends to the delta list for the object. Caller must hold the lock. | [
"queueActionLocked",
"appends",
"to",
"the",
"delta",
"list",
"for",
"the",
"object",
".",
"Caller",
"must",
"hold",
"the",
"lock",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L337-L370 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.willObjectBeDeletedLocked | private boolean willObjectBeDeletedLocked(String id) {
if (!this.items.containsKey(id)) {
return false;
}
Deque<MutablePair<DeltaType, Object>> deltas = this.items.get(id);
return !(Collections.isEmptyCollection(deltas))
&& deltas.peekLast().getLeft().equals(DeltaType.Deleted);
} | java | private boolean willObjectBeDeletedLocked(String id) {
if (!this.items.containsKey(id)) {
return false;
}
Deque<MutablePair<DeltaType, Object>> deltas = this.items.get(id);
return !(Collections.isEmptyCollection(deltas))
&& deltas.peekLast().getLeft().equals(DeltaType.Deleted);
} | [
"private",
"boolean",
"willObjectBeDeletedLocked",
"(",
"String",
"id",
")",
"{",
"if",
"(",
"!",
"this",
".",
"items",
".",
"containsKey",
"(",
"id",
")",
")",
"{",
"return",
"false",
";",
"}",
"Deque",
"<",
"MutablePair",
"<",
"DeltaType",
",",
"Object... | willObjectBeDeletedLocked returns true only if the last delta for the give object is Deleted.
Caller must hold the lock. | [
"willObjectBeDeletedLocked",
"returns",
"true",
"only",
"if",
"the",
"last",
"delta",
"for",
"the",
"give",
"object",
"is",
"Deleted",
".",
"Caller",
"must",
"hold",
"the",
"lock",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L376-L383 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.keyOf | private String keyOf(Object obj) {
Object innerObj = obj;
if (obj instanceof Deque) {
Deque<MutablePair<DeltaType, Object>> deltas = (Deque<MutablePair<DeltaType, Object>>) obj;
if (deltas.size() == 0) {
throw new NoSuchElementException("0 length Deltas object; can't get key");
}
innerObj = deltas.peekLast().getRight();
}
if (innerObj instanceof DeletedFinalStateUnknown) {
return ((DeletedFinalStateUnknown) innerObj).key;
}
return keyFunc.apply((ApiType) innerObj);
} | java | private String keyOf(Object obj) {
Object innerObj = obj;
if (obj instanceof Deque) {
Deque<MutablePair<DeltaType, Object>> deltas = (Deque<MutablePair<DeltaType, Object>>) obj;
if (deltas.size() == 0) {
throw new NoSuchElementException("0 length Deltas object; can't get key");
}
innerObj = deltas.peekLast().getRight();
}
if (innerObj instanceof DeletedFinalStateUnknown) {
return ((DeletedFinalStateUnknown) innerObj).key;
}
return keyFunc.apply((ApiType) innerObj);
} | [
"private",
"String",
"keyOf",
"(",
"Object",
"obj",
")",
"{",
"Object",
"innerObj",
"=",
"obj",
";",
"if",
"(",
"obj",
"instanceof",
"Deque",
")",
"{",
"Deque",
"<",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
">",
"deltas",
"=",
"(",
"Deque",... | DeletedFinalStateUnknown objects. | [
"DeletedFinalStateUnknown",
"objects",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L387-L400 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.syncKeyLocked | private void syncKeyLocked(String key) {
ApiType obj = this.knownObjects.getByKey(key);
if (obj == null) {
return;
}
String id = this.keyOf(obj);
Deque<MutablePair<DeltaType, Object>> deltas = this.items.get(id);
if (deltas != null && !(Collections.isEmptyCollection(deltas))) {
return;
}
this.queueActionLocked(DeltaType.Sync, obj);
} | java | private void syncKeyLocked(String key) {
ApiType obj = this.knownObjects.getByKey(key);
if (obj == null) {
return;
}
String id = this.keyOf(obj);
Deque<MutablePair<DeltaType, Object>> deltas = this.items.get(id);
if (deltas != null && !(Collections.isEmptyCollection(deltas))) {
return;
}
this.queueActionLocked(DeltaType.Sync, obj);
} | [
"private",
"void",
"syncKeyLocked",
"(",
"String",
"key",
")",
"{",
"ApiType",
"obj",
"=",
"this",
".",
"knownObjects",
".",
"getByKey",
"(",
"key",
")",
";",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"return",
";",
"}",
"String",
"id",
"=",
"this",
... | Add Sync delta. Caller must hold the lock. | [
"Add",
"Sync",
"delta",
".",
"Caller",
"must",
"hold",
"the",
"lock",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L403-L416 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.combineDeltas | private Deque<MutablePair<DeltaType, Object>> combineDeltas(
LinkedList<MutablePair<DeltaType, Object>> deltas) {
if (deltas.size() < 2) {
return deltas;
}
int size = deltas.size();
MutablePair<DeltaType, Object> d1 = deltas.peekLast();
MutablePair<DeltaType, Object> d2 = deltas.get(size - 2);
MutablePair<DeltaType, Object> out = isDuplicate(d1, d2);
if (out != null) {
Deque<MutablePair<DeltaType, Object>> newDeltas = new LinkedList<>();
newDeltas.addAll(deltas.subList(0, size - 2));
newDeltas.add(out);
return newDeltas;
}
return deltas;
} | java | private Deque<MutablePair<DeltaType, Object>> combineDeltas(
LinkedList<MutablePair<DeltaType, Object>> deltas) {
if (deltas.size() < 2) {
return deltas;
}
int size = deltas.size();
MutablePair<DeltaType, Object> d1 = deltas.peekLast();
MutablePair<DeltaType, Object> d2 = deltas.get(size - 2);
MutablePair<DeltaType, Object> out = isDuplicate(d1, d2);
if (out != null) {
Deque<MutablePair<DeltaType, Object>> newDeltas = new LinkedList<>();
newDeltas.addAll(deltas.subList(0, size - 2));
newDeltas.add(out);
return newDeltas;
}
return deltas;
} | [
"private",
"Deque",
"<",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
">",
"combineDeltas",
"(",
"LinkedList",
"<",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
">",
"deltas",
")",
"{",
"if",
"(",
"deltas",
".",
"size",
"(",
")",
"<",
"... | order. This will combine the most recent two deltas if they are the same. | [
"order",
".",
"This",
"will",
"combine",
"the",
"most",
"recent",
"two",
"deltas",
"if",
"they",
"are",
"the",
"same",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L420-L436 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.isDuplicate | private MutablePair<DeltaType, Object> isDuplicate(
MutablePair<DeltaType, Object> d1, MutablePair<DeltaType, Object> d2) {
MutablePair<DeltaType, Object> deletionDelta = isDeletionDup(d1, d2);
if (deletionDelta != null) {
return deletionDelta;
}
return null;
} | java | private MutablePair<DeltaType, Object> isDuplicate(
MutablePair<DeltaType, Object> d1, MutablePair<DeltaType, Object> d2) {
MutablePair<DeltaType, Object> deletionDelta = isDeletionDup(d1, d2);
if (deletionDelta != null) {
return deletionDelta;
}
return null;
} | [
"private",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
"isDuplicate",
"(",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
"d1",
",",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
"d2",
")",
"{",
"MutablePair",
"<",
"DeltaType",
",",
"... | If d1 & d2 represent the same event, returns the delta that ought to be kept.
@param d1 the elder one
@param d2 the most one
@return the one ought to be kept | [
"If",
"d1",
"&",
"d2",
"represent",
"the",
"same",
"event",
"returns",
"the",
"delta",
"that",
"ought",
"to",
"be",
"kept",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L445-L452 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java | DeltaFIFO.isDeletionDup | private MutablePair<DeltaType, Object> isDeletionDup(
MutablePair<DeltaType, Object> d1, MutablePair<DeltaType, Object> d2) {
if (!d1.getLeft().equals(DeltaType.Deleted) || !d2.getLeft().equals(DeltaType.Deleted)) {
return null;
}
Object obj = d2.getRight();
if (obj instanceof DeletedFinalStateUnknown) {
return d1;
}
return d2;
} | java | private MutablePair<DeltaType, Object> isDeletionDup(
MutablePair<DeltaType, Object> d1, MutablePair<DeltaType, Object> d2) {
if (!d1.getLeft().equals(DeltaType.Deleted) || !d2.getLeft().equals(DeltaType.Deleted)) {
return null;
}
Object obj = d2.getRight();
if (obj instanceof DeletedFinalStateUnknown) {
return d1;
}
return d2;
} | [
"private",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
"isDeletionDup",
"(",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
"d1",
",",
"MutablePair",
"<",
"DeltaType",
",",
"Object",
">",
"d2",
")",
"{",
"if",
"(",
"!",
"d1",
".",
"getLeft... | keep the one with the most information if both are deletions.
@param d1 the most one
@param d2 the elder one
@return the most one | [
"keep",
"the",
"one",
"with",
"the",
"most",
"information",
"if",
"both",
"are",
"deletions",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/DeltaFIFO.java#L461-L471 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/ReflectorRunnable.java | ReflectorRunnable.run | public void run() {
try {
log.info("{}#Start listing and watching...", apiTypeClass);
ApiListType list = listerWatcher.list(new CallGeneratorParams(Boolean.FALSE, null, null));
V1ListMeta listMeta = Reflect.listMetadata(list);
String resourceVersion = listMeta.getResourceVersion();
List<ApiType> items = Reflect.getItems(list);
if (log.isDebugEnabled()) {
log.debug("{}#Extract resourceVersion {} list meta", apiTypeClass, resourceVersion);
}
this.syncWith(items, resourceVersion);
this.lastSyncResourceVersion = resourceVersion;
if (log.isDebugEnabled()) {
log.debug("{}#Start watching with {}...", apiTypeClass, lastSyncResourceVersion);
}
while (true) {
if (!isActive.get()) {
if (watch != null) {
watch.close();
return;
}
}
try {
if (log.isDebugEnabled()) {
log.debug(
"{}#Start watch with resource version {}", apiTypeClass, lastSyncResourceVersion);
}
watch =
listerWatcher.watch(
new CallGeneratorParams(
Boolean.TRUE,
lastSyncResourceVersion,
Long.valueOf(Duration.ofMinutes(5).toMillis()).intValue()));
watchHandler(watch);
} catch (Throwable t) {
log.info("{}#Watch connection get exception {}", apiTypeClass, t.getMessage());
Throwable cause = t.getCause();
// If this is "connection refused" error, it means that most likely apiserver is not
// responsive.
// It doesn't make sense to re-list all objects because most likely we will be able to
// restart
// watch where we ended.
// If that's the case wait and resend watch request.
if (cause != null && (cause instanceof ConnectException)) {
log.info("{}#Watch get connect exception, retry watch", apiTypeClass);
Thread.sleep(1000L);
continue;
}
if ((t instanceof RuntimeException)
&& t.getMessage().contains("IO Exception during hasNext")) {
log.info("{}#Read timeout retry list and watch", apiTypeClass);
return;
}
log.error("{}#Watch failed as {} unexpected", apiTypeClass, t.getMessage(), t);
return;
} finally {
if (watch != null) {
watch.close();
watch = null;
}
}
}
} catch (Throwable t) {
log.error("{}#Failed to list-watch: {}", apiTypeClass, t);
}
} | java | public void run() {
try {
log.info("{}#Start listing and watching...", apiTypeClass);
ApiListType list = listerWatcher.list(new CallGeneratorParams(Boolean.FALSE, null, null));
V1ListMeta listMeta = Reflect.listMetadata(list);
String resourceVersion = listMeta.getResourceVersion();
List<ApiType> items = Reflect.getItems(list);
if (log.isDebugEnabled()) {
log.debug("{}#Extract resourceVersion {} list meta", apiTypeClass, resourceVersion);
}
this.syncWith(items, resourceVersion);
this.lastSyncResourceVersion = resourceVersion;
if (log.isDebugEnabled()) {
log.debug("{}#Start watching with {}...", apiTypeClass, lastSyncResourceVersion);
}
while (true) {
if (!isActive.get()) {
if (watch != null) {
watch.close();
return;
}
}
try {
if (log.isDebugEnabled()) {
log.debug(
"{}#Start watch with resource version {}", apiTypeClass, lastSyncResourceVersion);
}
watch =
listerWatcher.watch(
new CallGeneratorParams(
Boolean.TRUE,
lastSyncResourceVersion,
Long.valueOf(Duration.ofMinutes(5).toMillis()).intValue()));
watchHandler(watch);
} catch (Throwable t) {
log.info("{}#Watch connection get exception {}", apiTypeClass, t.getMessage());
Throwable cause = t.getCause();
// If this is "connection refused" error, it means that most likely apiserver is not
// responsive.
// It doesn't make sense to re-list all objects because most likely we will be able to
// restart
// watch where we ended.
// If that's the case wait and resend watch request.
if (cause != null && (cause instanceof ConnectException)) {
log.info("{}#Watch get connect exception, retry watch", apiTypeClass);
Thread.sleep(1000L);
continue;
}
if ((t instanceof RuntimeException)
&& t.getMessage().contains("IO Exception during hasNext")) {
log.info("{}#Read timeout retry list and watch", apiTypeClass);
return;
}
log.error("{}#Watch failed as {} unexpected", apiTypeClass, t.getMessage(), t);
return;
} finally {
if (watch != null) {
watch.close();
watch = null;
}
}
}
} catch (Throwable t) {
log.error("{}#Failed to list-watch: {}", apiTypeClass, t);
}
} | [
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"log",
".",
"info",
"(",
"\"{}#Start listing and watching...\"",
",",
"apiTypeClass",
")",
";",
"ApiListType",
"list",
"=",
"listerWatcher",
".",
"list",
"(",
"new",
"CallGeneratorParams",
"(",
"Boolean",
"."... | run first lists all items and get the resource version at the moment of call, and then use the
resource version to watch. | [
"run",
"first",
"lists",
"all",
"items",
"and",
"get",
"the",
"resource",
"version",
"at",
"the",
"moment",
"of",
"call",
"and",
"then",
"use",
"the",
"resource",
"version",
"to",
"watch",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/ReflectorRunnable.java#L43-L113 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/ClientBuilder.java | ClientBuilder.cluster | public static ClientBuilder cluster() throws IOException {
final ClientBuilder builder = new ClientBuilder();
final String host = System.getenv(ENV_SERVICE_HOST);
final String port = System.getenv(ENV_SERVICE_PORT);
builder.setBasePath("https://" + host + ":" + port);
final String token =
new String(
Files.readAllBytes(Paths.get(SERVICEACCOUNT_TOKEN_PATH)), Charset.defaultCharset());
builder.setCertificateAuthority(Files.readAllBytes(Paths.get(SERVICEACCOUNT_CA_PATH)));
builder.setAuthentication(new AccessTokenAuthentication(token));
return builder;
} | java | public static ClientBuilder cluster() throws IOException {
final ClientBuilder builder = new ClientBuilder();
final String host = System.getenv(ENV_SERVICE_HOST);
final String port = System.getenv(ENV_SERVICE_PORT);
builder.setBasePath("https://" + host + ":" + port);
final String token =
new String(
Files.readAllBytes(Paths.get(SERVICEACCOUNT_TOKEN_PATH)), Charset.defaultCharset());
builder.setCertificateAuthority(Files.readAllBytes(Paths.get(SERVICEACCOUNT_CA_PATH)));
builder.setAuthentication(new AccessTokenAuthentication(token));
return builder;
} | [
"public",
"static",
"ClientBuilder",
"cluster",
"(",
")",
"throws",
"IOException",
"{",
"final",
"ClientBuilder",
"builder",
"=",
"new",
"ClientBuilder",
"(",
")",
";",
"final",
"String",
"host",
"=",
"System",
".",
"getenv",
"(",
"ENV_SERVICE_HOST",
")",
";",... | Creates a builder which is pre-configured from the cluster configuration.
@return <tt>ClientBuilder</tt> configured from the cluster configuration.
@throws IOException if the Service Account Token Path or CA Path is not readable. | [
"Creates",
"a",
"builder",
"which",
"is",
"pre",
"-",
"configured",
"from",
"the",
"cluster",
"configuration",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/ClientBuilder.java#L196-L210 | train |
kubernetes-client/java | examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java | ExpandedExample.getAllNameSpaces | public static List<String> getAllNameSpaces() throws ApiException {
V1NamespaceList listNamespace =
COREV1_API.listNamespace(
null, "true", null, null, null, 0, null, Integer.MAX_VALUE, Boolean.FALSE);
List<String> list =
listNamespace
.getItems()
.stream()
.map(v1Namespace -> v1Namespace.getMetadata().getName())
.collect(Collectors.toList());
return list;
} | java | public static List<String> getAllNameSpaces() throws ApiException {
V1NamespaceList listNamespace =
COREV1_API.listNamespace(
null, "true", null, null, null, 0, null, Integer.MAX_VALUE, Boolean.FALSE);
List<String> list =
listNamespace
.getItems()
.stream()
.map(v1Namespace -> v1Namespace.getMetadata().getName())
.collect(Collectors.toList());
return list;
} | [
"public",
"static",
"List",
"<",
"String",
">",
"getAllNameSpaces",
"(",
")",
"throws",
"ApiException",
"{",
"V1NamespaceList",
"listNamespace",
"=",
"COREV1_API",
".",
"listNamespace",
"(",
"null",
",",
"\"true\"",
",",
"null",
",",
"null",
",",
"null",
",",
... | Get all namespaces in k8s cluster
@return
@throws ApiException | [
"Get",
"all",
"namespaces",
"in",
"k8s",
"cluster"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java#L103-L114 | train |
kubernetes-client/java | examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java | ExpandedExample.getPods | public static List<String> getPods() throws ApiException {
V1PodList v1podList =
COREV1_API.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
List<String> podList =
v1podList
.getItems()
.stream()
.map(v1Pod -> v1Pod.getMetadata().getName())
.collect(Collectors.toList());
return podList;
} | java | public static List<String> getPods() throws ApiException {
V1PodList v1podList =
COREV1_API.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
List<String> podList =
v1podList
.getItems()
.stream()
.map(v1Pod -> v1Pod.getMetadata().getName())
.collect(Collectors.toList());
return podList;
} | [
"public",
"static",
"List",
"<",
"String",
">",
"getPods",
"(",
")",
"throws",
"ApiException",
"{",
"V1PodList",
"v1podList",
"=",
"COREV1_API",
".",
"listPodForAllNamespaces",
"(",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
",",
"null",
"... | List all pod names in all namespaces in k8s cluster
@return
@throws ApiException | [
"List",
"all",
"pod",
"names",
"in",
"all",
"namespaces",
"in",
"k8s",
"cluster"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java#L122-L132 | train |
kubernetes-client/java | examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java | ExpandedExample.getNamespacedPod | public static List<String> getNamespacedPod(String namespace, String label) throws ApiException {
V1PodList listNamespacedPod =
COREV1_API.listNamespacedPod(
namespace,
null,
null,
null,
null,
label,
Integer.MAX_VALUE,
null,
TIME_OUT_VALUE,
Boolean.FALSE);
List<String> listPods =
listNamespacedPod
.getItems()
.stream()
.map(v1pod -> v1pod.getMetadata().getName())
.collect(Collectors.toList());
return listPods;
} | java | public static List<String> getNamespacedPod(String namespace, String label) throws ApiException {
V1PodList listNamespacedPod =
COREV1_API.listNamespacedPod(
namespace,
null,
null,
null,
null,
label,
Integer.MAX_VALUE,
null,
TIME_OUT_VALUE,
Boolean.FALSE);
List<String> listPods =
listNamespacedPod
.getItems()
.stream()
.map(v1pod -> v1pod.getMetadata().getName())
.collect(Collectors.toList());
return listPods;
} | [
"public",
"static",
"List",
"<",
"String",
">",
"getNamespacedPod",
"(",
"String",
"namespace",
",",
"String",
"label",
")",
"throws",
"ApiException",
"{",
"V1PodList",
"listNamespacedPod",
"=",
"COREV1_API",
".",
"listNamespacedPod",
"(",
"namespace",
",",
"null"... | List pod in specific namespace with label
@param namespace
@param label
@return
@throws ApiException | [
"List",
"pod",
"in",
"specific",
"namespace",
"with",
"label"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java#L163-L183 | train |
kubernetes-client/java | examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java | ExpandedExample.getServices | public static List<String> getServices() throws ApiException {
V1ServiceList listNamespacedService =
COREV1_API.listNamespacedService(
DEFAULT_NAME_SPACE,
null,
null,
null,
null,
null,
Integer.MAX_VALUE,
null,
TIME_OUT_VALUE,
Boolean.FALSE);
return listNamespacedService
.getItems()
.stream()
.map(v1service -> v1service.getMetadata().getName())
.collect(Collectors.toList());
} | java | public static List<String> getServices() throws ApiException {
V1ServiceList listNamespacedService =
COREV1_API.listNamespacedService(
DEFAULT_NAME_SPACE,
null,
null,
null,
null,
null,
Integer.MAX_VALUE,
null,
TIME_OUT_VALUE,
Boolean.FALSE);
return listNamespacedService
.getItems()
.stream()
.map(v1service -> v1service.getMetadata().getName())
.collect(Collectors.toList());
} | [
"public",
"static",
"List",
"<",
"String",
">",
"getServices",
"(",
")",
"throws",
"ApiException",
"{",
"V1ServiceList",
"listNamespacedService",
"=",
"COREV1_API",
".",
"listNamespacedService",
"(",
"DEFAULT_NAME_SPACE",
",",
"null",
",",
"null",
",",
"null",
","... | List all Services in default namespace
@return
@throws ApiException | [
"List",
"all",
"Services",
"in",
"default",
"namespace"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java#L191-L209 | train |
kubernetes-client/java | examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java | ExpandedExample.printLog | public static void printLog(String namespace, String podName) throws ApiException {
// https://github.com/kubernetes-client/java/blob/master/kubernetes/docs/CoreV1Api.md#readNamespacedPodLog
String readNamespacedPodLog =
COREV1_API.readNamespacedPodLog(
podName,
namespace,
null,
Boolean.FALSE,
Integer.MAX_VALUE,
null,
Boolean.FALSE,
Integer.MAX_VALUE,
40,
Boolean.FALSE);
System.out.println(readNamespacedPodLog);
} | java | public static void printLog(String namespace, String podName) throws ApiException {
// https://github.com/kubernetes-client/java/blob/master/kubernetes/docs/CoreV1Api.md#readNamespacedPodLog
String readNamespacedPodLog =
COREV1_API.readNamespacedPodLog(
podName,
namespace,
null,
Boolean.FALSE,
Integer.MAX_VALUE,
null,
Boolean.FALSE,
Integer.MAX_VALUE,
40,
Boolean.FALSE);
System.out.println(readNamespacedPodLog);
} | [
"public",
"static",
"void",
"printLog",
"(",
"String",
"namespace",
",",
"String",
"podName",
")",
"throws",
"ApiException",
"{",
"// https://github.com/kubernetes-client/java/blob/master/kubernetes/docs/CoreV1Api.md#readNamespacedPodLog",
"String",
"readNamespacedPodLog",
"=",
"... | Print out the Log for specific Pods
@param namespace
@param podName
@throws ApiException | [
"Print",
"out",
"the",
"Log",
"for",
"specific",
"Pods"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/examples/src/main/java/io/kubernetes/client/examples/ExpandedExample.java#L255-L270 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/KubeConfig.java | KubeConfig.loadKubeConfig | public static KubeConfig loadKubeConfig(Reader input) {
Yaml yaml = new Yaml(new SafeConstructor());
Object config = yaml.load(input);
Map<String, Object> configMap = (Map<String, Object>) config;
String currentContext = (String) configMap.get("current-context");
ArrayList<Object> contexts = (ArrayList<Object>) configMap.get("contexts");
ArrayList<Object> clusters = (ArrayList<Object>) configMap.get("clusters");
ArrayList<Object> users = (ArrayList<Object>) configMap.get("users");
Object preferences = configMap.get("preferences");
KubeConfig kubeConfig = new KubeConfig(contexts, clusters, users);
kubeConfig.setContext(currentContext);
kubeConfig.setPreferences(preferences);
return kubeConfig;
} | java | public static KubeConfig loadKubeConfig(Reader input) {
Yaml yaml = new Yaml(new SafeConstructor());
Object config = yaml.load(input);
Map<String, Object> configMap = (Map<String, Object>) config;
String currentContext = (String) configMap.get("current-context");
ArrayList<Object> contexts = (ArrayList<Object>) configMap.get("contexts");
ArrayList<Object> clusters = (ArrayList<Object>) configMap.get("clusters");
ArrayList<Object> users = (ArrayList<Object>) configMap.get("users");
Object preferences = configMap.get("preferences");
KubeConfig kubeConfig = new KubeConfig(contexts, clusters, users);
kubeConfig.setContext(currentContext);
kubeConfig.setPreferences(preferences);
return kubeConfig;
} | [
"public",
"static",
"KubeConfig",
"loadKubeConfig",
"(",
"Reader",
"input",
")",
"{",
"Yaml",
"yaml",
"=",
"new",
"Yaml",
"(",
"new",
"SafeConstructor",
"(",
")",
")",
";",
"Object",
"config",
"=",
"yaml",
".",
"load",
"(",
"input",
")",
";",
"Map",
"<... | Load a Kubernetes config from a Reader | [
"Load",
"a",
"Kubernetes",
"config",
"from",
"a",
"Reader"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/KubeConfig.java#L80-L96 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/KubeConfig.java | KubeConfig.tokenViaExecCredential | @SuppressWarnings("unchecked")
private String tokenViaExecCredential(Map<String, Object> execMap) {
if (execMap == null) {
return null;
}
String apiVersion = (String) execMap.get("apiVersion");
if (!"client.authentication.k8s.io/v1beta1".equals(apiVersion)
&& !"client.authentication.k8s.io/v1alpha1".equals(apiVersion)) {
log.error("Unrecognized user.exec.apiVersion: {}", apiVersion);
return null;
}
String command = (String) execMap.get("command");
JsonElement root = runExec(command, (List) execMap.get("args"), (List) execMap.get("env"));
if (root == null) {
return null;
}
if (!"ExecCredential".equals(root.getAsJsonObject().get("kind").getAsString())) {
log.error("Unrecognized kind in response");
return null;
}
if (!apiVersion.equals(root.getAsJsonObject().get("apiVersion").getAsString())) {
log.error("Mismatched apiVersion in response");
return null;
}
JsonObject status = root.getAsJsonObject().get("status").getAsJsonObject();
JsonElement token = status.get("token");
if (token == null) {
// TODO handle clientCertificateData/clientKeyData
// (KubeconfigAuthentication is not yet set up for that to be dynamic)
log.warn("No token produced by {}", command);
return null;
}
log.debug("Obtained a token from {}", command);
return token.getAsString();
// TODO cache tokens between calls, up to .status.expirationTimestamp
// TODO a 401 is supposed to force a refresh,
// but KubeconfigAuthentication hardcodes AccessTokenAuthentication which does not support that
// and anyway ClientBuilder only calls Authenticator.provide once per ApiClient;
// we would need to do it on every request
} | java | @SuppressWarnings("unchecked")
private String tokenViaExecCredential(Map<String, Object> execMap) {
if (execMap == null) {
return null;
}
String apiVersion = (String) execMap.get("apiVersion");
if (!"client.authentication.k8s.io/v1beta1".equals(apiVersion)
&& !"client.authentication.k8s.io/v1alpha1".equals(apiVersion)) {
log.error("Unrecognized user.exec.apiVersion: {}", apiVersion);
return null;
}
String command = (String) execMap.get("command");
JsonElement root = runExec(command, (List) execMap.get("args"), (List) execMap.get("env"));
if (root == null) {
return null;
}
if (!"ExecCredential".equals(root.getAsJsonObject().get("kind").getAsString())) {
log.error("Unrecognized kind in response");
return null;
}
if (!apiVersion.equals(root.getAsJsonObject().get("apiVersion").getAsString())) {
log.error("Mismatched apiVersion in response");
return null;
}
JsonObject status = root.getAsJsonObject().get("status").getAsJsonObject();
JsonElement token = status.get("token");
if (token == null) {
// TODO handle clientCertificateData/clientKeyData
// (KubeconfigAuthentication is not yet set up for that to be dynamic)
log.warn("No token produced by {}", command);
return null;
}
log.debug("Obtained a token from {}", command);
return token.getAsString();
// TODO cache tokens between calls, up to .status.expirationTimestamp
// TODO a 401 is supposed to force a refresh,
// but KubeconfigAuthentication hardcodes AccessTokenAuthentication which does not support that
// and anyway ClientBuilder only calls Authenticator.provide once per ApiClient;
// we would need to do it on every request
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"String",
"tokenViaExecCredential",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"execMap",
")",
"{",
"if",
"(",
"execMap",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"String",
"apiV... | Attempt to create an access token by running a configured external program.
@see <a
href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/#client-go-credential-plugins">
Authenticating » client-go credential plugins</a> | [
"Attempt",
"to",
"create",
"an",
"access",
"token",
"by",
"running",
"a",
"configured",
"external",
"program",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/KubeConfig.java#L255-L294 | train |
kubernetes-client/java | extended/src/main/java/io/kubernetes/client/extended/pager/Pager.java | Pager.getNextCall | private Call getNextCall(Integer nextLimit, String continueToken) {
PagerParams params = new PagerParams((nextLimit != null) ? nextLimit : limit, continueToken);
return listFunc.apply(params);
} | java | private Call getNextCall(Integer nextLimit, String continueToken) {
PagerParams params = new PagerParams((nextLimit != null) ? nextLimit : limit, continueToken);
return listFunc.apply(params);
} | [
"private",
"Call",
"getNextCall",
"(",
"Integer",
"nextLimit",
",",
"String",
"continueToken",
")",
"{",
"PagerParams",
"params",
"=",
"new",
"PagerParams",
"(",
"(",
"nextLimit",
"!=",
"null",
")",
"?",
"nextLimit",
":",
"limit",
",",
"continueToken",
")",
... | returns next list call by setting continue variable and limit | [
"returns",
"next",
"list",
"call",
"by",
"setting",
"continue",
"variable",
"and",
"limit"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/extended/src/main/java/io/kubernetes/client/extended/pager/Pager.java#L65-L68 | train |
kubernetes-client/java | extended/src/main/java/io/kubernetes/client/extended/pager/Pager.java | Pager.executeRequest | private ApiListType executeRequest(Call call) throws IOException, ApiException {
return client.handleResponse(call.execute(), listType);
} | java | private ApiListType executeRequest(Call call) throws IOException, ApiException {
return client.handleResponse(call.execute(), listType);
} | [
"private",
"ApiListType",
"executeRequest",
"(",
"Call",
"call",
")",
"throws",
"IOException",
",",
"ApiException",
"{",
"return",
"client",
".",
"handleResponse",
"(",
"call",
".",
"execute",
"(",
")",
",",
"listType",
")",
";",
"}"
] | executes the list call and sets the continue variable for next list call | [
"executes",
"the",
"list",
"call",
"and",
"sets",
"the",
"continue",
"variable",
"for",
"next",
"list",
"call"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/extended/src/main/java/io/kubernetes/client/extended/pager/Pager.java#L71-L73 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/PortForward.java | PortForward.forward | public PortForwardResult forward(V1Pod pod, List<Integer> ports)
throws ApiException, IOException {
return forward(pod.getMetadata().getNamespace(), pod.getMetadata().getName(), ports);
} | java | public PortForwardResult forward(V1Pod pod, List<Integer> ports)
throws ApiException, IOException {
return forward(pod.getMetadata().getNamespace(), pod.getMetadata().getName(), ports);
} | [
"public",
"PortForwardResult",
"forward",
"(",
"V1Pod",
"pod",
",",
"List",
"<",
"Integer",
">",
"ports",
")",
"throws",
"ApiException",
",",
"IOException",
"{",
"return",
"forward",
"(",
"pod",
".",
"getMetadata",
"(",
")",
".",
"getNamespace",
"(",
")",
... | PortForward to a container
@param pod The pod where the port forward is run.
@param ports The ports to forward
@return The result of the Port Forward request. | [
"PortForward",
"to",
"a",
"container"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/PortForward.java#L90-L93 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/PortForward.java | PortForward.forward | public PortForwardResult forward(String namespace, String name, List<Integer> ports)
throws ApiException, IOException {
String path = makePath(namespace, name);
WebSocketStreamHandler handler = new WebSocketStreamHandler();
PortForwardResult result = new PortForwardResult(handler, ports);
List<Pair> queryParams = new ArrayList<>();
for (Integer port : ports) {
queryParams.add(new Pair("ports", port.toString()));
}
WebSockets.stream(path, "GET", queryParams, apiClient, handler);
// Wait for streams to start.
result.init();
return result;
} | java | public PortForwardResult forward(String namespace, String name, List<Integer> ports)
throws ApiException, IOException {
String path = makePath(namespace, name);
WebSocketStreamHandler handler = new WebSocketStreamHandler();
PortForwardResult result = new PortForwardResult(handler, ports);
List<Pair> queryParams = new ArrayList<>();
for (Integer port : ports) {
queryParams.add(new Pair("ports", port.toString()));
}
WebSockets.stream(path, "GET", queryParams, apiClient, handler);
// Wait for streams to start.
result.init();
return result;
} | [
"public",
"PortForwardResult",
"forward",
"(",
"String",
"namespace",
",",
"String",
"name",
",",
"List",
"<",
"Integer",
">",
"ports",
")",
"throws",
"ApiException",
",",
"IOException",
"{",
"String",
"path",
"=",
"makePath",
"(",
"namespace",
",",
"name",
... | PortForward to a container.
@param namespace The namespace of the Pod
@param name The name of the Pod
@param ports The ports to forward
@return The result of the Port Forward request. | [
"PortForward",
"to",
"a",
"container",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/PortForward.java#L103-L118 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.add | @Override
public void add(ApiType obj) {
String key = keyFunc.apply(obj);
lock.lock();
try {
ApiType oldObj = this.items.get(key);
this.items.put(key, obj);
this.updateIndices(oldObj, obj, key);
} finally {
lock.unlock();
}
} | java | @Override
public void add(ApiType obj) {
String key = keyFunc.apply(obj);
lock.lock();
try {
ApiType oldObj = this.items.get(key);
this.items.put(key, obj);
this.updateIndices(oldObj, obj, key);
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"void",
"add",
"(",
"ApiType",
"obj",
")",
"{",
"String",
"key",
"=",
"keyFunc",
".",
"apply",
"(",
"obj",
")",
";",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"ApiType",
"oldObj",
"=",
"this",
".",
"items",
".",
"... | Add objects.
@param obj the obj | [
"Add",
"objects",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L67-L78 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.delete | @Override
public void delete(ApiType obj) {
String key = keyFunc.apply(obj);
lock.lock();
try {
boolean exists = this.items.containsKey(key);
if (exists) {
this.deleteFromIndices(this.items.get(key), key);
this.items.remove(key);
}
} finally {
lock.unlock();
}
} | java | @Override
public void delete(ApiType obj) {
String key = keyFunc.apply(obj);
lock.lock();
try {
boolean exists = this.items.containsKey(key);
if (exists) {
this.deleteFromIndices(this.items.get(key), key);
this.items.remove(key);
}
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"void",
"delete",
"(",
"ApiType",
"obj",
")",
"{",
"String",
"key",
"=",
"keyFunc",
".",
"apply",
"(",
"obj",
")",
";",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"boolean",
"exists",
"=",
"this",
".",
"items",
".",
... | Delete the object.
@param obj the obj | [
"Delete",
"the",
"object",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L103-L116 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.replace | @Override
public void replace(List<ApiType> list, String resourceVersion) {
lock.lock();
try {
Map<String, ApiType> newItems = new HashMap<>();
for (ApiType item : list) {
String key = keyFunc.apply(item);
newItems.put(key, item);
}
this.items = newItems;
// rebuild any index
this.indices = new HashMap<>();
for (Map.Entry<String, ApiType> itemEntry : items.entrySet()) {
this.updateIndices(null, itemEntry.getValue(), itemEntry.getKey());
}
} finally {
lock.unlock();
}
} | java | @Override
public void replace(List<ApiType> list, String resourceVersion) {
lock.lock();
try {
Map<String, ApiType> newItems = new HashMap<>();
for (ApiType item : list) {
String key = keyFunc.apply(item);
newItems.put(key, item);
}
this.items = newItems;
// rebuild any index
this.indices = new HashMap<>();
for (Map.Entry<String, ApiType> itemEntry : items.entrySet()) {
this.updateIndices(null, itemEntry.getValue(), itemEntry.getKey());
}
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"void",
"replace",
"(",
"List",
"<",
"ApiType",
">",
"list",
",",
"String",
"resourceVersion",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"Map",
"<",
"String",
",",
"ApiType",
">",
"newItems",
"=",
"new",
"Ha... | Replace the content in the cache completely.
@param list the list
@param resourceVersion the resource version | [
"Replace",
"the",
"content",
"in",
"the",
"cache",
"completely",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L124-L143 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.listKeys | @Override
public List<String> listKeys() {
lock.lock();
try {
List<String> keys = new ArrayList<>(this.items.size());
for (Map.Entry<String, ApiType> entry : this.items.entrySet()) {
keys.add(entry.getKey());
}
return keys;
} finally {
lock.unlock();
}
} | java | @Override
public List<String> listKeys() {
lock.lock();
try {
List<String> keys = new ArrayList<>(this.items.size());
for (Map.Entry<String, ApiType> entry : this.items.entrySet()) {
keys.add(entry.getKey());
}
return keys;
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"List",
"<",
"String",
">",
"listKeys",
"(",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"List",
"<",
"String",
">",
"keys",
"=",
"new",
"ArrayList",
"<>",
"(",
"this",
".",
"items",
".",
"size",
"(",
")",... | List keys.
@return the list | [
"List",
"keys",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L156-L168 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.get | @Override
public ApiType get(ApiType obj) {
String key = this.keyFunc.apply(obj);
lock.lock();
try {
return this.getByKey(key);
} finally {
lock.unlock();
}
} | java | @Override
public ApiType get(ApiType obj) {
String key = this.keyFunc.apply(obj);
lock.lock();
try {
return this.getByKey(key);
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"ApiType",
"get",
"(",
"ApiType",
"obj",
")",
"{",
"String",
"key",
"=",
"this",
".",
"keyFunc",
".",
"apply",
"(",
"obj",
")",
";",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"return",
"this",
".",
"getByKey",
"(",
... | Get object t.
@param obj the obj
@return the t | [
"Get",
"object",
"t",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L176-L185 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.list | @Override
public List<ApiType> list() {
lock.lock();
try {
List<ApiType> itemList = new ArrayList<>(this.items.size());
for (Map.Entry<String, ApiType> entry : this.items.entrySet()) {
itemList.add(entry.getValue());
}
return itemList;
} finally {
lock.unlock();
}
} | java | @Override
public List<ApiType> list() {
lock.lock();
try {
List<ApiType> itemList = new ArrayList<>(this.items.size());
for (Map.Entry<String, ApiType> entry : this.items.entrySet()) {
itemList.add(entry.getValue());
}
return itemList;
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"List",
"<",
"ApiType",
">",
"list",
"(",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"List",
"<",
"ApiType",
">",
"itemList",
"=",
"new",
"ArrayList",
"<>",
"(",
"this",
".",
"items",
".",
"size",
"(",
")... | List all objects in the cache.
@return the list | [
"List",
"all",
"objects",
"in",
"the",
"cache",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L192-L204 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.index | @Override
public List<ApiType> index(String indexName, Object obj) {
lock.lock();
try {
if (!this.indexers.containsKey(indexName)) {
throw new IllegalArgumentException(String.format("index %s doesn't exist!", indexName));
}
Function<ApiType, List<String>> indexFunc = this.indexers.get(indexName);
List<String> indexKeys = indexFunc.apply((ApiType) obj);
Map<String, Set<String>> index = this.indices.get(indexName);
if (io.kubernetes.client.util.common.Collections.isEmptyMap(index)) {
return new ArrayList<>();
}
Set<String> returnKeySet = new HashSet<>();
for (String indexKey : indexKeys) {
Set<String> set = index.get(indexKey);
if (io.kubernetes.client.util.common.Collections.isEmptyCollection(set)) {
continue;
}
returnKeySet.addAll(set);
}
List<ApiType> items = new ArrayList<>(returnKeySet.size());
for (String absoluteKey : returnKeySet) {
items.add(this.items.get(absoluteKey));
}
return items;
} finally {
lock.unlock();
}
} | java | @Override
public List<ApiType> index(String indexName, Object obj) {
lock.lock();
try {
if (!this.indexers.containsKey(indexName)) {
throw new IllegalArgumentException(String.format("index %s doesn't exist!", indexName));
}
Function<ApiType, List<String>> indexFunc = this.indexers.get(indexName);
List<String> indexKeys = indexFunc.apply((ApiType) obj);
Map<String, Set<String>> index = this.indices.get(indexName);
if (io.kubernetes.client.util.common.Collections.isEmptyMap(index)) {
return new ArrayList<>();
}
Set<String> returnKeySet = new HashSet<>();
for (String indexKey : indexKeys) {
Set<String> set = index.get(indexKey);
if (io.kubernetes.client.util.common.Collections.isEmptyCollection(set)) {
continue;
}
returnKeySet.addAll(set);
}
List<ApiType> items = new ArrayList<>(returnKeySet.size());
for (String absoluteKey : returnKeySet) {
items.add(this.items.get(absoluteKey));
}
return items;
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"List",
"<",
"ApiType",
">",
"index",
"(",
"String",
"indexName",
",",
"Object",
"obj",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"!",
"this",
".",
"indexers",
".",
"containsKey",
"(",
"indexName"... | Get objects .
@param indexName the index name
@param obj the obj
@return the list | [
"Get",
"objects",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L229-L259 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.indexKeys | @Override
public List<String> indexKeys(String indexName, String indexKey) {
lock.lock();
try {
if (!this.indexers.containsKey(indexName)) {
throw new IllegalArgumentException(String.format("index %s doesn't exist!", indexName));
}
Map<String, Set<String>> index = this.indices.get(indexName);
Set<String> set = index.get(indexKey);
List<String> keys = new ArrayList<>(set.size());
for (String key : set) {
keys.add(key);
}
return keys;
} finally {
lock.unlock();
}
} | java | @Override
public List<String> indexKeys(String indexName, String indexKey) {
lock.lock();
try {
if (!this.indexers.containsKey(indexName)) {
throw new IllegalArgumentException(String.format("index %s doesn't exist!", indexName));
}
Map<String, Set<String>> index = this.indices.get(indexName);
Set<String> set = index.get(indexKey);
List<String> keys = new ArrayList<>(set.size());
for (String key : set) {
keys.add(key);
}
return keys;
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"List",
"<",
"String",
">",
"indexKeys",
"(",
"String",
"indexName",
",",
"String",
"indexKey",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"!",
"this",
".",
"indexers",
".",
"containsKey",
"(",
"in... | Index keys list.
@param indexName the index name
@param indexKey the index key
@return the list | [
"Index",
"keys",
"list",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L268-L285 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.byIndex | @Override
public List<ApiType> byIndex(String indexName, String indexKey) {
lock.lock();
try {
if (!this.indexers.containsKey(indexName)) {
throw new IllegalArgumentException(String.format("index %s doesn't exist!", indexName));
}
Map<String, Set<String>> index = this.indices.get(indexName);
Set<String> set = index.get(indexKey);
if (set == null) {
return Arrays.asList();
}
List<ApiType> items = new ArrayList<>(set.size());
for (String key : set) {
items.add(this.items.get(key));
}
return items;
} finally {
lock.unlock();
}
} | java | @Override
public List<ApiType> byIndex(String indexName, String indexKey) {
lock.lock();
try {
if (!this.indexers.containsKey(indexName)) {
throw new IllegalArgumentException(String.format("index %s doesn't exist!", indexName));
}
Map<String, Set<String>> index = this.indices.get(indexName);
Set<String> set = index.get(indexKey);
if (set == null) {
return Arrays.asList();
}
List<ApiType> items = new ArrayList<>(set.size());
for (String key : set) {
items.add(this.items.get(key));
}
return items;
} finally {
lock.unlock();
}
} | [
"@",
"Override",
"public",
"List",
"<",
"ApiType",
">",
"byIndex",
"(",
"String",
"indexName",
",",
"String",
"indexKey",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"!",
"this",
".",
"indexers",
".",
"containsKey",
"(",
"ind... | By index list.
@param indexName the index name
@param indexKey the index key
@return the list | [
"By",
"index",
"list",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L294-L314 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.updateIndices | public void updateIndices(ApiType oldObj, ApiType newObj, String key) {
// if we got an old object, we need to remove it before we can add
// it again.
if (oldObj != null) {
deleteFromIndices(oldObj, key);
}
for (Map.Entry<String, Function<ApiType, List<String>>> indexEntry : indexers.entrySet()) {
String indexName = indexEntry.getKey();
Function<ApiType, List<String>> indexFunc = indexEntry.getValue();
List<String> indexValues = indexFunc.apply(newObj);
if (io.kubernetes.client.util.common.Collections.isEmptyCollection(indexValues)) {
continue;
}
Map<String, Set<String>> index =
this.indices.computeIfAbsent(indexName, k -> new HashMap<>());
for (String indexValue : indexValues) {
Set<String> indexSet = index.computeIfAbsent(indexValue, k -> new HashSet<>());
indexSet.add(key);
}
}
} | java | public void updateIndices(ApiType oldObj, ApiType newObj, String key) {
// if we got an old object, we need to remove it before we can add
// it again.
if (oldObj != null) {
deleteFromIndices(oldObj, key);
}
for (Map.Entry<String, Function<ApiType, List<String>>> indexEntry : indexers.entrySet()) {
String indexName = indexEntry.getKey();
Function<ApiType, List<String>> indexFunc = indexEntry.getValue();
List<String> indexValues = indexFunc.apply(newObj);
if (io.kubernetes.client.util.common.Collections.isEmptyCollection(indexValues)) {
continue;
}
Map<String, Set<String>> index =
this.indices.computeIfAbsent(indexName, k -> new HashMap<>());
for (String indexValue : indexValues) {
Set<String> indexSet = index.computeIfAbsent(indexValue, k -> new HashSet<>());
indexSet.add(key);
}
}
} | [
"public",
"void",
"updateIndices",
"(",
"ApiType",
"oldObj",
",",
"ApiType",
"newObj",
",",
"String",
"key",
")",
"{",
"// if we got an old object, we need to remove it before we can add",
"// it again.",
"if",
"(",
"oldObj",
"!=",
"null",
")",
"{",
"deleteFromIndices",... | updateIndices modifies the objects location in the managed indexes, if this is an update, you
must provide an oldObj.
<p>Note: updateIndices must be called from a function that already has a lock on the cache.
@param oldObj the old obj
@param newObj the new obj
@param key the key | [
"updateIndices",
"modifies",
"the",
"objects",
"location",
"in",
"the",
"managed",
"indexes",
"if",
"this",
"is",
"an",
"update",
"you",
"must",
"provide",
"an",
"oldObj",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L326-L347 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.deleteFromIndices | private void deleteFromIndices(ApiType oldObj, String key) {
for (Map.Entry<String, Function<ApiType, List<String>>> indexEntry : this.indexers.entrySet()) {
Function<ApiType, List<String>> indexFunc = indexEntry.getValue();
List<String> indexValues = indexFunc.apply(oldObj);
if (io.kubernetes.client.util.common.Collections.isEmptyCollection(indexValues)) {
continue;
}
Map<String, Set<String>> index = this.indices.get(indexEntry.getKey());
if (index == null) {
continue;
}
for (String indexValue : indexValues) {
Set<String> indexSet = index.get(indexValue);
if (indexSet != null) {
indexSet.remove(key);
}
}
}
} | java | private void deleteFromIndices(ApiType oldObj, String key) {
for (Map.Entry<String, Function<ApiType, List<String>>> indexEntry : this.indexers.entrySet()) {
Function<ApiType, List<String>> indexFunc = indexEntry.getValue();
List<String> indexValues = indexFunc.apply(oldObj);
if (io.kubernetes.client.util.common.Collections.isEmptyCollection(indexValues)) {
continue;
}
Map<String, Set<String>> index = this.indices.get(indexEntry.getKey());
if (index == null) {
continue;
}
for (String indexValue : indexValues) {
Set<String> indexSet = index.get(indexValue);
if (indexSet != null) {
indexSet.remove(key);
}
}
}
} | [
"private",
"void",
"deleteFromIndices",
"(",
"ApiType",
"oldObj",
",",
"String",
"key",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Function",
"<",
"ApiType",
",",
"List",
"<",
"String",
">",
">",
">",
"indexEntry",
":",
"this",
"."... | deleteFromIndices removes the object from each of the managed indexes.
<p>Note: It is intended to be called from a function that already has a lock on the cache.
@param oldObj the old obj
@param key the key | [
"deleteFromIndices",
"removes",
"the",
"object",
"from",
"each",
"of",
"the",
"managed",
"indexes",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L357-L376 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.deletionHandlingMetaNamespaceKeyFunc | public static <ApiType> String deletionHandlingMetaNamespaceKeyFunc(ApiType object) {
if (object instanceof DeltaFIFO.DeletedFinalStateUnknown) {
DeltaFIFO.DeletedFinalStateUnknown deleteObj = (DeltaFIFO.DeletedFinalStateUnknown) object;
return deleteObj.getKey();
}
return metaNamespaceKeyFunc(object);
} | java | public static <ApiType> String deletionHandlingMetaNamespaceKeyFunc(ApiType object) {
if (object instanceof DeltaFIFO.DeletedFinalStateUnknown) {
DeltaFIFO.DeletedFinalStateUnknown deleteObj = (DeltaFIFO.DeletedFinalStateUnknown) object;
return deleteObj.getKey();
}
return metaNamespaceKeyFunc(object);
} | [
"public",
"static",
"<",
"ApiType",
">",
"String",
"deletionHandlingMetaNamespaceKeyFunc",
"(",
"ApiType",
"object",
")",
"{",
"if",
"(",
"object",
"instanceof",
"DeltaFIFO",
".",
"DeletedFinalStateUnknown",
")",
"{",
"DeltaFIFO",
".",
"DeletedFinalStateUnknown",
"del... | deletionHandlingMetaNamespaceKeyFunc checks for DeletedFinalStateUnknown objects before calling
metaNamespaceKeyFunc.
@param object specific object
@return the key | [
"deletionHandlingMetaNamespaceKeyFunc",
"checks",
"for",
"DeletedFinalStateUnknown",
"objects",
"before",
"calling",
"metaNamespaceKeyFunc",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L385-L391 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/cache/Cache.java | Cache.metaNamespaceIndexFunc | public static List<String> metaNamespaceIndexFunc(Object obj) {
try {
V1ObjectMeta metadata = Reflect.objectMetadata(obj);
if (metadata == null) {
return Collections.emptyList();
}
return Collections.singletonList(metadata.getNamespace());
} catch (ObjectMetaReflectException e) {
// NOTE(yue9944882): might want to handle this as a checked exception
throw new RuntimeException(e);
}
} | java | public static List<String> metaNamespaceIndexFunc(Object obj) {
try {
V1ObjectMeta metadata = Reflect.objectMetadata(obj);
if (metadata == null) {
return Collections.emptyList();
}
return Collections.singletonList(metadata.getNamespace());
} catch (ObjectMetaReflectException e) {
// NOTE(yue9944882): might want to handle this as a checked exception
throw new RuntimeException(e);
}
} | [
"public",
"static",
"List",
"<",
"String",
">",
"metaNamespaceIndexFunc",
"(",
"Object",
"obj",
")",
"{",
"try",
"{",
"V1ObjectMeta",
"metadata",
"=",
"Reflect",
".",
"objectMetadata",
"(",
"obj",
")",
";",
"if",
"(",
"metadata",
"==",
"null",
")",
"{",
... | metaNamespaceIndexFunc is a default index function that indexes based on an object's namespace.
@param obj specific object
@return the indexed value | [
"metaNamespaceIndexFunc",
"is",
"a",
"default",
"index",
"function",
"that",
"indexes",
"based",
"on",
"an",
"object",
"s",
"namespace",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/cache/Cache.java#L430-L441 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/ProtoClient.java | ProtoClient.list | public <T extends Message> ObjectOrStatus<T> list(T.Builder builder, String path)
throws ApiException, IOException {
return get(builder, path);
} | java | public <T extends Message> ObjectOrStatus<T> list(T.Builder builder, String path)
throws ApiException, IOException {
return get(builder, path);
} | [
"public",
"<",
"T",
"extends",
"Message",
">",
"ObjectOrStatus",
"<",
"T",
">",
"list",
"(",
"T",
".",
"Builder",
"builder",
",",
"String",
"path",
")",
"throws",
"ApiException",
",",
"IOException",
"{",
"return",
"get",
"(",
"builder",
",",
"path",
")",... | List is fluent, semantic sugar method on top of get, which is intended to convey that the
object is a List of objects rather than a single object
@param builder The appropriate Builder for the object received from the request.
@param path The URL path to call (e.g. /api/v1/namespaces/default/pods/pod-name)
@return An ObjectOrStatus which contains the Object requested, or a Status about the request. | [
"List",
"is",
"fluent",
"semantic",
"sugar",
"method",
"on",
"top",
"of",
"get",
"which",
"is",
"intended",
"to",
"convey",
"that",
"the",
"object",
"is",
"a",
"List",
"of",
"objects",
"rather",
"than",
"a",
"single",
"object"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/ProtoClient.java#L115-L118 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/ProtoClient.java | ProtoClient.create | public <T extends Message> ObjectOrStatus<T> create(
T obj, String path, String apiVersion, String kind) throws ApiException, IOException {
return request(obj.newBuilderForType(), path, "POST", obj, apiVersion, kind);
} | java | public <T extends Message> ObjectOrStatus<T> create(
T obj, String path, String apiVersion, String kind) throws ApiException, IOException {
return request(obj.newBuilderForType(), path, "POST", obj, apiVersion, kind);
} | [
"public",
"<",
"T",
"extends",
"Message",
">",
"ObjectOrStatus",
"<",
"T",
">",
"create",
"(",
"T",
"obj",
",",
"String",
"path",
",",
"String",
"apiVersion",
",",
"String",
"kind",
")",
"throws",
"ApiException",
",",
"IOException",
"{",
"return",
"request... | Create a Kubernetes API object using protocol buffer encoding. Performs a POST
@param obj The object to create
@param path The URL path to call
@param apiVersion The api version to use
@param kind The kind of the object
@return An ObjectOrStatus which contains the Object requested, or a Status about the request. | [
"Create",
"a",
"Kubernetes",
"API",
"object",
"using",
"protocol",
"buffer",
"encoding",
".",
"Performs",
"a",
"POST"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/ProtoClient.java#L129-L132 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/ProtoClient.java | ProtoClient.request | public <T extends Message> ObjectOrStatus<T> request(
T.Builder builder, String path, String method, T body, String apiVersion, String kind)
throws ApiException, IOException {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", MEDIA_TYPE);
headers.put("Accept", MEDIA_TYPE);
String[] localVarAuthNames = new String[] {"BearerToken"};
Request request =
apiClient.buildRequest(
path,
method,
new ArrayList<Pair>(),
new ArrayList<Pair>(),
null,
headers,
new HashMap<String, Object>(),
localVarAuthNames,
null);
if (body != null) {
byte[] bytes = encode(body, apiVersion, kind);
switch (method) {
case "POST":
request =
request
.newBuilder()
.post(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
case "PUT":
request =
request
.newBuilder()
.put(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
case "PATCH":
request =
request
.newBuilder()
.patch(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
default:
throw new ApiException("Unknown proto client API method: " + method);
}
}
Response resp = apiClient.getHttpClient().newCall(request).execute();
Unknown u = parse(resp.body().byteStream());
resp.body().close();
if (u.getTypeMeta().getApiVersion().equals("v1")
&& u.getTypeMeta().getKind().equals("Status")) {
Status status = Status.newBuilder().mergeFrom(u.getRaw()).build();
return new ObjectOrStatus(null, status);
}
return new ObjectOrStatus((T) builder.mergeFrom(u.getRaw()).build(), null);
} | java | public <T extends Message> ObjectOrStatus<T> request(
T.Builder builder, String path, String method, T body, String apiVersion, String kind)
throws ApiException, IOException {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", MEDIA_TYPE);
headers.put("Accept", MEDIA_TYPE);
String[] localVarAuthNames = new String[] {"BearerToken"};
Request request =
apiClient.buildRequest(
path,
method,
new ArrayList<Pair>(),
new ArrayList<Pair>(),
null,
headers,
new HashMap<String, Object>(),
localVarAuthNames,
null);
if (body != null) {
byte[] bytes = encode(body, apiVersion, kind);
switch (method) {
case "POST":
request =
request
.newBuilder()
.post(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
case "PUT":
request =
request
.newBuilder()
.put(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
case "PATCH":
request =
request
.newBuilder()
.patch(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
default:
throw new ApiException("Unknown proto client API method: " + method);
}
}
Response resp = apiClient.getHttpClient().newCall(request).execute();
Unknown u = parse(resp.body().byteStream());
resp.body().close();
if (u.getTypeMeta().getApiVersion().equals("v1")
&& u.getTypeMeta().getKind().equals("Status")) {
Status status = Status.newBuilder().mergeFrom(u.getRaw()).build();
return new ObjectOrStatus(null, status);
}
return new ObjectOrStatus((T) builder.mergeFrom(u.getRaw()).build(), null);
} | [
"public",
"<",
"T",
"extends",
"Message",
">",
"ObjectOrStatus",
"<",
"T",
">",
"request",
"(",
"T",
".",
"Builder",
"builder",
",",
"String",
"path",
",",
"String",
"method",
",",
"T",
"body",
",",
"String",
"apiVersion",
",",
"String",
"kind",
")",
"... | Generic protocol buffer based HTTP request. Not intended for general consumption, but public
for advance use cases.
@param builder The appropriate Builder for the object received from the request.
@param method The HTTP method (e.g. GET) for this request.
@param path The URL path to call (e.g. /api/v1/namespaces/default/pods/pod-name)
@param body The body to send with the request (optional)
@param apiVersion The 'apiVersion' to use when encoding, required if body is non-null, ignored
otherwise.
@param kind The 'kind' field to use when encoding, required if body is non-null, ignored
otherwise.
@return An ObjectOrStatus which contains the Object requested, or a Status about the request. | [
"Generic",
"protocol",
"buffer",
"based",
"HTTP",
"request",
".",
"Not",
"intended",
"for",
"general",
"consumption",
"but",
"public",
"for",
"advance",
"use",
"cases",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/ProtoClient.java#L234-L291 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/WebSockets.java | WebSockets.stream | public static void stream(String path, String method, ApiClient client, SocketListener listener)
throws ApiException, IOException {
stream(path, method, new ArrayList<Pair>(), client, listener);
} | java | public static void stream(String path, String method, ApiClient client, SocketListener listener)
throws ApiException, IOException {
stream(path, method, new ArrayList<Pair>(), client, listener);
} | [
"public",
"static",
"void",
"stream",
"(",
"String",
"path",
",",
"String",
"method",
",",
"ApiClient",
"client",
",",
"SocketListener",
"listener",
")",
"throws",
"ApiException",
",",
"IOException",
"{",
"stream",
"(",
"path",
",",
"method",
",",
"new",
"Ar... | Create a new WebSocket stream
@param path The HTTP Path to request from the API
@param method The HTTP method to use for the call
@param client The ApiClient for communicating with the API
@param listener The socket listener to handle socket events | [
"Create",
"a",
"new",
"WebSocket",
"stream"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/WebSockets.java#L77-L80 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/WebSocketStreamHandler.java | WebSocketStreamHandler.getInputStream | public synchronized InputStream getInputStream(int stream) {
if (state == State.CLOSED) throw new IllegalStateException();
if (!input.containsKey(stream)) {
try {
PipedInputStream pipeIn = new PipedInputStream();
PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
pipedOutput.put(stream, pipeOut);
input.put(stream, pipeIn);
} catch (IOException ex) {
// This is _very_ unlikely, as it requires the above constructor to fail.
// don't force callers to catch, but still throw
throw new IllegalStateException(ex);
}
}
return input.get(stream);
} | java | public synchronized InputStream getInputStream(int stream) {
if (state == State.CLOSED) throw new IllegalStateException();
if (!input.containsKey(stream)) {
try {
PipedInputStream pipeIn = new PipedInputStream();
PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
pipedOutput.put(stream, pipeOut);
input.put(stream, pipeIn);
} catch (IOException ex) {
// This is _very_ unlikely, as it requires the above constructor to fail.
// don't force callers to catch, but still throw
throw new IllegalStateException(ex);
}
}
return input.get(stream);
} | [
"public",
"synchronized",
"InputStream",
"getInputStream",
"(",
"int",
"stream",
")",
"{",
"if",
"(",
"state",
"==",
"State",
".",
"CLOSED",
")",
"throw",
"new",
"IllegalStateException",
"(",
")",
";",
"if",
"(",
"!",
"input",
".",
"containsKey",
"(",
"str... | Get a specific input stream using its identifier. Caller is responsible for closing these
streams.
@param stream The stream to return
@return The specified stream. | [
"Get",
"a",
"specific",
"input",
"stream",
"using",
"its",
"identifier",
".",
"Caller",
"is",
"responsible",
"for",
"closing",
"these",
"streams",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/WebSocketStreamHandler.java#L121-L137 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/WebSocketStreamHandler.java | WebSocketStreamHandler.getOutputStream | public synchronized OutputStream getOutputStream(int stream) {
if (!output.containsKey(stream)) {
output.put(stream, new WebSocketOutputStream(stream));
}
return output.get(stream);
} | java | public synchronized OutputStream getOutputStream(int stream) {
if (!output.containsKey(stream)) {
output.put(stream, new WebSocketOutputStream(stream));
}
return output.get(stream);
} | [
"public",
"synchronized",
"OutputStream",
"getOutputStream",
"(",
"int",
"stream",
")",
"{",
"if",
"(",
"!",
"output",
".",
"containsKey",
"(",
"stream",
")",
")",
"{",
"output",
".",
"put",
"(",
"stream",
",",
"new",
"WebSocketOutputStream",
"(",
"stream",
... | Gets a specific output stream using it's identified
@param stream The stream to return
@return The specified stream. | [
"Gets",
"a",
"specific",
"output",
"stream",
"using",
"it",
"s",
"identified"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/WebSocketStreamHandler.java#L145-L150 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/WebSocketStreamHandler.java | WebSocketStreamHandler.getSocketInputOutputStream | private synchronized OutputStream getSocketInputOutputStream(int stream) {
if (!pipedOutput.containsKey(stream)) {
try {
PipedInputStream pipeIn = new PipedInputStream();
PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
pipedOutput.put(stream, pipeOut);
input.put(stream, pipeIn);
} catch (IOException ex) {
// This is _very_ unlikely, as it requires the above constructor to fail.
// don't force callers to catch, but still throw
throw new IllegalStateException(ex);
}
}
return pipedOutput.get(stream);
} | java | private synchronized OutputStream getSocketInputOutputStream(int stream) {
if (!pipedOutput.containsKey(stream)) {
try {
PipedInputStream pipeIn = new PipedInputStream();
PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
pipedOutput.put(stream, pipeOut);
input.put(stream, pipeIn);
} catch (IOException ex) {
// This is _very_ unlikely, as it requires the above constructor to fail.
// don't force callers to catch, but still throw
throw new IllegalStateException(ex);
}
}
return pipedOutput.get(stream);
} | [
"private",
"synchronized",
"OutputStream",
"getSocketInputOutputStream",
"(",
"int",
"stream",
")",
"{",
"if",
"(",
"!",
"pipedOutput",
".",
"containsKey",
"(",
"stream",
")",
")",
"{",
"try",
"{",
"PipedInputStream",
"pipeIn",
"=",
"new",
"PipedInputStream",
"(... | Get the pipe to write data to a specific InputStream. This is called when new data is read from
the web socket, to send the data on to the right stream.
@param stream The stream to return
@return The specified stream. | [
"Get",
"the",
"pipe",
"to",
"write",
"data",
"to",
"a",
"specific",
"InputStream",
".",
"This",
"is",
"called",
"when",
"new",
"data",
"is",
"read",
"from",
"the",
"web",
"socket",
"to",
"send",
"the",
"data",
"on",
"to",
"the",
"right",
"stream",
"."
... | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/WebSocketStreamHandler.java#L159-L173 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/impl/DefaultSharedIndexInformer.java | DefaultSharedIndexInformer.addEventHandlerWithResyncPeriod | @Override
public void addEventHandlerWithResyncPeriod(
ResourceEventHandler<ApiType> handler, long resyncPeriodMillis) {
if (stopped) {
log.info(
"DefaultSharedIndexInformer#Handler was not added to shared informer because it has stopped already");
return;
}
if (resyncPeriodMillis > 0) {
if (resyncPeriodMillis < MINIMUM_RESYNC_PERIOD_MILLIS) {
log.warn(
"DefaultSharedIndexInformer#resyncPeriod {} is too small. Changing it to the minimum allowed rule of {}",
resyncPeriodMillis,
MINIMUM_RESYNC_PERIOD_MILLIS);
resyncPeriodMillis = MINIMUM_RESYNC_PERIOD_MILLIS;
}
if (resyncPeriodMillis < this.resyncCheckPeriodMillis) {
if (started) {
log.warn(
"DefaultSharedIndexInformer#resyncPeriod {} is smaller than resyncCheckPeriod {} and the informer has already started. Changing it to {}",
resyncPeriodMillis,
resyncCheckPeriodMillis);
resyncPeriodMillis = resyncCheckPeriodMillis;
} else {
// if the event handler's resyncPeriod is smaller than the current resyncCheckPeriod,
// update resyncCheckPeriod to match resyncPeriod and adjust the resync periods of all
// the listeners accordingly
this.resyncCheckPeriodMillis = resyncPeriodMillis;
}
}
}
ProcessorListener<ApiType> listener =
new ProcessorListener(
handler, determineResyncPeriod(resyncCheckPeriodMillis, this.resyncCheckPeriodMillis));
if (!started) {
this.processor.addListener(listener);
return;
}
this.processor.addAndStartListener(listener);
List<ApiType> objectList = this.indexer.list();
for (Object item : objectList) {
listener.add(new ProcessorListener.AddNotification(item));
}
} | java | @Override
public void addEventHandlerWithResyncPeriod(
ResourceEventHandler<ApiType> handler, long resyncPeriodMillis) {
if (stopped) {
log.info(
"DefaultSharedIndexInformer#Handler was not added to shared informer because it has stopped already");
return;
}
if (resyncPeriodMillis > 0) {
if (resyncPeriodMillis < MINIMUM_RESYNC_PERIOD_MILLIS) {
log.warn(
"DefaultSharedIndexInformer#resyncPeriod {} is too small. Changing it to the minimum allowed rule of {}",
resyncPeriodMillis,
MINIMUM_RESYNC_PERIOD_MILLIS);
resyncPeriodMillis = MINIMUM_RESYNC_PERIOD_MILLIS;
}
if (resyncPeriodMillis < this.resyncCheckPeriodMillis) {
if (started) {
log.warn(
"DefaultSharedIndexInformer#resyncPeriod {} is smaller than resyncCheckPeriod {} and the informer has already started. Changing it to {}",
resyncPeriodMillis,
resyncCheckPeriodMillis);
resyncPeriodMillis = resyncCheckPeriodMillis;
} else {
// if the event handler's resyncPeriod is smaller than the current resyncCheckPeriod,
// update resyncCheckPeriod to match resyncPeriod and adjust the resync periods of all
// the listeners accordingly
this.resyncCheckPeriodMillis = resyncPeriodMillis;
}
}
}
ProcessorListener<ApiType> listener =
new ProcessorListener(
handler, determineResyncPeriod(resyncCheckPeriodMillis, this.resyncCheckPeriodMillis));
if (!started) {
this.processor.addListener(listener);
return;
}
this.processor.addAndStartListener(listener);
List<ApiType> objectList = this.indexer.list();
for (Object item : objectList) {
listener.add(new ProcessorListener.AddNotification(item));
}
} | [
"@",
"Override",
"public",
"void",
"addEventHandlerWithResyncPeriod",
"(",
"ResourceEventHandler",
"<",
"ApiType",
">",
"handler",
",",
"long",
"resyncPeriodMillis",
")",
"{",
"if",
"(",
"stopped",
")",
"{",
"log",
".",
"info",
"(",
"\"DefaultSharedIndexInformer#Han... | add event callback with a resync period | [
"add",
"event",
"callback",
"with",
"a",
"resync",
"period"
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/impl/DefaultSharedIndexInformer.java#L70-L117 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/impl/DefaultSharedIndexInformer.java | DefaultSharedIndexInformer.handleDeltas | private void handleDeltas(Deque<MutablePair<DeltaFIFO.DeltaType, Object>> deltas) {
if (Collections.isEmptyCollection(deltas)) {
return;
}
// from oldest to newest
for (MutablePair<DeltaFIFO.DeltaType, Object> delta : deltas) {
DeltaFIFO.DeltaType deltaType = delta.getLeft();
switch (deltaType) {
case Sync:
case Added:
case Updated:
boolean isSync = deltaType == DeltaFIFO.DeltaType.Sync;
Object oldObj = this.indexer.get((ApiType) delta.getRight());
if (oldObj != null) {
this.indexer.update((ApiType) delta.getRight());
this.processor.distribute(
new ProcessorListener.UpdateNotification(oldObj, delta.getRight()), isSync);
} else {
this.indexer.add((ApiType) delta.getRight());
this.processor.distribute(
new ProcessorListener.AddNotification(delta.getRight()), isSync);
}
break;
case Deleted:
this.indexer.delete((ApiType) delta.getRight());
this.processor.distribute(
new ProcessorListener.DeleteNotification(delta.getRight()), false);
break;
}
}
} | java | private void handleDeltas(Deque<MutablePair<DeltaFIFO.DeltaType, Object>> deltas) {
if (Collections.isEmptyCollection(deltas)) {
return;
}
// from oldest to newest
for (MutablePair<DeltaFIFO.DeltaType, Object> delta : deltas) {
DeltaFIFO.DeltaType deltaType = delta.getLeft();
switch (deltaType) {
case Sync:
case Added:
case Updated:
boolean isSync = deltaType == DeltaFIFO.DeltaType.Sync;
Object oldObj = this.indexer.get((ApiType) delta.getRight());
if (oldObj != null) {
this.indexer.update((ApiType) delta.getRight());
this.processor.distribute(
new ProcessorListener.UpdateNotification(oldObj, delta.getRight()), isSync);
} else {
this.indexer.add((ApiType) delta.getRight());
this.processor.distribute(
new ProcessorListener.AddNotification(delta.getRight()), isSync);
}
break;
case Deleted:
this.indexer.delete((ApiType) delta.getRight());
this.processor.distribute(
new ProcessorListener.DeleteNotification(delta.getRight()), false);
break;
}
}
} | [
"private",
"void",
"handleDeltas",
"(",
"Deque",
"<",
"MutablePair",
"<",
"DeltaFIFO",
".",
"DeltaType",
",",
"Object",
">",
">",
"deltas",
")",
"{",
"if",
"(",
"Collections",
".",
"isEmptyCollection",
"(",
"deltas",
")",
")",
"{",
"return",
";",
"}",
"/... | handleDeltas handles deltas and call processor distribute.
@param deltas deltas | [
"handleDeltas",
"handles",
"deltas",
"and",
"call",
"processor",
"distribute",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/impl/DefaultSharedIndexInformer.java#L167-L198 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/Yaml.java | Yaml.loadAs | public static <T> T loadAs(String content, Class<T> clazz) {
return getSnakeYaml().loadAs(new StringReader(content), clazz);
} | java | public static <T> T loadAs(String content, Class<T> clazz) {
return getSnakeYaml().loadAs(new StringReader(content), clazz);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"loadAs",
"(",
"String",
"content",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"return",
"getSnakeYaml",
"(",
")",
".",
"loadAs",
"(",
"new",
"StringReader",
"(",
"content",
")",
",",
"clazz",
")",
";",
... | Load an API object from a YAML string representation. Returns a concrete typed object using the
type specified.
@param content The YAML content
@param clazz The class of object to return.
@return An instantiation of the object.
@throws IOException If an error occurs while reading the YAML. | [
"Load",
"an",
"API",
"object",
"from",
"a",
"YAML",
"string",
"representation",
".",
"Returns",
"a",
"concrete",
"typed",
"object",
"using",
"the",
"type",
"specified",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/Yaml.java#L196-L198 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/Yaml.java | Yaml.loadAs | public static <T> T loadAs(File f, Class<T> clazz) throws IOException {
return getSnakeYaml().loadAs(new FileReader(f), clazz);
} | java | public static <T> T loadAs(File f, Class<T> clazz) throws IOException {
return getSnakeYaml().loadAs(new FileReader(f), clazz);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"loadAs",
"(",
"File",
"f",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"throws",
"IOException",
"{",
"return",
"getSnakeYaml",
"(",
")",
".",
"loadAs",
"(",
"new",
"FileReader",
"(",
"f",
")",
",",
"clazz",
"... | Load an API object from a YAML file. Returns a concrete typed object using the type specified.
@param f The YAML file
@param clazz The class of object to return.
@return An instantiation of the object.
@throws IOException If an error occurs while reading the YAML. | [
"Load",
"an",
"API",
"object",
"from",
"a",
"YAML",
"file",
".",
"Returns",
"a",
"concrete",
"typed",
"object",
"using",
"the",
"type",
"specified",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/Yaml.java#L208-L210 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/Yaml.java | Yaml.loadAs | public static <T> T loadAs(Reader reader, Class<T> clazz) {
return getSnakeYaml().loadAs(reader, clazz);
} | java | public static <T> T loadAs(Reader reader, Class<T> clazz) {
return getSnakeYaml().loadAs(reader, clazz);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"loadAs",
"(",
"Reader",
"reader",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"{",
"return",
"getSnakeYaml",
"(",
")",
".",
"loadAs",
"(",
"reader",
",",
"clazz",
")",
";",
"}"
] | Load an API object from a YAML stream. Returns a concrete typed object using the type
specified.
@param reader The YAML stream
@param clazz The class of object to return.
@return An instantiation of the object.
@throws IOException If an error occurs while reading the YAML. | [
"Load",
"an",
"API",
"object",
"from",
"a",
"YAML",
"stream",
".",
"Returns",
"a",
"concrete",
"typed",
"object",
"using",
"the",
"type",
"specified",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/Yaml.java#L221-L223 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/util/Yaml.java | Yaml.dumpAll | public static void dumpAll(Iterator<? extends Object> data, Writer output) {
getSnakeYaml().dumpAll(data, output);
} | java | public static void dumpAll(Iterator<? extends Object> data, Writer output) {
getSnakeYaml().dumpAll(data, output);
} | [
"public",
"static",
"void",
"dumpAll",
"(",
"Iterator",
"<",
"?",
"extends",
"Object",
">",
"data",
",",
"Writer",
"output",
")",
"{",
"getSnakeYaml",
"(",
")",
".",
"dumpAll",
"(",
"data",
",",
"output",
")",
";",
"}"
] | Takes an Iterator of YAML API objects and writes a YAML String representing all of them.
@param data The list of YAML API objects.
@param output The writer to output the YAML String to. | [
"Takes",
"an",
"Iterator",
"of",
"YAML",
"API",
"objects",
"and",
"writes",
"a",
"YAML",
"String",
"representing",
"all",
"of",
"them",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/util/Yaml.java#L316-L318 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/SharedInformerFactory.java | SharedInformerFactory.sharedIndexInformerFor | public synchronized <ApiType, ApiListType> SharedIndexInformer<ApiType> sharedIndexInformerFor(
Function<CallGeneratorParams, Call> callGenerator,
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass) {
return sharedIndexInformerFor(callGenerator, apiTypeClass, apiListTypeClass, 0);
} | java | public synchronized <ApiType, ApiListType> SharedIndexInformer<ApiType> sharedIndexInformerFor(
Function<CallGeneratorParams, Call> callGenerator,
Class<ApiType> apiTypeClass,
Class<ApiListType> apiListTypeClass) {
return sharedIndexInformerFor(callGenerator, apiTypeClass, apiListTypeClass, 0);
} | [
"public",
"synchronized",
"<",
"ApiType",
",",
"ApiListType",
">",
"SharedIndexInformer",
"<",
"ApiType",
">",
"sharedIndexInformerFor",
"(",
"Function",
"<",
"CallGeneratorParams",
",",
"Call",
">",
"callGenerator",
",",
"Class",
"<",
"ApiType",
">",
"apiTypeClass"... | Shared index informer for shared index informer.
@param <ApiType> the type parameter
@param <ApiListType> the type parameter
@param callGenerator the call generator
@param apiTypeClass the api type class
@param apiListTypeClass the api list type class
@return the shared index informer | [
"Shared",
"index",
"informer",
"for",
"shared",
"index",
"informer",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/SharedInformerFactory.java#L53-L58 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/SharedInformerFactory.java | SharedInformerFactory.startAllRegisteredInformers | public synchronized void startAllRegisteredInformers() {
if (Collections.isEmptyMap(informers)) {
return;
}
informers.forEach(
(informerType, informer) -> {
if (!startedInformers.containsKey(informerType)) {
startedInformers.put(informerType, informerExecutor.submit(informer::run));
}
});
} | java | public synchronized void startAllRegisteredInformers() {
if (Collections.isEmptyMap(informers)) {
return;
}
informers.forEach(
(informerType, informer) -> {
if (!startedInformers.containsKey(informerType)) {
startedInformers.put(informerType, informerExecutor.submit(informer::run));
}
});
} | [
"public",
"synchronized",
"void",
"startAllRegisteredInformers",
"(",
")",
"{",
"if",
"(",
"Collections",
".",
"isEmptyMap",
"(",
"informers",
")",
")",
"{",
"return",
";",
"}",
"informers",
".",
"forEach",
"(",
"(",
"informerType",
",",
"informer",
")",
"->... | Start all registered informers. | [
"Start",
"all",
"registered",
"informers",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/SharedInformerFactory.java#L110-L120 | train |
kubernetes-client/java | util/src/main/java/io/kubernetes/client/informer/SharedInformerFactory.java | SharedInformerFactory.stopAllRegisteredInformers | public synchronized void stopAllRegisteredInformers() {
if (Collections.isEmptyMap(informers)) {
return;
}
informers.forEach(
(informerType, informer) -> {
if (startedInformers.containsKey(informerType)) {
startedInformers.remove(informerType);
informer.stop();
}
});
informerExecutor.shutdown();
} | java | public synchronized void stopAllRegisteredInformers() {
if (Collections.isEmptyMap(informers)) {
return;
}
informers.forEach(
(informerType, informer) -> {
if (startedInformers.containsKey(informerType)) {
startedInformers.remove(informerType);
informer.stop();
}
});
informerExecutor.shutdown();
} | [
"public",
"synchronized",
"void",
"stopAllRegisteredInformers",
"(",
")",
"{",
"if",
"(",
"Collections",
".",
"isEmptyMap",
"(",
"informers",
")",
")",
"{",
"return",
";",
"}",
"informers",
".",
"forEach",
"(",
"(",
"informerType",
",",
"informer",
")",
"->"... | Stop all registered informers. | [
"Stop",
"all",
"registered",
"informers",
"."
] | 7413e98bd904f09d1ad00fb60e8c6ff787f3f560 | https://github.com/kubernetes-client/java/blob/7413e98bd904f09d1ad00fb60e8c6ff787f3f560/util/src/main/java/io/kubernetes/client/informer/SharedInformerFactory.java#L123-L135 | train |
yanzhenjie/SwipeRecyclerView | support/src/main/java/com/yanzhenjie/recyclerview/SwipeRecyclerView.java | SwipeRecyclerView.setSwipeItemMenuEnabled | public void setSwipeItemMenuEnabled(int position, boolean enabled) {
if (enabled) {
if (mDisableSwipeItemMenuList.contains(position)) {
mDisableSwipeItemMenuList.remove(Integer.valueOf(position));
}
} else {
if (!mDisableSwipeItemMenuList.contains(position)) {
mDisableSwipeItemMenuList.add(position);
}
}
} | java | public void setSwipeItemMenuEnabled(int position, boolean enabled) {
if (enabled) {
if (mDisableSwipeItemMenuList.contains(position)) {
mDisableSwipeItemMenuList.remove(Integer.valueOf(position));
}
} else {
if (!mDisableSwipeItemMenuList.contains(position)) {
mDisableSwipeItemMenuList.add(position);
}
}
} | [
"public",
"void",
"setSwipeItemMenuEnabled",
"(",
"int",
"position",
",",
"boolean",
"enabled",
")",
"{",
"if",
"(",
"enabled",
")",
"{",
"if",
"(",
"mDisableSwipeItemMenuList",
".",
"contains",
"(",
"position",
")",
")",
"{",
"mDisableSwipeItemMenuList",
".",
... | Set the item menu to enable status.
@param position the position of the item.
@param enabled true means available, otherwise not available; default is true. | [
"Set",
"the",
"item",
"menu",
"to",
"enable",
"status",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/support/src/main/java/com/yanzhenjie/recyclerview/SwipeRecyclerView.java#L157-L167 | train |
yanzhenjie/SwipeRecyclerView | support/src/main/java/com/yanzhenjie/recyclerview/SwipeRecyclerView.java | SwipeRecyclerView.addHeaderView | public void addHeaderView(View view) {
mHeaderViewList.add(view);
if (mAdapterWrapper != null) {
mAdapterWrapper.addHeaderViewAndNotify(view);
}
} | java | public void addHeaderView(View view) {
mHeaderViewList.add(view);
if (mAdapterWrapper != null) {
mAdapterWrapper.addHeaderViewAndNotify(view);
}
} | [
"public",
"void",
"addHeaderView",
"(",
"View",
"view",
")",
"{",
"mHeaderViewList",
".",
"add",
"(",
"view",
")",
";",
"if",
"(",
"mAdapterWrapper",
"!=",
"null",
")",
"{",
"mAdapterWrapper",
".",
"addHeaderViewAndNotify",
"(",
"view",
")",
";",
"}",
"}"
... | Add view at the headers. | [
"Add",
"view",
"at",
"the",
"headers",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/support/src/main/java/com/yanzhenjie/recyclerview/SwipeRecyclerView.java#L441-L446 | train |
yanzhenjie/SwipeRecyclerView | support/src/main/java/com/yanzhenjie/recyclerview/SwipeRecyclerView.java | SwipeRecyclerView.removeHeaderView | public void removeHeaderView(View view) {
mHeaderViewList.remove(view);
if (mAdapterWrapper != null) {
mAdapterWrapper.removeHeaderViewAndNotify(view);
}
} | java | public void removeHeaderView(View view) {
mHeaderViewList.remove(view);
if (mAdapterWrapper != null) {
mAdapterWrapper.removeHeaderViewAndNotify(view);
}
} | [
"public",
"void",
"removeHeaderView",
"(",
"View",
"view",
")",
"{",
"mHeaderViewList",
".",
"remove",
"(",
"view",
")",
";",
"if",
"(",
"mAdapterWrapper",
"!=",
"null",
")",
"{",
"mAdapterWrapper",
".",
"removeHeaderViewAndNotify",
"(",
"view",
")",
";",
"}... | Remove view from header. | [
"Remove",
"view",
"from",
"header",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/support/src/main/java/com/yanzhenjie/recyclerview/SwipeRecyclerView.java#L451-L456 | train |
yanzhenjie/SwipeRecyclerView | support/src/main/java/com/yanzhenjie/recyclerview/SwipeRecyclerView.java | SwipeRecyclerView.addFooterView | public void addFooterView(View view) {
mFooterViewList.add(view);
if (mAdapterWrapper != null) {
mAdapterWrapper.addFooterViewAndNotify(view);
}
} | java | public void addFooterView(View view) {
mFooterViewList.add(view);
if (mAdapterWrapper != null) {
mAdapterWrapper.addFooterViewAndNotify(view);
}
} | [
"public",
"void",
"addFooterView",
"(",
"View",
"view",
")",
"{",
"mFooterViewList",
".",
"add",
"(",
"view",
")",
";",
"if",
"(",
"mAdapterWrapper",
"!=",
"null",
")",
"{",
"mAdapterWrapper",
".",
"addFooterViewAndNotify",
"(",
"view",
")",
";",
"}",
"}"
... | Add view at the footer. | [
"Add",
"view",
"at",
"the",
"footer",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/support/src/main/java/com/yanzhenjie/recyclerview/SwipeRecyclerView.java#L461-L466 | train |
yanzhenjie/SwipeRecyclerView | support/src/main/java/com/yanzhenjie/recyclerview/ExpandableAdapter.java | ExpandableAdapter.expandParent | public final void expandParent(int parentPosition) {
if (!isExpanded(parentPosition)) {
mExpandItemArray.append(parentPosition, true);
int position = positionFromParentPosition(parentPosition);
int childCount = childItemCount(parentPosition);
notifyItemRangeInserted(position + 1, childCount);
}
} | java | public final void expandParent(int parentPosition) {
if (!isExpanded(parentPosition)) {
mExpandItemArray.append(parentPosition, true);
int position = positionFromParentPosition(parentPosition);
int childCount = childItemCount(parentPosition);
notifyItemRangeInserted(position + 1, childCount);
}
} | [
"public",
"final",
"void",
"expandParent",
"(",
"int",
"parentPosition",
")",
"{",
"if",
"(",
"!",
"isExpanded",
"(",
"parentPosition",
")",
")",
"{",
"mExpandItemArray",
".",
"append",
"(",
"parentPosition",
",",
"true",
")",
";",
"int",
"position",
"=",
... | Expand parent.
@param parentPosition position of parent item. | [
"Expand",
"parent",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/support/src/main/java/com/yanzhenjie/recyclerview/ExpandableAdapter.java#L56-L64 | train |
yanzhenjie/SwipeRecyclerView | support/src/main/java/com/yanzhenjie/recyclerview/ExpandableAdapter.java | ExpandableAdapter.collapseParent | public final void collapseParent(int parentPosition) {
if (isExpanded(parentPosition)) {
mExpandItemArray.append(parentPosition, false);
int position = positionFromParentPosition(parentPosition);
int childCount = childItemCount(parentPosition);
notifyItemRangeRemoved(position + 1, childCount);
}
} | java | public final void collapseParent(int parentPosition) {
if (isExpanded(parentPosition)) {
mExpandItemArray.append(parentPosition, false);
int position = positionFromParentPosition(parentPosition);
int childCount = childItemCount(parentPosition);
notifyItemRangeRemoved(position + 1, childCount);
}
} | [
"public",
"final",
"void",
"collapseParent",
"(",
"int",
"parentPosition",
")",
"{",
"if",
"(",
"isExpanded",
"(",
"parentPosition",
")",
")",
"{",
"mExpandItemArray",
".",
"append",
"(",
"parentPosition",
",",
"false",
")",
";",
"int",
"position",
"=",
"pos... | Collapse parent.
@param parentPosition position of parent item. | [
"Collapse",
"parent",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/support/src/main/java/com/yanzhenjie/recyclerview/ExpandableAdapter.java#L71-L79 | train |
yanzhenjie/SwipeRecyclerView | support/src/main/java/com/yanzhenjie/recyclerview/ExpandableAdapter.java | ExpandableAdapter.isParentItem | public final boolean isParentItem(int adapterPosition) {
int itemCount = 0;
int parentCount = parentItemCount();
for (int i = 0; i < parentCount; i++) {
if (itemCount == adapterPosition) {
return true;
}
itemCount += 1;
if (isExpanded(i)) {
itemCount += childItemCount(i);
} else {
// itemCount += 1;
}
}
return false;
} | java | public final boolean isParentItem(int adapterPosition) {
int itemCount = 0;
int parentCount = parentItemCount();
for (int i = 0; i < parentCount; i++) {
if (itemCount == adapterPosition) {
return true;
}
itemCount += 1;
if (isExpanded(i)) {
itemCount += childItemCount(i);
} else {
// itemCount += 1;
}
}
return false;
} | [
"public",
"final",
"boolean",
"isParentItem",
"(",
"int",
"adapterPosition",
")",
"{",
"int",
"itemCount",
"=",
"0",
";",
"int",
"parentCount",
"=",
"parentItemCount",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"parentCount",
";",
... | Item is a parent item.
@param adapterPosition adapter position.
@return true, otherwise is false. | [
"Item",
"is",
"a",
"parent",
"item",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/support/src/main/java/com/yanzhenjie/recyclerview/ExpandableAdapter.java#L260-L279 | train |
yanzhenjie/SwipeRecyclerView | support/src/main/java/com/yanzhenjie/recyclerview/ExpandableAdapter.java | ExpandableAdapter.parentItemPosition | public final int parentItemPosition(int adapterPosition) {
int itemCount = 0;
for (int i = 0; i < parentItemCount(); i++) {
itemCount += 1;
if (isExpanded(i)) {
int childCount = childItemCount(i);
itemCount += childCount;
}
if (adapterPosition < itemCount) {
return i;
}
}
throw new IllegalStateException("The adapter position is not a parent type: " + adapterPosition);
} | java | public final int parentItemPosition(int adapterPosition) {
int itemCount = 0;
for (int i = 0; i < parentItemCount(); i++) {
itemCount += 1;
if (isExpanded(i)) {
int childCount = childItemCount(i);
itemCount += childCount;
}
if (adapterPosition < itemCount) {
return i;
}
}
throw new IllegalStateException("The adapter position is not a parent type: " + adapterPosition);
} | [
"public",
"final",
"int",
"parentItemPosition",
"(",
"int",
"adapterPosition",
")",
"{",
"int",
"itemCount",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"parentItemCount",
"(",
")",
";",
"i",
"++",
")",
"{",
"itemCount",
"+=",
"1"... | Get the position of the parent item from the adapter position.
@param adapterPosition adapter position of item. | [
"Get",
"the",
"position",
"of",
"the",
"parent",
"item",
"from",
"the",
"adapter",
"position",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/support/src/main/java/com/yanzhenjie/recyclerview/ExpandableAdapter.java#L286-L301 | train |
yanzhenjie/SwipeRecyclerView | support/src/main/java/com/yanzhenjie/recyclerview/ExpandableAdapter.java | ExpandableAdapter.childItemPosition | public final int childItemPosition(int childAdapterPosition) {
int itemCount = 0;
int parentCount = parentItemCount();
for (int i = 0; i < parentCount; i++) {
itemCount += 1;
if (isExpanded(i)) {
int childCount = childItemCount(i);
itemCount += childCount;
if (childAdapterPosition < itemCount) {
return childCount - (itemCount - childAdapterPosition);
}
} else {
// itemCount += 1;
}
}
throw new IllegalStateException("The adapter position is invalid: " + childAdapterPosition);
} | java | public final int childItemPosition(int childAdapterPosition) {
int itemCount = 0;
int parentCount = parentItemCount();
for (int i = 0; i < parentCount; i++) {
itemCount += 1;
if (isExpanded(i)) {
int childCount = childItemCount(i);
itemCount += childCount;
if (childAdapterPosition < itemCount) {
return childCount - (itemCount - childAdapterPosition);
}
} else {
// itemCount += 1;
}
}
throw new IllegalStateException("The adapter position is invalid: " + childAdapterPosition);
} | [
"public",
"final",
"int",
"childItemPosition",
"(",
"int",
"childAdapterPosition",
")",
"{",
"int",
"itemCount",
"=",
"0",
";",
"int",
"parentCount",
"=",
"parentItemCount",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"parentCount",
"... | Get the position of the child item from the adapter position.
@param childAdapterPosition adapter position of child item. | [
"Get",
"the",
"position",
"of",
"the",
"child",
"item",
"from",
"the",
"adapter",
"position",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/support/src/main/java/com/yanzhenjie/recyclerview/ExpandableAdapter.java#L308-L328 | train |
yanzhenjie/SwipeRecyclerView | support/src/main/java/com/yanzhenjie/recyclerview/widget/Drawer.java | Drawer.drawLeft | public void drawLeft(View view, Canvas c) {
int left = view.getLeft() - mWidth;
int top = view.getTop() - mHeight;
int right = left + mWidth;
int bottom = view.getBottom() + mHeight;
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
} | java | public void drawLeft(View view, Canvas c) {
int left = view.getLeft() - mWidth;
int top = view.getTop() - mHeight;
int right = left + mWidth;
int bottom = view.getBottom() + mHeight;
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
} | [
"public",
"void",
"drawLeft",
"(",
"View",
"view",
",",
"Canvas",
"c",
")",
"{",
"int",
"left",
"=",
"view",
".",
"getLeft",
"(",
")",
"-",
"mWidth",
";",
"int",
"top",
"=",
"view",
".",
"getTop",
"(",
")",
"-",
"mHeight",
";",
"int",
"right",
"=... | Draw the divider on the left side of the Item. | [
"Draw",
"the",
"divider",
"on",
"the",
"left",
"side",
"of",
"the",
"Item",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/support/src/main/java/com/yanzhenjie/recyclerview/widget/Drawer.java#L40-L47 | train |
yanzhenjie/SwipeRecyclerView | x/src/main/java/com/yanzhenjie/recyclerview/SwipeMenuLayout.java | SwipeMenuLayout.getSwipeDuration | private int getSwipeDuration(MotionEvent ev, int velocity) {
int sx = getScrollX();
int dx = (int)(ev.getX() - sx);
final int width = mSwipeCurrentHorizontal.getMenuWidth();
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio);
int duration;
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
final float pageDelta = (float)Math.abs(dx) / width;
duration = (int)((pageDelta + 1) * 100);
}
duration = Math.min(duration, mScrollerDuration);
return duration;
} | java | private int getSwipeDuration(MotionEvent ev, int velocity) {
int sx = getScrollX();
int dx = (int)(ev.getX() - sx);
final int width = mSwipeCurrentHorizontal.getMenuWidth();
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio);
int duration;
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
final float pageDelta = (float)Math.abs(dx) / width;
duration = (int)((pageDelta + 1) * 100);
}
duration = Math.min(duration, mScrollerDuration);
return duration;
} | [
"private",
"int",
"getSwipeDuration",
"(",
"MotionEvent",
"ev",
",",
"int",
"velocity",
")",
"{",
"int",
"sx",
"=",
"getScrollX",
"(",
")",
";",
"int",
"dx",
"=",
"(",
"int",
")",
"(",
"ev",
".",
"getX",
"(",
")",
"-",
"sx",
")",
";",
"final",
"i... | compute finish duration.
@param ev up event.
@param velocity velocity x.
@return finish duration. | [
"compute",
"finish",
"duration",
"."
] | 69aa14d05da09beaeb880240c62f7de6f4f1bb39 | https://github.com/yanzhenjie/SwipeRecyclerView/blob/69aa14d05da09beaeb880240c62f7de6f4f1bb39/x/src/main/java/com/yanzhenjie/recyclerview/SwipeMenuLayout.java#L305-L321 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/MapTileProviderArray.java | MapTileProviderArray.findNextAppropriateProvider | protected MapTileModuleProviderBase findNextAppropriateProvider(final MapTileRequestState aState) {
MapTileModuleProviderBase provider;
boolean providerDoesntExist = false, providerCantGetDataConnection = false, providerCantServiceZoomlevel = false;
// The logic of the while statement is
// "Keep looping until you get null, or a provider that still exists
// and has a data connection if it needs one and can service the zoom level,"
do {
provider = aState.getNextProvider();
// Perform some checks to see if we can use this provider
// If any of these are true, then that disqualifies the provider for this tile request.
if (provider != null) {
providerDoesntExist = !this.getProviderExists(provider);
providerCantGetDataConnection = !useDataConnection()
&& provider.getUsesDataConnection();
int zoomLevel = MapTileIndex.getZoom(aState.getMapTile());
providerCantServiceZoomlevel = zoomLevel > provider.getMaximumZoomLevel()
|| zoomLevel < provider.getMinimumZoomLevel();
}
} while ((provider != null)
&& (providerDoesntExist || providerCantGetDataConnection || providerCantServiceZoomlevel));
return provider;
} | java | protected MapTileModuleProviderBase findNextAppropriateProvider(final MapTileRequestState aState) {
MapTileModuleProviderBase provider;
boolean providerDoesntExist = false, providerCantGetDataConnection = false, providerCantServiceZoomlevel = false;
// The logic of the while statement is
// "Keep looping until you get null, or a provider that still exists
// and has a data connection if it needs one and can service the zoom level,"
do {
provider = aState.getNextProvider();
// Perform some checks to see if we can use this provider
// If any of these are true, then that disqualifies the provider for this tile request.
if (provider != null) {
providerDoesntExist = !this.getProviderExists(provider);
providerCantGetDataConnection = !useDataConnection()
&& provider.getUsesDataConnection();
int zoomLevel = MapTileIndex.getZoom(aState.getMapTile());
providerCantServiceZoomlevel = zoomLevel > provider.getMaximumZoomLevel()
|| zoomLevel < provider.getMinimumZoomLevel();
}
} while ((provider != null)
&& (providerDoesntExist || providerCantGetDataConnection || providerCantServiceZoomlevel));
return provider;
} | [
"protected",
"MapTileModuleProviderBase",
"findNextAppropriateProvider",
"(",
"final",
"MapTileRequestState",
"aState",
")",
"{",
"MapTileModuleProviderBase",
"provider",
";",
"boolean",
"providerDoesntExist",
"=",
"false",
",",
"providerCantGetDataConnection",
"=",
"false",
... | We want to not use a provider that doesn't exist anymore in the chain, and we want to not use
a provider that requires a data connection when one is not available. | [
"We",
"want",
"to",
"not",
"use",
"a",
"provider",
"that",
"doesn",
"t",
"exist",
"anymore",
"in",
"the",
"chain",
"and",
"we",
"want",
"to",
"not",
"use",
"a",
"provider",
"that",
"requires",
"a",
"data",
"connection",
"when",
"one",
"is",
"not",
"ava... | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/MapTileProviderArray.java#L198-L219 | train |
osmdroid/osmdroid | OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/AsyncTaskDemoFragment.java | AsyncTaskDemoFragment.reloadMarker | private void reloadMarker(BoundingBox latLonArea, double zoom) {
Log.d(TAG,"reloadMarker " + latLonArea + ", zoom " + zoom);
this.mCurrentBackgroundMarkerLoaderTask = new BackgroundMarkerLoaderTask();
this.mCurrentBackgroundMarkerLoaderTask.execute(
latLonArea.getLatSouth(), latLonArea.getLatNorth(),
latLonArea.getLonEast(), latLonArea.getLonWest(), zoom);
} | java | private void reloadMarker(BoundingBox latLonArea, double zoom) {
Log.d(TAG,"reloadMarker " + latLonArea + ", zoom " + zoom);
this.mCurrentBackgroundMarkerLoaderTask = new BackgroundMarkerLoaderTask();
this.mCurrentBackgroundMarkerLoaderTask.execute(
latLonArea.getLatSouth(), latLonArea.getLatNorth(),
latLonArea.getLonEast(), latLonArea.getLonWest(), zoom);
} | [
"private",
"void",
"reloadMarker",
"(",
"BoundingBox",
"latLonArea",
",",
"double",
"zoom",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"reloadMarker \"",
"+",
"latLonArea",
"+",
"\", zoom \"",
"+",
"zoom",
")",
";",
"this",
".",
"mCurrentBackgroundMarkerLoa... | called by MapView if zoom or scroll has changed to reload marker for new visible region | [
"called",
"by",
"MapView",
"if",
"zoom",
"or",
"scroll",
"has",
"changed",
"to",
"reload",
"marker",
"for",
"new",
"visible",
"region"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/AsyncTaskDemoFragment.java#L163-L169 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/MapTilePreCache.java | MapTilePreCache.next | private long next() {
while(true) {
final long index;
synchronized (mTileAreas) {
if(!mTileIndices.hasNext()) {
return -1;
}
index = mTileIndices.next();
}
final Drawable drawable = mCache.getMapTile(index);
if (drawable == null) {
return index;
}
}
} | java | private long next() {
while(true) {
final long index;
synchronized (mTileAreas) {
if(!mTileIndices.hasNext()) {
return -1;
}
index = mTileIndices.next();
}
final Drawable drawable = mCache.getMapTile(index);
if (drawable == null) {
return index;
}
}
} | [
"private",
"long",
"next",
"(",
")",
"{",
"while",
"(",
"true",
")",
"{",
"final",
"long",
"index",
";",
"synchronized",
"(",
"mTileAreas",
")",
"{",
"if",
"(",
"!",
"mTileIndices",
".",
"hasNext",
"(",
")",
")",
"{",
"return",
"-",
"1",
";",
"}",
... | Get the next tile to search for
@return -1 if not found | [
"Get",
"the",
"next",
"tile",
"to",
"search",
"for"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/MapTilePreCache.java#L95-L109 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/MapTilePreCache.java | MapTilePreCache.search | private void search(final long pMapTileIndex) {
for (final MapTileModuleProviderBase provider : mProviders) {
try {
if (provider instanceof MapTileDownloader) {
final ITileSource tileSource = ((MapTileDownloader) provider).getTileSource();
if (tileSource instanceof OnlineTileSourceBase) {
if (!((OnlineTileSourceBase)tileSource).getTileSourcePolicy().acceptsPreventive()) {
continue;
}
}
}
final Drawable drawable = provider.getTileLoader().loadTile(pMapTileIndex);
if (drawable == null) {
continue;
}
mCache.putTile(pMapTileIndex, drawable);
return;
} catch (CantContinueException exception) {
// just dismiss that lazily: we don't need to be severe here
}
}
} | java | private void search(final long pMapTileIndex) {
for (final MapTileModuleProviderBase provider : mProviders) {
try {
if (provider instanceof MapTileDownloader) {
final ITileSource tileSource = ((MapTileDownloader) provider).getTileSource();
if (tileSource instanceof OnlineTileSourceBase) {
if (!((OnlineTileSourceBase)tileSource).getTileSourcePolicy().acceptsPreventive()) {
continue;
}
}
}
final Drawable drawable = provider.getTileLoader().loadTile(pMapTileIndex);
if (drawable == null) {
continue;
}
mCache.putTile(pMapTileIndex, drawable);
return;
} catch (CantContinueException exception) {
// just dismiss that lazily: we don't need to be severe here
}
}
} | [
"private",
"void",
"search",
"(",
"final",
"long",
"pMapTileIndex",
")",
"{",
"for",
"(",
"final",
"MapTileModuleProviderBase",
"provider",
":",
"mProviders",
")",
"{",
"try",
"{",
"if",
"(",
"provider",
"instanceof",
"MapTileDownloader",
")",
"{",
"final",
"I... | Search for a tile bitmap into the list of providers and put it in the memory cache | [
"Search",
"for",
"a",
"tile",
"bitmap",
"into",
"the",
"list",
"of",
"providers",
"and",
"put",
"it",
"in",
"the",
"memory",
"cache"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/MapTilePreCache.java#L114-L135 | train |
osmdroid/osmdroid | OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/tileproviders/OfflinePickerSample.java | OfflinePickerSample.promptForFiles | private void promptForFiles() {
DialogProperties properties = new DialogProperties();
properties.selection_mode = DialogConfigs.MULTI_MODE;
properties.selection_type = DialogConfigs.FILE_SELECT;
properties.root = new File(DialogConfigs.DEFAULT_DIR);
properties.error_dir = new File(DialogConfigs.DEFAULT_DIR);
properties.offset = new File(DialogConfigs.DEFAULT_DIR);
Set<String> registeredExtensions = ArchiveFileFactory.getRegisteredExtensions();
//api check
if (Build.VERSION.SDK_INT >= 14)
registeredExtensions.add("gpkg");
registeredExtensions.add("map");
String[] ret = new String[registeredExtensions.size()];
ret = registeredExtensions.toArray(ret);
properties.extensions = ret;
FilePickerDialog dialog = new FilePickerDialog(getContext(), properties);
dialog.setTitle("Select a File");
dialog.setDialogSelectionListener(new DialogSelectionListener() {
@Override
public void onSelectedFilePaths(String[] files) {
//files is the array of the paths of files selected by the Application User.
setProviderConfig(files);
}
});
dialog.show();
} | java | private void promptForFiles() {
DialogProperties properties = new DialogProperties();
properties.selection_mode = DialogConfigs.MULTI_MODE;
properties.selection_type = DialogConfigs.FILE_SELECT;
properties.root = new File(DialogConfigs.DEFAULT_DIR);
properties.error_dir = new File(DialogConfigs.DEFAULT_DIR);
properties.offset = new File(DialogConfigs.DEFAULT_DIR);
Set<String> registeredExtensions = ArchiveFileFactory.getRegisteredExtensions();
//api check
if (Build.VERSION.SDK_INT >= 14)
registeredExtensions.add("gpkg");
registeredExtensions.add("map");
String[] ret = new String[registeredExtensions.size()];
ret = registeredExtensions.toArray(ret);
properties.extensions = ret;
FilePickerDialog dialog = new FilePickerDialog(getContext(), properties);
dialog.setTitle("Select a File");
dialog.setDialogSelectionListener(new DialogSelectionListener() {
@Override
public void onSelectedFilePaths(String[] files) {
//files is the array of the paths of files selected by the Application User.
setProviderConfig(files);
}
});
dialog.show();
} | [
"private",
"void",
"promptForFiles",
"(",
")",
"{",
"DialogProperties",
"properties",
"=",
"new",
"DialogProperties",
"(",
")",
";",
"properties",
".",
"selection_mode",
"=",
"DialogConfigs",
".",
"MULTI_MODE",
";",
"properties",
".",
"selection_type",
"=",
"Dialo... | step 1, users selects files | [
"step",
"1",
"users",
"selects",
"files"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/tileproviders/OfflinePickerSample.java#L102-L131 | train |
osmdroid/osmdroid | OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/tileproviders/OfflinePickerSample.java | OfflinePickerSample.promptForTileSource | private void promptForTileSource() {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(getContext());
builderSingle.setIcon(R.drawable.icon);
builderSingle.setTitle("Select Offline Tile source:-");
final ArrayAdapter<ITileSource> arrayAdapter = new ArrayAdapter<ITileSource>(getContext(), android.R.layout.select_dialog_singlechoice);
arrayAdapter.addAll(tileSources);
builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final ITileSource strName = arrayAdapter.getItem(which);
AlertDialog.Builder builderInner = new AlertDialog.Builder(getContext());
builderInner.setMessage(strName.name());
builderInner.setTitle("Your Selected Item is");
builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mMapView.setTileSource(strName);//new XYTileSource(strName, 0, 22, 256, "png", new String[0]));
//on tile sources that are supported, center the map an area that's within bounds
if (strName instanceof MapsForgeTileSource) {
final MapsForgeTileSource src = (MapsForgeTileSource) strName;
mMapView.post(new Runnable() {
@Override
public void run() {
mMapView.getController().setZoom(src.getMinimumZoomLevel());
mMapView.setMinZoomLevel((double) src.getMinimumZoomLevel());
mMapView.setMaxZoomLevel((double) src.getMaximumZoomLevel());
mMapView.invalidate();
mMapView.zoomToBoundingBox(src.getBoundsOsmdroid(), true);
}
});
} else if (strName instanceof GeopackageRasterTileSource) {
final GeopackageRasterTileSource src = (GeopackageRasterTileSource) strName;
mMapView.post(new Runnable() {
@Override
public void run() {
mMapView.getController().setZoom(src.getMinimumZoomLevel());
mMapView.setMinZoomLevel((double) src.getMinimumZoomLevel());
mMapView.setMaxZoomLevel((double) src.getMaximumZoomLevel());
mMapView.invalidate();
mMapView.zoomToBoundingBox(src.getBounds(), true);
}
});
}
dialog.dismiss();
}
});
builderInner.show();
}
});
builderSingle.show();
} | java | private void promptForTileSource() {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(getContext());
builderSingle.setIcon(R.drawable.icon);
builderSingle.setTitle("Select Offline Tile source:-");
final ArrayAdapter<ITileSource> arrayAdapter = new ArrayAdapter<ITileSource>(getContext(), android.R.layout.select_dialog_singlechoice);
arrayAdapter.addAll(tileSources);
builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final ITileSource strName = arrayAdapter.getItem(which);
AlertDialog.Builder builderInner = new AlertDialog.Builder(getContext());
builderInner.setMessage(strName.name());
builderInner.setTitle("Your Selected Item is");
builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mMapView.setTileSource(strName);//new XYTileSource(strName, 0, 22, 256, "png", new String[0]));
//on tile sources that are supported, center the map an area that's within bounds
if (strName instanceof MapsForgeTileSource) {
final MapsForgeTileSource src = (MapsForgeTileSource) strName;
mMapView.post(new Runnable() {
@Override
public void run() {
mMapView.getController().setZoom(src.getMinimumZoomLevel());
mMapView.setMinZoomLevel((double) src.getMinimumZoomLevel());
mMapView.setMaxZoomLevel((double) src.getMaximumZoomLevel());
mMapView.invalidate();
mMapView.zoomToBoundingBox(src.getBoundsOsmdroid(), true);
}
});
} else if (strName instanceof GeopackageRasterTileSource) {
final GeopackageRasterTileSource src = (GeopackageRasterTileSource) strName;
mMapView.post(new Runnable() {
@Override
public void run() {
mMapView.getController().setZoom(src.getMinimumZoomLevel());
mMapView.setMinZoomLevel((double) src.getMinimumZoomLevel());
mMapView.setMaxZoomLevel((double) src.getMaximumZoomLevel());
mMapView.invalidate();
mMapView.zoomToBoundingBox(src.getBounds(), true);
}
});
}
dialog.dismiss();
}
});
builderInner.show();
}
});
builderSingle.show();
} | [
"private",
"void",
"promptForTileSource",
"(",
")",
"{",
"AlertDialog",
".",
"Builder",
"builderSingle",
"=",
"new",
"AlertDialog",
".",
"Builder",
"(",
"getContext",
"(",
")",
")",
";",
"builderSingle",
".",
"setIcon",
"(",
"R",
".",
"drawable",
".",
"icon"... | step 3 ask for the tile source | [
"step",
"3",
"ask",
"for",
"the",
"tile",
"source"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/tileproviders/OfflinePickerSample.java#L261-L326 | train |
osmdroid/osmdroid | osmdroid-mapsforge/src/main/java/org/osmdroid/mapsforge/MapsForgeTileSource.java | MapsForgeTileSource.renderTile | public synchronized Drawable renderTile(final long pMapTileIndex) {
Tile tile = new Tile(MapTileIndex.getX(pMapTileIndex), MapTileIndex.getY(pMapTileIndex), (byte) MapTileIndex.getZoom(pMapTileIndex), 256);
model.setFixedTileSize(256);
//You could try something like this to load a custom theme
//try{
// jobTheme = new ExternalRenderTheme(themeFile);
//}
//catch(Exception e){
// jobTheme = InternalRenderTheme.OSMARENDER;
//}
if (mapDatabase==null)
return null;
try {
//Draw the tile
RendererJob mapGeneratorJob = new RendererJob(tile, mapDatabase, theme, model, scale, false, false);
AndroidTileBitmap bmp = (AndroidTileBitmap) renderer.executeJob(mapGeneratorJob);
if (bmp != null)
return new BitmapDrawable(AndroidGraphicFactory.getBitmap(bmp));
} catch (Exception ex) {
Log.d(IMapView.LOGTAG, "###################### Mapsforge tile generation failed", ex);
}
//Make the bad tile easy to spot
Bitmap bitmap = Bitmap.createBitmap(TILE_SIZE_PIXELS, TILE_SIZE_PIXELS, Bitmap.Config.RGB_565);
bitmap.eraseColor(Color.YELLOW);
return new BitmapDrawable(bitmap);
} | java | public synchronized Drawable renderTile(final long pMapTileIndex) {
Tile tile = new Tile(MapTileIndex.getX(pMapTileIndex), MapTileIndex.getY(pMapTileIndex), (byte) MapTileIndex.getZoom(pMapTileIndex), 256);
model.setFixedTileSize(256);
//You could try something like this to load a custom theme
//try{
// jobTheme = new ExternalRenderTheme(themeFile);
//}
//catch(Exception e){
// jobTheme = InternalRenderTheme.OSMARENDER;
//}
if (mapDatabase==null)
return null;
try {
//Draw the tile
RendererJob mapGeneratorJob = new RendererJob(tile, mapDatabase, theme, model, scale, false, false);
AndroidTileBitmap bmp = (AndroidTileBitmap) renderer.executeJob(mapGeneratorJob);
if (bmp != null)
return new BitmapDrawable(AndroidGraphicFactory.getBitmap(bmp));
} catch (Exception ex) {
Log.d(IMapView.LOGTAG, "###################### Mapsforge tile generation failed", ex);
}
//Make the bad tile easy to spot
Bitmap bitmap = Bitmap.createBitmap(TILE_SIZE_PIXELS, TILE_SIZE_PIXELS, Bitmap.Config.RGB_565);
bitmap.eraseColor(Color.YELLOW);
return new BitmapDrawable(bitmap);
} | [
"public",
"synchronized",
"Drawable",
"renderTile",
"(",
"final",
"long",
"pMapTileIndex",
")",
"{",
"Tile",
"tile",
"=",
"new",
"Tile",
"(",
"MapTileIndex",
".",
"getX",
"(",
"pMapTileIndex",
")",
",",
"MapTileIndex",
".",
"getY",
"(",
"pMapTileIndex",
")",
... | The synchronized here is VERY important. If missing, the mapDatabase read gets corrupted by multiple threads reading the file at once. | [
"The",
"synchronized",
"here",
"is",
"VERY",
"important",
".",
"If",
"missing",
"the",
"mapDatabase",
"read",
"gets",
"corrupted",
"by",
"multiple",
"threads",
"reading",
"the",
"file",
"at",
"once",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-mapsforge/src/main/java/org/osmdroid/mapsforge/MapsForgeTileSource.java#L178-L207 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/util/GeoPoint.java | GeoPoint.destinationPoint | public GeoPoint destinationPoint(final double aDistanceInMeters, final double aBearingInDegrees) {
// convert distance to angular distance
final double dist = aDistanceInMeters / RADIUS_EARTH_METERS;
// convert bearing to radians
final double brng = DEG2RAD * aBearingInDegrees;
// get current location in radians
final double lat1 = DEG2RAD * getLatitude();
final double lon1 = DEG2RAD * getLongitude();
final double lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1)
* Math.sin(dist) * Math.cos(brng));
final double lon2 = lon1
+ Math.atan2(Math.sin(brng) * Math.sin(dist) * Math.cos(lat1), Math.cos(dist)
- Math.sin(lat1) * Math.sin(lat2));
final double lat2deg = lat2 / DEG2RAD;
final double lon2deg = lon2 / DEG2RAD;
return new GeoPoint(lat2deg, lon2deg);
} | java | public GeoPoint destinationPoint(final double aDistanceInMeters, final double aBearingInDegrees) {
// convert distance to angular distance
final double dist = aDistanceInMeters / RADIUS_EARTH_METERS;
// convert bearing to radians
final double brng = DEG2RAD * aBearingInDegrees;
// get current location in radians
final double lat1 = DEG2RAD * getLatitude();
final double lon1 = DEG2RAD * getLongitude();
final double lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1)
* Math.sin(dist) * Math.cos(brng));
final double lon2 = lon1
+ Math.atan2(Math.sin(brng) * Math.sin(dist) * Math.cos(lat1), Math.cos(dist)
- Math.sin(lat1) * Math.sin(lat2));
final double lat2deg = lat2 / DEG2RAD;
final double lon2deg = lon2 / DEG2RAD;
return new GeoPoint(lat2deg, lon2deg);
} | [
"public",
"GeoPoint",
"destinationPoint",
"(",
"final",
"double",
"aDistanceInMeters",
",",
"final",
"double",
"aBearingInDegrees",
")",
"{",
"// convert distance to angular distance",
"final",
"double",
"dist",
"=",
"aDistanceInMeters",
"/",
"RADIUS_EARTH_METERS",
";",
"... | Calculate a point that is the specified distance and bearing away from this point.
@see <a href="http://www.movable-type.co.uk/scripts/latlong.html">latlong.html</a>
@see <a href="http://www.movable-type.co.uk/scripts/latlon.js">latlon.js</a> | [
"Calculate",
"a",
"point",
"that",
"is",
"the",
"specified",
"distance",
"and",
"bearing",
"away",
"from",
"this",
"point",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/GeoPoint.java#L288-L310 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/util/Distance.java | Distance.getSquaredDistanceToPoint | public static double getSquaredDistanceToPoint(
final double pFromX, final double pFromY, final double pToX, final double pToY) {
final double dX = pFromX - pToX;
final double dY = pFromY - pToY;
return dX * dX + dY * dY;
} | java | public static double getSquaredDistanceToPoint(
final double pFromX, final double pFromY, final double pToX, final double pToY) {
final double dX = pFromX - pToX;
final double dY = pFromY - pToY;
return dX * dX + dY * dY;
} | [
"public",
"static",
"double",
"getSquaredDistanceToPoint",
"(",
"final",
"double",
"pFromX",
",",
"final",
"double",
"pFromY",
",",
"final",
"double",
"pToX",
",",
"final",
"double",
"pToY",
")",
"{",
"final",
"double",
"dX",
"=",
"pFromX",
"-",
"pToX",
";",... | Square of the distance between two points | [
"Square",
"of",
"the",
"distance",
"between",
"two",
"points"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/Distance.java#L16-L21 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/util/Distance.java | Distance.getSquaredDistanceToLine | public static double getSquaredDistanceToLine(
final double pFromX, final double pFromY,
final double pAX, final double pAY, final double pBX, final double pBY
) {
return getSquaredDistanceToProjection(pFromX, pFromY, pAX, pAY, pBX, pBY,
getProjectionFactorToLine(pFromX, pFromY, pAX, pAY, pBX, pBY));
} | java | public static double getSquaredDistanceToLine(
final double pFromX, final double pFromY,
final double pAX, final double pAY, final double pBX, final double pBY
) {
return getSquaredDistanceToProjection(pFromX, pFromY, pAX, pAY, pBX, pBY,
getProjectionFactorToLine(pFromX, pFromY, pAX, pAY, pBX, pBY));
} | [
"public",
"static",
"double",
"getSquaredDistanceToLine",
"(",
"final",
"double",
"pFromX",
",",
"final",
"double",
"pFromY",
",",
"final",
"double",
"pAX",
",",
"final",
"double",
"pAY",
",",
"final",
"double",
"pBX",
",",
"final",
"double",
"pBY",
")",
"{"... | Square of the distance between a point and line AB | [
"Square",
"of",
"the",
"distance",
"between",
"a",
"point",
"and",
"line",
"AB"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/Distance.java#L26-L32 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/util/Distance.java | Distance.getSquaredDistanceToSegment | public static double getSquaredDistanceToSegment(
final double pFromX, final double pFromY,
final double pAX, final double pAY, final double pBX, final double pBY
) {
return getSquaredDistanceToProjection(pFromX, pFromY, pAX, pAY, pBX, pBY,
getProjectionFactorToSegment(pFromX, pFromY, pAX, pAY, pBX, pBY));
} | java | public static double getSquaredDistanceToSegment(
final double pFromX, final double pFromY,
final double pAX, final double pAY, final double pBX, final double pBY
) {
return getSquaredDistanceToProjection(pFromX, pFromY, pAX, pAY, pBX, pBY,
getProjectionFactorToSegment(pFromX, pFromY, pAX, pAY, pBX, pBY));
} | [
"public",
"static",
"double",
"getSquaredDistanceToSegment",
"(",
"final",
"double",
"pFromX",
",",
"final",
"double",
"pFromY",
",",
"final",
"double",
"pAX",
",",
"final",
"double",
"pAY",
",",
"final",
"double",
"pBX",
",",
"final",
"double",
"pBY",
")",
... | Square of the distance between a point and segment AB | [
"Square",
"of",
"the",
"distance",
"between",
"a",
"point",
"and",
"segment",
"AB"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/Distance.java#L37-L43 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/util/Distance.java | Distance.dotProduct | private static double dotProduct(
final double pAX, final double pAY, final double pBX, final double pBY,
final double pCX, final double pCY) {
return (pBX - pAX) * (pCX - pAX) + (pBY - pAY) * (pCY - pAY);
} | java | private static double dotProduct(
final double pAX, final double pAY, final double pBX, final double pBY,
final double pCX, final double pCY) {
return (pBX - pAX) * (pCX - pAX) + (pBY - pAY) * (pCY - pAY);
} | [
"private",
"static",
"double",
"dotProduct",
"(",
"final",
"double",
"pAX",
",",
"final",
"double",
"pAY",
",",
"final",
"double",
"pBX",
",",
"final",
"double",
"pBY",
",",
"final",
"double",
"pCX",
",",
"final",
"double",
"pCY",
")",
"{",
"return",
"("... | Compute the dot product AB x AC | [
"Compute",
"the",
"dot",
"product",
"AB",
"x",
"AC"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/Distance.java#L98-L102 | train |
osmdroid/osmdroid | GoogleWrapperSample/src/main/java/org/osmdroid/google/sample/Googlev2WrapperSample.java | Googlev2WrapperSample.debugProjection | private void debugProjection() {
new Thread() {
@Override
public void run() {
// let the map get redrawn and a new projection calculated
try {
sleep(1000);
} catch (InterruptedException ignore) {
}
// then get the projection
runOnUiThread(new Runnable() {
@Override
public void run() {
final IProjection projection = mMap.getProjection();
final IGeoPoint northEast = projection.getNorthEast();
final IGeoPoint southWest = projection.getSouthWest();
final IProjection breakpoint = projection;
}
});
}
}.start();
} | java | private void debugProjection() {
new Thread() {
@Override
public void run() {
// let the map get redrawn and a new projection calculated
try {
sleep(1000);
} catch (InterruptedException ignore) {
}
// then get the projection
runOnUiThread(new Runnable() {
@Override
public void run() {
final IProjection projection = mMap.getProjection();
final IGeoPoint northEast = projection.getNorthEast();
final IGeoPoint southWest = projection.getSouthWest();
final IProjection breakpoint = projection;
}
});
}
}.start();
} | [
"private",
"void",
"debugProjection",
"(",
")",
"{",
"new",
"Thread",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"// let the map get redrawn and a new projection calculated",
"try",
"{",
"sleep",
"(",
"1000",
")",
";",
"}",
"catch"... | This is just used for debugging | [
"This",
"is",
"just",
"used",
"for",
"debugging"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/GoogleWrapperSample/src/main/java/org/osmdroid/google/sample/Googlev2WrapperSample.java#L194-L216 | train |
osmdroid/osmdroid | OSMMapTilePackager/src/main/java/org/osmdroid/mtp/OSMMapTilePackager.java | OSMMapTilePackager.run | private static void run(final String pServerURL, final String pDestinationFile, final String pTempFolder, final int pThreadCount, final String pFileAppendix, final int pMinZoom, final int pMaxZoom, final double pNorth, final double pSouth, final double pEast, final double pWest) {
new File(pTempFolder).mkdirs();
System.out.println("---------------------------");
runFileExpecterWithAbort(pMinZoom, pMaxZoom, pNorth, pSouth, pEast, pWest);
execute(pServerURL, pDestinationFile, pTempFolder, pThreadCount, pFileAppendix, pMinZoom, pMaxZoom, pNorth, pSouth, pEast, pWest, null);
if (pServerURL != null) {
runCleanup(pTempFolder, true);
}
} | java | private static void run(final String pServerURL, final String pDestinationFile, final String pTempFolder, final int pThreadCount, final String pFileAppendix, final int pMinZoom, final int pMaxZoom, final double pNorth, final double pSouth, final double pEast, final double pWest) {
new File(pTempFolder).mkdirs();
System.out.println("---------------------------");
runFileExpecterWithAbort(pMinZoom, pMaxZoom, pNorth, pSouth, pEast, pWest);
execute(pServerURL, pDestinationFile, pTempFolder, pThreadCount, pFileAppendix, pMinZoom, pMaxZoom, pNorth, pSouth, pEast, pWest, null);
if (pServerURL != null) {
runCleanup(pTempFolder, true);
}
} | [
"private",
"static",
"void",
"run",
"(",
"final",
"String",
"pServerURL",
",",
"final",
"String",
"pDestinationFile",
",",
"final",
"String",
"pTempFolder",
",",
"final",
"int",
"pThreadCount",
",",
"final",
"String",
"pFileAppendix",
",",
"final",
"int",
"pMinZ... | this starts executing the download and packaging
@param pServerURL
@param pDestinationFile
@param pTempFolder
@param pThreadCount
@param pFileAppendix
@param pMinZoom
@param pMaxZoom
@param pNorth
@param pSouth
@param pEast
@param pWest | [
"this",
"starts",
"executing",
"the",
"download",
"and",
"packaging"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OSMMapTilePackager/src/main/java/org/osmdroid/mtp/OSMMapTilePackager.java#L166-L177 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/views/overlay/compass/CompassOverlay.java | CompassOverlay.disableCompass | public void disableCompass() {
mIsCompassEnabled = false;
if (mOrientationProvider != null) {
mOrientationProvider.stopOrientationProvider();
}
// Reset values
mAzimuth = Float.NaN;
// Update the screen to see changes take effect
if (mMapView != null) {
this.invalidateCompass();
}
} | java | public void disableCompass() {
mIsCompassEnabled = false;
if (mOrientationProvider != null) {
mOrientationProvider.stopOrientationProvider();
}
// Reset values
mAzimuth = Float.NaN;
// Update the screen to see changes take effect
if (mMapView != null) {
this.invalidateCompass();
}
} | [
"public",
"void",
"disableCompass",
"(",
")",
"{",
"mIsCompassEnabled",
"=",
"false",
";",
"if",
"(",
"mOrientationProvider",
"!=",
"null",
")",
"{",
"mOrientationProvider",
".",
"stopOrientationProvider",
"(",
")",
";",
"}",
"// Reset values",
"mAzimuth",
"=",
... | Disable orientation updates.
Note the behavior has changed since v6.0.0. This method no longer releases
references to the orientation provider. Instead, that happens in the onDetached
method. | [
"Disable",
"orientation",
"updates",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/compass/CompassOverlay.java#L357-L371 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/views/overlay/compass/CompassOverlay.java | CompassOverlay.createCompassRosePicture | private void createCompassRosePicture() {
// Paint design of north triangle (it's common to paint north in red color)
final Paint northPaint = new Paint();
northPaint.setColor(0xFFA00000);
northPaint.setAntiAlias(true);
northPaint.setStyle(Style.FILL);
northPaint.setAlpha(220);
// Paint design of south triangle (black)
final Paint southPaint = new Paint();
southPaint.setColor(Color.BLACK);
southPaint.setAntiAlias(true);
southPaint.setStyle(Style.FILL);
southPaint.setAlpha(220);
// Create a little white dot in the middle of the compass rose
final Paint centerPaint = new Paint();
centerPaint.setColor(Color.WHITE);
centerPaint.setAntiAlias(true);
centerPaint.setStyle(Style.FILL);
centerPaint.setAlpha(220);
final int picBorderWidthAndHeight = (int) ((mCompassRadius + 5) * 2 * mScale);
final int center = picBorderWidthAndHeight / 2;
if (mCompassRoseBitmap != null)
mCompassRoseBitmap.recycle();
mCompassRoseBitmap = Bitmap.createBitmap(picBorderWidthAndHeight, picBorderWidthAndHeight,
Config.ARGB_8888);
final Canvas canvas = new Canvas(mCompassRoseBitmap);
// Triangle pointing north
final Path pathNorth = new Path();
pathNorth.moveTo(center, center - (mCompassRadius - 3) * mScale);
pathNorth.lineTo(center + 4 * mScale, center);
pathNorth.lineTo(center - 4 * mScale, center);
pathNorth.lineTo(center, center - (mCompassRadius - 3) * mScale);
pathNorth.close();
canvas.drawPath(pathNorth, northPaint);
// Triangle pointing south
final Path pathSouth = new Path();
pathSouth.moveTo(center, center + (mCompassRadius - 3) * mScale);
pathSouth.lineTo(center + 4 * mScale, center);
pathSouth.lineTo(center - 4 * mScale, center);
pathSouth.lineTo(center, center + (mCompassRadius - 3) * mScale);
pathSouth.close();
canvas.drawPath(pathSouth, southPaint);
// Draw a little white dot in the middle
canvas.drawCircle(center, center, 2, centerPaint);
} | java | private void createCompassRosePicture() {
// Paint design of north triangle (it's common to paint north in red color)
final Paint northPaint = new Paint();
northPaint.setColor(0xFFA00000);
northPaint.setAntiAlias(true);
northPaint.setStyle(Style.FILL);
northPaint.setAlpha(220);
// Paint design of south triangle (black)
final Paint southPaint = new Paint();
southPaint.setColor(Color.BLACK);
southPaint.setAntiAlias(true);
southPaint.setStyle(Style.FILL);
southPaint.setAlpha(220);
// Create a little white dot in the middle of the compass rose
final Paint centerPaint = new Paint();
centerPaint.setColor(Color.WHITE);
centerPaint.setAntiAlias(true);
centerPaint.setStyle(Style.FILL);
centerPaint.setAlpha(220);
final int picBorderWidthAndHeight = (int) ((mCompassRadius + 5) * 2 * mScale);
final int center = picBorderWidthAndHeight / 2;
if (mCompassRoseBitmap != null)
mCompassRoseBitmap.recycle();
mCompassRoseBitmap = Bitmap.createBitmap(picBorderWidthAndHeight, picBorderWidthAndHeight,
Config.ARGB_8888);
final Canvas canvas = new Canvas(mCompassRoseBitmap);
// Triangle pointing north
final Path pathNorth = new Path();
pathNorth.moveTo(center, center - (mCompassRadius - 3) * mScale);
pathNorth.lineTo(center + 4 * mScale, center);
pathNorth.lineTo(center - 4 * mScale, center);
pathNorth.lineTo(center, center - (mCompassRadius - 3) * mScale);
pathNorth.close();
canvas.drawPath(pathNorth, northPaint);
// Triangle pointing south
final Path pathSouth = new Path();
pathSouth.moveTo(center, center + (mCompassRadius - 3) * mScale);
pathSouth.lineTo(center + 4 * mScale, center);
pathSouth.lineTo(center - 4 * mScale, center);
pathSouth.lineTo(center, center + (mCompassRadius - 3) * mScale);
pathSouth.close();
canvas.drawPath(pathSouth, southPaint);
// Draw a little white dot in the middle
canvas.drawCircle(center, center, 2, centerPaint);
} | [
"private",
"void",
"createCompassRosePicture",
"(",
")",
"{",
"// Paint design of north triangle (it's common to paint north in red color)",
"final",
"Paint",
"northPaint",
"=",
"new",
"Paint",
"(",
")",
";",
"northPaint",
".",
"setColor",
"(",
"0xFFA00000",
")",
";",
"... | A conventional red and black compass needle. | [
"A",
"conventional",
"red",
"and",
"black",
"compass",
"needle",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/compass/CompassOverlay.java#L497-L548 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/views/overlay/compass/CompassOverlay.java | CompassOverlay.createPointerPicture | private void createPointerPicture() {
final Paint arrowPaint = new Paint();
arrowPaint.setColor(Color.BLACK);
arrowPaint.setAntiAlias(true);
arrowPaint.setStyle(Style.FILL);
arrowPaint.setAlpha(220);
// Create a little white dot in the middle of the compass rose
final Paint centerPaint = new Paint();
centerPaint.setColor(Color.WHITE);
centerPaint.setAntiAlias(true);
centerPaint.setStyle(Style.FILL);
centerPaint.setAlpha(220);
final int picBorderWidthAndHeight = (int) ((mCompassRadius + 5) * 2 * mScale);
final int center = picBorderWidthAndHeight / 2;
if (mCompassRoseBitmap != null)
mCompassRoseBitmap.recycle();
mCompassRoseBitmap = Bitmap.createBitmap(picBorderWidthAndHeight, picBorderWidthAndHeight,
Config.ARGB_8888);
final Canvas canvas = new Canvas(mCompassRoseBitmap);
// Arrow comprised of 2 triangles
final Path pathArrow = new Path();
pathArrow.moveTo(center, center - (mCompassRadius - 3) * mScale);
pathArrow.lineTo(center + 4 * mScale, center + (mCompassRadius - 3) * mScale);
pathArrow.lineTo(center, center + 0.5f * (mCompassRadius - 3) * mScale);
pathArrow.lineTo(center - 4 * mScale, center + (mCompassRadius - 3) * mScale);
pathArrow.lineTo(center, center - (mCompassRadius - 3) * mScale);
pathArrow.close();
canvas.drawPath(pathArrow, arrowPaint);
// Draw a little white dot in the middle
canvas.drawCircle(center, center, 2, centerPaint);
} | java | private void createPointerPicture() {
final Paint arrowPaint = new Paint();
arrowPaint.setColor(Color.BLACK);
arrowPaint.setAntiAlias(true);
arrowPaint.setStyle(Style.FILL);
arrowPaint.setAlpha(220);
// Create a little white dot in the middle of the compass rose
final Paint centerPaint = new Paint();
centerPaint.setColor(Color.WHITE);
centerPaint.setAntiAlias(true);
centerPaint.setStyle(Style.FILL);
centerPaint.setAlpha(220);
final int picBorderWidthAndHeight = (int) ((mCompassRadius + 5) * 2 * mScale);
final int center = picBorderWidthAndHeight / 2;
if (mCompassRoseBitmap != null)
mCompassRoseBitmap.recycle();
mCompassRoseBitmap = Bitmap.createBitmap(picBorderWidthAndHeight, picBorderWidthAndHeight,
Config.ARGB_8888);
final Canvas canvas = new Canvas(mCompassRoseBitmap);
// Arrow comprised of 2 triangles
final Path pathArrow = new Path();
pathArrow.moveTo(center, center - (mCompassRadius - 3) * mScale);
pathArrow.lineTo(center + 4 * mScale, center + (mCompassRadius - 3) * mScale);
pathArrow.lineTo(center, center + 0.5f * (mCompassRadius - 3) * mScale);
pathArrow.lineTo(center - 4 * mScale, center + (mCompassRadius - 3) * mScale);
pathArrow.lineTo(center, center - (mCompassRadius - 3) * mScale);
pathArrow.close();
canvas.drawPath(pathArrow, arrowPaint);
// Draw a little white dot in the middle
canvas.drawCircle(center, center, 2, centerPaint);
} | [
"private",
"void",
"createPointerPicture",
"(",
")",
"{",
"final",
"Paint",
"arrowPaint",
"=",
"new",
"Paint",
"(",
")",
";",
"arrowPaint",
".",
"setColor",
"(",
"Color",
".",
"BLACK",
")",
";",
"arrowPaint",
".",
"setAntiAlias",
"(",
"true",
")",
";",
"... | A black pointer arrow. | [
"A",
"black",
"pointer",
"arrow",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/compass/CompassOverlay.java#L553-L588 | train |
osmdroid/osmdroid | osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java | SphericalUtil.wrap | static double wrap(double n, double min, double max) {
return (n >= min && n < max) ? n : (mod(n - min, max - min) + min);
} | java | static double wrap(double n, double min, double max) {
return (n >= min && n < max) ? n : (mod(n - min, max - min) + min);
} | [
"static",
"double",
"wrap",
"(",
"double",
"n",
",",
"double",
"min",
",",
"double",
"max",
")",
"{",
"return",
"(",
"n",
">=",
"min",
"&&",
"n",
"<",
"max",
")",
"?",
"n",
":",
"(",
"mod",
"(",
"n",
"-",
"min",
",",
"max",
"-",
"min",
")",
... | Wraps the given value into the inclusive-exclusive interval between min and max.
@param n The value to wrap.
@param min The minimum.
@param max The maximum. | [
"Wraps",
"the",
"given",
"value",
"into",
"the",
"inclusive",
"-",
"exclusive",
"interval",
"between",
"min",
"and",
"max",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L58-L60 | train |
osmdroid/osmdroid | osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java | SphericalUtil.computeHeading | public static double computeHeading(IGeoPoint from, IGeoPoint to) {
// http://williams.best.vwh.net/avform.htm#Crs
double fromLat = toRadians(from.getLatitude());
double fromLng = toRadians(from.getLongitude());
double toLat = toRadians(to.getLatitude());
double toLng = toRadians(to.getLongitude());
double dLng = toLng - fromLng;
double heading = atan2(
sin(dLng) * cos(toLat),
cos(fromLat) * sin(toLat) - sin(fromLat) * cos(toLat) * cos(dLng));
return wrap(toDegrees(heading), -180, 180);
} | java | public static double computeHeading(IGeoPoint from, IGeoPoint to) {
// http://williams.best.vwh.net/avform.htm#Crs
double fromLat = toRadians(from.getLatitude());
double fromLng = toRadians(from.getLongitude());
double toLat = toRadians(to.getLatitude());
double toLng = toRadians(to.getLongitude());
double dLng = toLng - fromLng;
double heading = atan2(
sin(dLng) * cos(toLat),
cos(fromLat) * sin(toLat) - sin(fromLat) * cos(toLat) * cos(dLng));
return wrap(toDegrees(heading), -180, 180);
} | [
"public",
"static",
"double",
"computeHeading",
"(",
"IGeoPoint",
"from",
",",
"IGeoPoint",
"to",
")",
"{",
"// http://williams.best.vwh.net/avform.htm#Crs",
"double",
"fromLat",
"=",
"toRadians",
"(",
"from",
".",
"getLatitude",
"(",
")",
")",
";",
"double",
"fro... | Returns the heading from one LatLng to another LatLng. Headings are
expressed in degrees clockwise from North within the range [-180,180).
@return The heading in degrees clockwise from north. | [
"Returns",
"the",
"heading",
"from",
"one",
"LatLng",
"to",
"another",
"LatLng",
".",
"Headings",
"are",
"expressed",
"in",
"degrees",
"clockwise",
"from",
"North",
"within",
"the",
"range",
"[",
"-",
"180",
"180",
")",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L136-L147 | train |
osmdroid/osmdroid | osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java | SphericalUtil.computeOffsetOrigin | public static IGeoPoint computeOffsetOrigin(IGeoPoint to, double distance, double heading) {
heading = toRadians(heading);
distance /= EARTH_RADIUS;
// http://lists.maptools.org/pipermail/proj/2008-October/003939.html
double n1 = cos(distance);
double n2 = sin(distance) * cos(heading);
double n3 = sin(distance) * sin(heading);
double n4 = sin(toRadians(to.getLatitude()));
// There are two solutions for b. b = n2 * n4 +/- sqrt(), one solution results
// in the latitude outside the [-90, 90] range. We first try one solution and
// back off to the other if we are outside that range.
double n12 = n1 * n1;
double discriminant = n2 * n2 * n12 + n12 * n12 - n12 * n4 * n4;
if (discriminant < 0) {
// No real solution which would make sense in IGeoPoint-space.
return null;
}
double b = n2 * n4 + sqrt(discriminant);
b /= n1 * n1 + n2 * n2;
double a = (n4 - n2 * b) / n1;
double fromLatRadians = atan2(a, b);
if (fromLatRadians < -PI / 2 || fromLatRadians > PI / 2) {
b = n2 * n4 - sqrt(discriminant);
b /= n1 * n1 + n2 * n2;
fromLatRadians = atan2(a, b);
}
if (fromLatRadians < -PI / 2 || fromLatRadians > PI / 2) {
// No solution which would make sense in IGeoPoint-space.
return null;
}
double fromLngRadians = toRadians(to.getLongitude()) -
atan2(n3, n1 * cos(fromLatRadians) - n2 * sin(fromLatRadians));
return new GeoPoint(toDegrees(fromLatRadians), toDegrees(fromLngRadians));
} | java | public static IGeoPoint computeOffsetOrigin(IGeoPoint to, double distance, double heading) {
heading = toRadians(heading);
distance /= EARTH_RADIUS;
// http://lists.maptools.org/pipermail/proj/2008-October/003939.html
double n1 = cos(distance);
double n2 = sin(distance) * cos(heading);
double n3 = sin(distance) * sin(heading);
double n4 = sin(toRadians(to.getLatitude()));
// There are two solutions for b. b = n2 * n4 +/- sqrt(), one solution results
// in the latitude outside the [-90, 90] range. We first try one solution and
// back off to the other if we are outside that range.
double n12 = n1 * n1;
double discriminant = n2 * n2 * n12 + n12 * n12 - n12 * n4 * n4;
if (discriminant < 0) {
// No real solution which would make sense in IGeoPoint-space.
return null;
}
double b = n2 * n4 + sqrt(discriminant);
b /= n1 * n1 + n2 * n2;
double a = (n4 - n2 * b) / n1;
double fromLatRadians = atan2(a, b);
if (fromLatRadians < -PI / 2 || fromLatRadians > PI / 2) {
b = n2 * n4 - sqrt(discriminant);
b /= n1 * n1 + n2 * n2;
fromLatRadians = atan2(a, b);
}
if (fromLatRadians < -PI / 2 || fromLatRadians > PI / 2) {
// No solution which would make sense in IGeoPoint-space.
return null;
}
double fromLngRadians = toRadians(to.getLongitude()) -
atan2(n3, n1 * cos(fromLatRadians) - n2 * sin(fromLatRadians));
return new GeoPoint(toDegrees(fromLatRadians), toDegrees(fromLngRadians));
} | [
"public",
"static",
"IGeoPoint",
"computeOffsetOrigin",
"(",
"IGeoPoint",
"to",
",",
"double",
"distance",
",",
"double",
"heading",
")",
"{",
"heading",
"=",
"toRadians",
"(",
"heading",
")",
";",
"distance",
"/=",
"EARTH_RADIUS",
";",
"// http://lists.maptools.o... | Returns the location of origin when provided with a IGeoPoint destination,
meters travelled and original heading. Headings are expressed in degrees
clockwise from North. This function returns null when no solution is
available.
@param to The destination IGeoPoint.
@param distance The distance travelled, in meters.
@param heading The heading in degrees clockwise from north. | [
"Returns",
"the",
"location",
"of",
"origin",
"when",
"provided",
"with",
"a",
"IGeoPoint",
"destination",
"meters",
"travelled",
"and",
"original",
"heading",
".",
"Headings",
"are",
"expressed",
"in",
"degrees",
"clockwise",
"from",
"North",
".",
"This",
"func... | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L182-L215 | train |
osmdroid/osmdroid | osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java | SphericalUtil.interpolate | public static IGeoPoint interpolate(IGeoPoint from, IGeoPoint to, double fraction) {
// http://en.wikipedia.org/wiki/Slerp
double fromLat = toRadians(from.getLatitude());
double fromLng = toRadians(from.getLongitude());
double toLat = toRadians(to.getLatitude());
double toLng = toRadians(to.getLongitude());
double cosFromLat = cos(fromLat);
double cosToLat = cos(toLat);
// Computes Spherical interpolation coefficients.
double angle = computeAngleBetween(from, to);
double sinAngle = sin(angle);
if (sinAngle < 1E-6) {
return from;
}
double a = sin((1 - fraction) * angle) / sinAngle;
double b = sin(fraction * angle) / sinAngle;
// Converts from polar to vector and interpolate.
double x = a * cosFromLat * cos(fromLng) + b * cosToLat * cos(toLng);
double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng);
double z = a * sin(fromLat) + b * sin(toLat);
// Converts interpolated vector back to polar.
double lat = atan2(z, sqrt(x * x + y * y));
double lng = atan2(y, x);
return new GeoPoint(toDegrees(lat), toDegrees(lng));
} | java | public static IGeoPoint interpolate(IGeoPoint from, IGeoPoint to, double fraction) {
// http://en.wikipedia.org/wiki/Slerp
double fromLat = toRadians(from.getLatitude());
double fromLng = toRadians(from.getLongitude());
double toLat = toRadians(to.getLatitude());
double toLng = toRadians(to.getLongitude());
double cosFromLat = cos(fromLat);
double cosToLat = cos(toLat);
// Computes Spherical interpolation coefficients.
double angle = computeAngleBetween(from, to);
double sinAngle = sin(angle);
if (sinAngle < 1E-6) {
return from;
}
double a = sin((1 - fraction) * angle) / sinAngle;
double b = sin(fraction * angle) / sinAngle;
// Converts from polar to vector and interpolate.
double x = a * cosFromLat * cos(fromLng) + b * cosToLat * cos(toLng);
double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng);
double z = a * sin(fromLat) + b * sin(toLat);
// Converts interpolated vector back to polar.
double lat = atan2(z, sqrt(x * x + y * y));
double lng = atan2(y, x);
return new GeoPoint(toDegrees(lat), toDegrees(lng));
} | [
"public",
"static",
"IGeoPoint",
"interpolate",
"(",
"IGeoPoint",
"from",
",",
"IGeoPoint",
"to",
",",
"double",
"fraction",
")",
"{",
"// http://en.wikipedia.org/wiki/Slerp",
"double",
"fromLat",
"=",
"toRadians",
"(",
"from",
".",
"getLatitude",
"(",
")",
")",
... | Returns the IGeoPoint which lies the given fraction of the way between the
origin IGeoPoint and the destination IGeoPoint.
@param from The IGeoPoint from which to start.
@param to The IGeoPoint toward which to travel.
@param fraction A fraction of the distance to travel.
@return The interpolated IGeoPoint. | [
"Returns",
"the",
"IGeoPoint",
"which",
"lies",
"the",
"given",
"fraction",
"of",
"the",
"way",
"between",
"the",
"origin",
"IGeoPoint",
"and",
"the",
"destination",
"IGeoPoint",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L225-L252 | train |
osmdroid/osmdroid | osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java | SphericalUtil.distanceRadians | private static double distanceRadians(double lat1, double lng1, double lat2, double lng2) {
return arcHav(havDistance(lat1, lat2, lng1 - lng2));
} | java | private static double distanceRadians(double lat1, double lng1, double lat2, double lng2) {
return arcHav(havDistance(lat1, lat2, lng1 - lng2));
} | [
"private",
"static",
"double",
"distanceRadians",
"(",
"double",
"lat1",
",",
"double",
"lng1",
",",
"double",
"lat2",
",",
"double",
"lng2",
")",
"{",
"return",
"arcHav",
"(",
"havDistance",
"(",
"lat1",
",",
"lat2",
",",
"lng1",
"-",
"lng2",
")",
")",
... | Returns distance on the unit sphere; the arguments are in radians. | [
"Returns",
"distance",
"on",
"the",
"unit",
"sphere",
";",
"the",
"arguments",
"are",
"in",
"radians",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L257-L259 | train |
osmdroid/osmdroid | osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java | SphericalUtil.computeAngleBetween | static double computeAngleBetween(IGeoPoint from, IGeoPoint to) {
return distanceRadians(toRadians(from.getLatitude()), toRadians(from.getLongitude()),
toRadians(to.getLatitude()), toRadians(to.getLongitude()));
} | java | static double computeAngleBetween(IGeoPoint from, IGeoPoint to) {
return distanceRadians(toRadians(from.getLatitude()), toRadians(from.getLongitude()),
toRadians(to.getLatitude()), toRadians(to.getLongitude()));
} | [
"static",
"double",
"computeAngleBetween",
"(",
"IGeoPoint",
"from",
",",
"IGeoPoint",
"to",
")",
"{",
"return",
"distanceRadians",
"(",
"toRadians",
"(",
"from",
".",
"getLatitude",
"(",
")",
")",
",",
"toRadians",
"(",
"from",
".",
"getLongitude",
"(",
")"... | Returns the angle between two IGeoPoints, in radians. This is the same as the distance
on the unit sphere. | [
"Returns",
"the",
"angle",
"between",
"two",
"IGeoPoints",
"in",
"radians",
".",
"This",
"is",
"the",
"same",
"as",
"the",
"distance",
"on",
"the",
"unit",
"sphere",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L265-L268 | train |
osmdroid/osmdroid | osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java | SphericalUtil.computeLength | public static double computeLength(List<IGeoPoint> path) {
if (path.size() < 2) {
return 0;
}
double length = 0;
IGeoPoint prev = path.get(0);
double prevLat = toRadians(prev.getLatitude());
double prevLng = toRadians(prev.getLongitude());
for (IGeoPoint point : path) {
double lat = toRadians(point.getLatitude());
double lng = toRadians(point.getLongitude());
length += distanceRadians(prevLat, prevLng, lat, lng);
prevLat = lat;
prevLng = lng;
}
return length * EARTH_RADIUS;
} | java | public static double computeLength(List<IGeoPoint> path) {
if (path.size() < 2) {
return 0;
}
double length = 0;
IGeoPoint prev = path.get(0);
double prevLat = toRadians(prev.getLatitude());
double prevLng = toRadians(prev.getLongitude());
for (IGeoPoint point : path) {
double lat = toRadians(point.getLatitude());
double lng = toRadians(point.getLongitude());
length += distanceRadians(prevLat, prevLng, lat, lng);
prevLat = lat;
prevLng = lng;
}
return length * EARTH_RADIUS;
} | [
"public",
"static",
"double",
"computeLength",
"(",
"List",
"<",
"IGeoPoint",
">",
"path",
")",
"{",
"if",
"(",
"path",
".",
"size",
"(",
")",
"<",
"2",
")",
"{",
"return",
"0",
";",
"}",
"double",
"length",
"=",
"0",
";",
"IGeoPoint",
"prev",
"=",... | Returns the length of the given path, in meters, on Earth. | [
"Returns",
"the",
"length",
"of",
"the",
"given",
"path",
"in",
"meters",
"on",
"Earth",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L280-L296 | train |
osmdroid/osmdroid | osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java | SphericalUtil.computeSignedArea | static double computeSignedArea(List<IGeoPoint> path, double radius) {
int size = path.size();
if (size < 3) { return 0; }
double total = 0;
IGeoPoint prev = path.get(size - 1);
double prevTanLat = tan((PI / 2 - toRadians(prev.getLatitude())) / 2);
double prevLng = toRadians(prev.getLongitude());
// For each edge, accumulate the signed area of the triangle formed by the North Pole
// and that edge ("polar triangle").
for (IGeoPoint point : path) {
double tanLat = tan((PI / 2 - toRadians(point.getLatitude())) / 2);
double lng = toRadians(point.getLongitude());
total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
prevTanLat = tanLat;
prevLng = lng;
}
return total * (radius * radius);
} | java | static double computeSignedArea(List<IGeoPoint> path, double radius) {
int size = path.size();
if (size < 3) { return 0; }
double total = 0;
IGeoPoint prev = path.get(size - 1);
double prevTanLat = tan((PI / 2 - toRadians(prev.getLatitude())) / 2);
double prevLng = toRadians(prev.getLongitude());
// For each edge, accumulate the signed area of the triangle formed by the North Pole
// and that edge ("polar triangle").
for (IGeoPoint point : path) {
double tanLat = tan((PI / 2 - toRadians(point.getLatitude())) / 2);
double lng = toRadians(point.getLongitude());
total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng);
prevTanLat = tanLat;
prevLng = lng;
}
return total * (radius * radius);
} | [
"static",
"double",
"computeSignedArea",
"(",
"List",
"<",
"IGeoPoint",
">",
"path",
",",
"double",
"radius",
")",
"{",
"int",
"size",
"=",
"path",
".",
"size",
"(",
")",
";",
"if",
"(",
"size",
"<",
"3",
")",
"{",
"return",
"0",
";",
"}",
"double"... | Returns the signed area of a closed path on a sphere of given radius.
The computed area uses the same units as the radius squared.
Used by SphericalUtilTest. | [
"Returns",
"the",
"signed",
"area",
"of",
"a",
"closed",
"path",
"on",
"a",
"sphere",
"of",
"given",
"radius",
".",
"The",
"computed",
"area",
"uses",
"the",
"same",
"units",
"as",
"the",
"radius",
"squared",
".",
"Used",
"by",
"SphericalUtilTest",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-geopackage/src/main/java/org/osmdroid/gpkg/overlay/features/SphericalUtil.java#L323-L340 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java | TilesOverlay.protectDisplayedTilesForCache | public void protectDisplayedTilesForCache(final Canvas pCanvas, final Projection pProjection) {
if (!setViewPort(pCanvas, pProjection)) {
return;
}
TileSystem.getTileFromMercator(mViewPort, TileSystem.getTileSize(mProjection.getZoomLevel()), mProtectedTiles);
final int tileZoomLevel = TileSystem.getInputTileZoomLevel(mProjection.getZoomLevel());
mTileProvider.getTileCache().getMapTileArea().set(tileZoomLevel, mProtectedTiles);
mTileProvider.getTileCache().maintenance();
} | java | public void protectDisplayedTilesForCache(final Canvas pCanvas, final Projection pProjection) {
if (!setViewPort(pCanvas, pProjection)) {
return;
}
TileSystem.getTileFromMercator(mViewPort, TileSystem.getTileSize(mProjection.getZoomLevel()), mProtectedTiles);
final int tileZoomLevel = TileSystem.getInputTileZoomLevel(mProjection.getZoomLevel());
mTileProvider.getTileCache().getMapTileArea().set(tileZoomLevel, mProtectedTiles);
mTileProvider.getTileCache().maintenance();
} | [
"public",
"void",
"protectDisplayedTilesForCache",
"(",
"final",
"Canvas",
"pCanvas",
",",
"final",
"Projection",
"pProjection",
")",
"{",
"if",
"(",
"!",
"setViewPort",
"(",
"pCanvas",
",",
"pProjection",
")",
")",
"{",
"return",
";",
"}",
"TileSystem",
".",
... | Populates the tile provider's memory cache with the list of displayed tiles
@since 6.0.0 | [
"Populates",
"the",
"tile",
"provider",
"s",
"memory",
"cache",
"with",
"the",
"list",
"of",
"displayed",
"tiles"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java#L171-L179 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java | TilesOverlay.setViewPort | protected boolean setViewPort(final Canvas pCanvas, final Projection pProjection) {
setProjection(pProjection);
getProjection().getMercatorViewPort(mViewPort);
return true;
} | java | protected boolean setViewPort(final Canvas pCanvas, final Projection pProjection) {
setProjection(pProjection);
getProjection().getMercatorViewPort(mViewPort);
return true;
} | [
"protected",
"boolean",
"setViewPort",
"(",
"final",
"Canvas",
"pCanvas",
",",
"final",
"Projection",
"pProjection",
")",
"{",
"setProjection",
"(",
"pProjection",
")",
";",
"getProjection",
"(",
")",
".",
"getMercatorViewPort",
"(",
"mViewPort",
")",
";",
"retu... | Get the area we are drawing to
@since 6.0.0
@return true if the tiles are to be drawn | [
"Get",
"the",
"area",
"we",
"are",
"drawing",
"to"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java#L186-L190 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/util/StreamUtils.java | StreamUtils.closeStream | public static void closeStream(final Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (final IOException e) {
//don't use android classes here, since this class is used outside of android
e.printStackTrace();
}
}
} | java | public static void closeStream(final Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (final IOException e) {
//don't use android classes here, since this class is used outside of android
e.printStackTrace();
}
}
} | [
"public",
"static",
"void",
"closeStream",
"(",
"final",
"Closeable",
"stream",
")",
"{",
"if",
"(",
"stream",
"!=",
"null",
")",
"{",
"try",
"{",
"stream",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"IOException",
"e",
")",
"{",
"//don... | Closes the specified stream.
@param stream
The stream to close. | [
"Closes",
"the",
"specified",
"stream",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/util/StreamUtils.java#L76-L85 | train |
osmdroid/osmdroid | OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/events/SampleZoomToBounding.java | SampleZoomToBounding.addPoints | private void addPoints(final List<GeoPoint> pPoints,
final double pBeginLat, final double pBeginLon,
final double pEndLat, final double pEndLon) {
final double increment = 10; // in degrees
pPoints.add(new GeoPoint(pBeginLat, pBeginLon));
double lat = pBeginLat;
double lon = pBeginLon;
double incLat = pBeginLat == pEndLat ? 0 : pBeginLat < pEndLat ? increment : -increment;
double incLon = pBeginLon == pEndLon ? 0 : pBeginLon < pEndLon ? increment : -increment;
while (true) {
if (incLat != 0) {
lat += incLat;
if (incLat < 0) {
if (lat < pEndLat) {
break;
}
} else {
if (lat > pEndLat) {
break;
}
}
}
if (incLon != 0) {
lon += incLon;
if (incLon < 0) {
if (lon < pEndLon) {
break;
}
} else {
if (lon > pEndLon) {
break;
}
}
}
pPoints.add(new GeoPoint(lat, lon));
}
pPoints.add(new GeoPoint(pEndLat, pEndLon));
} | java | private void addPoints(final List<GeoPoint> pPoints,
final double pBeginLat, final double pBeginLon,
final double pEndLat, final double pEndLon) {
final double increment = 10; // in degrees
pPoints.add(new GeoPoint(pBeginLat, pBeginLon));
double lat = pBeginLat;
double lon = pBeginLon;
double incLat = pBeginLat == pEndLat ? 0 : pBeginLat < pEndLat ? increment : -increment;
double incLon = pBeginLon == pEndLon ? 0 : pBeginLon < pEndLon ? increment : -increment;
while (true) {
if (incLat != 0) {
lat += incLat;
if (incLat < 0) {
if (lat < pEndLat) {
break;
}
} else {
if (lat > pEndLat) {
break;
}
}
}
if (incLon != 0) {
lon += incLon;
if (incLon < 0) {
if (lon < pEndLon) {
break;
}
} else {
if (lon > pEndLon) {
break;
}
}
}
pPoints.add(new GeoPoint(lat, lon));
}
pPoints.add(new GeoPoint(pEndLat, pEndLon));
} | [
"private",
"void",
"addPoints",
"(",
"final",
"List",
"<",
"GeoPoint",
">",
"pPoints",
",",
"final",
"double",
"pBeginLat",
",",
"final",
"double",
"pBeginLon",
",",
"final",
"double",
"pEndLat",
",",
"final",
"double",
"pEndLon",
")",
"{",
"final",
"double"... | Add a succession of GeoPoint's, separated by an increment,
taken from the segment between two GeoPoint's
@since 6.0.0 | [
"Add",
"a",
"succession",
"of",
"GeoPoint",
"s",
"separated",
"by",
"an",
"increment",
"taken",
"from",
"the",
"segment",
"between",
"two",
"GeoPoint",
"s"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/events/SampleZoomToBounding.java#L120-L157 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/views/overlay/LinearRing.java | LinearRing.buildLinePortion | void buildLinePortion(final Projection pProjection,
final boolean pStorePoints){
final int size = mOriginalPoints.size();
if (size < 2) { // nothing to paint
return;
}
computeProjected(pProjection);
computeDistances();
final PointL offset = new PointL();
getBestOffset(pProjection, offset);
mSegmentClipper.init();
clipAndStore(pProjection, offset, false, pStorePoints, mSegmentClipper);
mSegmentClipper.end();
} | java | void buildLinePortion(final Projection pProjection,
final boolean pStorePoints){
final int size = mOriginalPoints.size();
if (size < 2) { // nothing to paint
return;
}
computeProjected(pProjection);
computeDistances();
final PointL offset = new PointL();
getBestOffset(pProjection, offset);
mSegmentClipper.init();
clipAndStore(pProjection, offset, false, pStorePoints, mSegmentClipper);
mSegmentClipper.end();
} | [
"void",
"buildLinePortion",
"(",
"final",
"Projection",
"pProjection",
",",
"final",
"boolean",
"pStorePoints",
")",
"{",
"final",
"int",
"size",
"=",
"mOriginalPoints",
".",
"size",
"(",
")",
";",
"if",
"(",
"size",
"<",
"2",
")",
"{",
"// nothing to paint"... | Dedicated to Polyline, as they can run much faster with drawLine than through a Path
@since 6.0.0 | [
"Dedicated",
"to",
"Polyline",
"as",
"they",
"can",
"run",
"much",
"faster",
"with",
"drawLine",
"than",
"through",
"a",
"Path"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/LinearRing.java#L207-L220 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/views/overlay/LinearRing.java | LinearRing.isCloseTo | boolean isCloseTo(final GeoPoint pPoint, final double tolerance,
final Projection pProjection, final boolean pClosePath) {
return getCloseTo(pPoint, tolerance, pProjection, pClosePath) != null;
} | java | boolean isCloseTo(final GeoPoint pPoint, final double tolerance,
final Projection pProjection, final boolean pClosePath) {
return getCloseTo(pPoint, tolerance, pProjection, pClosePath) != null;
} | [
"boolean",
"isCloseTo",
"(",
"final",
"GeoPoint",
"pPoint",
",",
"final",
"double",
"tolerance",
",",
"final",
"Projection",
"pProjection",
",",
"final",
"boolean",
"pClosePath",
")",
"{",
"return",
"getCloseTo",
"(",
"pPoint",
",",
"tolerance",
",",
"pProjectio... | Detection is done in screen coordinates.
@param tolerance in pixels
@return true if the Polyline is close enough to the point. | [
"Detection",
"is",
"done",
"in",
"screen",
"coordinates",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/views/overlay/LinearRing.java#L363-L366 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/tilesource/bing/ImageryMetaDataResource.java | ImageryMetaDataResource.getInstanceFromJSON | static public ImageryMetaDataResource getInstanceFromJSON(final JSONObject a_jsonObject, final JSONObject parent) throws Exception
{
final ImageryMetaDataResource result = new ImageryMetaDataResource();
if(a_jsonObject==null) {
throw new Exception("JSON to parse is null");
}
result.copyright = parent.getString(COPYRIGHT);
if(a_jsonObject.has(IMAGE_HEIGHT)) {
result.m_imageHeight = a_jsonObject.getInt(IMAGE_HEIGHT);
}
if(a_jsonObject.has(IMAGE_WIDTH)) {
result.m_imageWidth = a_jsonObject.getInt(IMAGE_WIDTH);
}
if(a_jsonObject.has(ZOOM_MIN)) {
result.m_zoomMin = a_jsonObject.getInt(ZOOM_MIN);
}
if(a_jsonObject.has(ZOOM_MAX)) {
result.m_zoomMax = a_jsonObject.getInt(ZOOM_MAX);
}
result.m_imageUrl = a_jsonObject.getString(IMAGE_URL);
if(result.m_imageUrl!=null && result.m_imageUrl.matches(".*?\\{.*?\\}.*?")) {
result.m_imageUrl = result.m_imageUrl.replaceAll("\\{.*?\\}", "%s");
}
final JSONArray subdomains = a_jsonObject.getJSONArray(IMAGE_URL_SUBDOMAINS);
if(subdomains!=null && subdomains.length()>=1)
{
result.m_imageUrlSubdomains = new String[subdomains.length()];
for(int i=0;i<subdomains.length();i++)
{
result.m_imageUrlSubdomains[i] = subdomains.getString(i);
}
}
result.m_isInitialised = true;
return result;
} | java | static public ImageryMetaDataResource getInstanceFromJSON(final JSONObject a_jsonObject, final JSONObject parent) throws Exception
{
final ImageryMetaDataResource result = new ImageryMetaDataResource();
if(a_jsonObject==null) {
throw new Exception("JSON to parse is null");
}
result.copyright = parent.getString(COPYRIGHT);
if(a_jsonObject.has(IMAGE_HEIGHT)) {
result.m_imageHeight = a_jsonObject.getInt(IMAGE_HEIGHT);
}
if(a_jsonObject.has(IMAGE_WIDTH)) {
result.m_imageWidth = a_jsonObject.getInt(IMAGE_WIDTH);
}
if(a_jsonObject.has(ZOOM_MIN)) {
result.m_zoomMin = a_jsonObject.getInt(ZOOM_MIN);
}
if(a_jsonObject.has(ZOOM_MAX)) {
result.m_zoomMax = a_jsonObject.getInt(ZOOM_MAX);
}
result.m_imageUrl = a_jsonObject.getString(IMAGE_URL);
if(result.m_imageUrl!=null && result.m_imageUrl.matches(".*?\\{.*?\\}.*?")) {
result.m_imageUrl = result.m_imageUrl.replaceAll("\\{.*?\\}", "%s");
}
final JSONArray subdomains = a_jsonObject.getJSONArray(IMAGE_URL_SUBDOMAINS);
if(subdomains!=null && subdomains.length()>=1)
{
result.m_imageUrlSubdomains = new String[subdomains.length()];
for(int i=0;i<subdomains.length();i++)
{
result.m_imageUrlSubdomains[i] = subdomains.getString(i);
}
}
result.m_isInitialised = true;
return result;
} | [
"static",
"public",
"ImageryMetaDataResource",
"getInstanceFromJSON",
"(",
"final",
"JSONObject",
"a_jsonObject",
",",
"final",
"JSONObject",
"parent",
")",
"throws",
"Exception",
"{",
"final",
"ImageryMetaDataResource",
"result",
"=",
"new",
"ImageryMetaDataResource",
"(... | Parse a JSON string containing resource field of a ImageryMetaData response
@param a_jsonObject the JSON content string
@return ImageryMetaDataResource object containing parsed information
@throws Exception | [
"Parse",
"a",
"JSON",
"string",
"containing",
"resource",
"field",
"of",
"a",
"ImageryMetaData",
"response"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/tilesource/bing/ImageryMetaDataResource.java#L55-L95 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/tilesource/bing/ImageryMetaDataResource.java | ImageryMetaDataResource.getSubDomain | public synchronized String getSubDomain()
{
if(m_imageUrlSubdomains==null || m_imageUrlSubdomains.length<=0) {
return null;
}
final String result = m_imageUrlSubdomains[m_subdomainsCounter];
if(m_subdomainsCounter<m_imageUrlSubdomains.length-1) {
m_subdomainsCounter++;
} else {
m_subdomainsCounter=0;
}
return result;
} | java | public synchronized String getSubDomain()
{
if(m_imageUrlSubdomains==null || m_imageUrlSubdomains.length<=0) {
return null;
}
final String result = m_imageUrlSubdomains[m_subdomainsCounter];
if(m_subdomainsCounter<m_imageUrlSubdomains.length-1) {
m_subdomainsCounter++;
} else {
m_subdomainsCounter=0;
}
return result;
} | [
"public",
"synchronized",
"String",
"getSubDomain",
"(",
")",
"{",
"if",
"(",
"m_imageUrlSubdomains",
"==",
"null",
"||",
"m_imageUrlSubdomains",
".",
"length",
"<=",
"0",
")",
"{",
"return",
"null",
";",
"}",
"final",
"String",
"result",
"=",
"m_imageUrlSubdo... | When several subdomains are available, get subdomain pointed by internal cycle counter on subdomains and increment this counter
@return the subdomain string associated to current counter value. | [
"When",
"several",
"subdomains",
"are",
"available",
"get",
"subdomain",
"pointed",
"by",
"internal",
"cycle",
"counter",
"on",
"subdomains",
"and",
"increment",
"this",
"counter"
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/tilesource/bing/ImageryMetaDataResource.java#L101-L115 | train |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/tileprovider/tilesource/TileSourceFactory.java | TileSourceFactory.getTileSource | public static ITileSource getTileSource(final String aName) throws IllegalArgumentException {
for (final ITileSource tileSource : mTileSources) {
if (tileSource.name().equals(aName)) {
return tileSource;
}
}
throw new IllegalArgumentException("No such tile source: " + aName);
} | java | public static ITileSource getTileSource(final String aName) throws IllegalArgumentException {
for (final ITileSource tileSource : mTileSources) {
if (tileSource.name().equals(aName)) {
return tileSource;
}
}
throw new IllegalArgumentException("No such tile source: " + aName);
} | [
"public",
"static",
"ITileSource",
"getTileSource",
"(",
"final",
"String",
"aName",
")",
"throws",
"IllegalArgumentException",
"{",
"for",
"(",
"final",
"ITileSource",
"tileSource",
":",
"mTileSources",
")",
"{",
"if",
"(",
"tileSource",
".",
"name",
"(",
")",
... | Get the tile source with the specified name. The tile source must be one of the registered sources
as defined in the static list mTileSources of this class.
@param aName
the tile source name
@return the tile source
@throws IllegalArgumentException
if tile source not found | [
"Get",
"the",
"tile",
"source",
"with",
"the",
"specified",
"name",
".",
"The",
"tile",
"source",
"must",
"be",
"one",
"of",
"the",
"registered",
"sources",
"as",
"defined",
"in",
"the",
"static",
"list",
"mTileSources",
"of",
"this",
"class",
"."
] | 3b178b2f078497dd88c137110e87aafe45ad2b16 | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/tileprovider/tilesource/TileSourceFactory.java#L30-L37 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.