Skip to content

Instantly share code, notes, and snippets.

Avatar
😎
Swift, Java, Kotlin

Charles Muchene charlesmuchene

😎
Swift, Java, Kotlin
View GitHub Profile
@charlesmuchene
charlesmuchene / statuscode.swift
Created Jul 20, 2020
Sample status code entity
View statuscode.swift
struct StatusCode: CustomStringConvertible, Equatable {
let code: Int
var description: String
static let ok = StatusCode(code: 200, description: "Success")
static let unauthorized = StatusCode(code: 403, description: "Unauthorized")
static let invalidCredentials = StatusCode(code: 401, description: "Invalid credentials")
static func == (lhs: Int, rhs: StatusCode) -> Bool {
View apierror.swift
struct APIError: Error, Decodable, CustomStringConvertible {
let code: Int
let message: String
let errors: [String] = [] // May be dictionary??
static let genericResponseError = APIError(code: 500, message: "Error getting response")
static let noResponseError = APIError(code: 500, message: "No response from server")
View scrollviewinsets.swift
let scrollView = UIScrollView()
scrollView.backgroundColor = .systemGreen
scrollView.contentInset = UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100)
scrollView.contentSize = self.view.bounds.size
scrollView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(scrollView)
let views = ["scrollview": scrollView]
NSLayoutConstraint.activate([
NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollview]|", metrics: nil, views: views),
@charlesmuchene
charlesmuchene / peripheral-delegate.swift
Last active Apr 17, 2020
iOS as Central - peripheral delegate
View peripheral-delegate.swift
// Implement peripheral callback methods
extension SocialService: CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
// Discover characteristics
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
// Request for TraceCharacteristic value -- TraceToken
}
View central.swift
// Initialize central manager, set self as delegate
centralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: TraceService.CMRestoreIdentifierKey])
// Provide implementation for delegate callback methods
extension TraceService: CBCentralManagerDelegate {
func centralManager(_ central: CBCentralManager, willRestoreState dict: [String: Any]) { ... }
func centralManagerDidUpdateState(_ central: CBCentralManager) {
// When .poweredOn, scan for Peripherals
@charlesmuchene
charlesmuchene / peripheral.kt
Last active Apr 17, 2020
Android Gatt server - Peripheral
View peripheral.kt
// Starts GattServer to serve remote Central requests
private val gattServer: BluetoothGattServer by lazyNone {
bluetoothManager.openGattServer(this.applicationContext, GattServerCallback())
}
private class GattServerCallback : BluetoothGattServerCallback() {
override fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) { ... }
override fun onCharacteristicReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, characteristic: BluetoothGattCharacteristic) {
@charlesmuchene
charlesmuchene / advertise.kt
Created Apr 17, 2020
Android as Peripheral - Advertising
View advertise.kt
// Advertisement data: only has Trace UUID to enable filtering
val advertiseData: AdvertiseData = AdvertiseData.Builder()
.addServiceUuid(Services.TRACE.serviceUUID)
.build()
// Advertise
bleAdvertiser.startAdvertising(advertiseSettings, advertiseData, adCallback)
// Advertisement callback - delivers advertising operation status
private inner class AdCallback : AdvertiseCallback() {
@charlesmuchene
charlesmuchene / lazynone.kt
Created Apr 16, 2020
A function to create an un-synchronized lazy initialization of a property
View lazynone.kt
/**
* Initialize lazily without thread synchronization
*
* @param initializer Initializer block
* @return [Lazy] instance
*/
fun <T> lazyNone(initializer: () -> T): Lazy<T> = lazy(LazyThreadSafetyMode.NONE, initializer)
View handlerthreadusage.kt
class NQueensActivity : AppCompatActivity() {
private val handlerThread = HandlerThread("NQueens").also { it.start() }
private val handler = Handler(handlerThread.looper)
private var queens = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
solveButton.setOnClickListener {
@charlesmuchene
charlesmuchene / thread.kt
Created Apr 4, 2020
Thread with an indefinite loop
View thread.kt
fun seriousWork() = thread(name = "Worker") {
while (!Thread.currentThread().isInterrupted) {
// Perform Genetic Sequencing
}
}