Skip to content

Instantly share code, notes, and snippets.

@bdsaglam
bdsaglam / Singleton.kt
Created September 9, 2019 07:52
Kotlin Singleton with initialization parameters
class Singleton private constructor(application: Application) {
companion object {
@Volatile
private var INSTANCE: Singleton? = null
fun getInstance(application: Application): Singleton =
INSTANCE ?: synchronized(this) {
INSTANCE
?: Singleton(application).also { INSTANCE = it }
}
@bdsaglam
bdsaglam / LiveDataExtensions.kt
Created September 23, 2019 07:16
LiveData with explicit notify
// https://stackoverflow.com/a/52075248/6641096
fun <T> MutableLiveData<T>.notifyObserver() {
this.value = this.value
}
// Usage
fun addSomething(item: Item) {
listLiveData.value?.add(item)
listLiveData.notifyObserver()
@bdsaglam
bdsaglam / batch.py
Last active September 23, 2019 09:39
Iterate by batches
def batch(iterable, size, drop_remainder=False):
if size < 1:
raise ValueError("size must be greater than zero.")
iterator = iter(iterable)
while True:
try:
items = []
for _ in range(size):
items.append(next(iterator))
@bdsaglam
bdsaglam / LiveChange.kt
Created September 24, 2019 13:53
a LiveData only notifies when its value changes
class LiveChange<T>(val source: LiveData<T>, ignoreFirst: Boolean = false) : MediatorLiveData<T>() {
private var shouldIgnoreNext: Boolean = ignoreFirst
init {
addSource(source) {
if (shouldIgnoreNext) {
shouldIgnoreNext = false
} else {
if (value != it) value = it
}
@bdsaglam
bdsaglam / renewing.py
Created September 25, 2019 12:29
Make a generator not exhaust
import functools
def renewing(generator):
"""
A decorator to turn a generator into an object that can be
iterated multiple times, restarting the generator each time.
"""
class RenewingGenerator:
def __init__(self, *args, **kwargs):
self.args = args
@bdsaglam
bdsaglam / NumericDict.py
Last active October 23, 2019 12:45
A wrapper for dictionaries with numeric values
_numeric_types = (int, float, complex)
class NumericDict(dict):
def __add__(self, other):
if isinstance(other, _numeric_types):
return self.apply(lambda v: v + other)
if isinstance(other, NumericDict):
return self.__class__({k: v + other.get(k, 0) for k, v in self.items()})
@bdsaglam
bdsaglam / non_max_suppress.py
Last active October 25, 2019 10:18
Generic non-max suppression
# items must be sorted from best to worst
def non_max_suppress(items_sorted, suppress_predicate):
num_items = len(items_sorted)
skip = [False]*num_items
i = 0
while i < num_items:
if skip[i]:
i += 1
continue
@bdsaglam
bdsaglam / joinGrammatically.swift
Created October 31, 2019 07:09
Join words like human
/// It joins words grammatically e.g. ["apple", "orange", "banana"] -> "apple, orange and banana"
/// and parameter is required to support different languages
func joinGrammatically(words: [String], and: String) -> String {
if words.count == 0 {
return ""
}
else if words.count == 1 {
return words.first!
}
else {
@bdsaglam
bdsaglam / callBlocking.swift
Last active November 11, 2019 12:03
Make an asynchronous function blocking
func callBlocking<T>(
_ closure: @escaping (_ continuationHandler: @escaping (T) -> Void ) -> Void )
-> T {
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
var result:T? = nil
closure { res in
result = res
dispatchGroup.leave()
@bdsaglam
bdsaglam / measureInMilliseconds.swift
Created November 3, 2019 13:29
Measure execution time in milliseconds
// implemented according to this answer
// https://stackoverflow.com/a/24755958/6641096
func measureInMilliseconds(_ block: () -> ()) -> UInt64 {
let start = DispatchTime.now()
block()
let end = DispatchTime.now()
// Difference in nano seconds (UInt64)
let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds