Skip to content

Instantly share code, notes, and snippets.

@nieldeokar
Last active October 29, 2023 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nieldeokar/770b85ee296a9675e3cbbd63347981a5 to your computer and use it in GitHub Desktop.
Save nieldeokar/770b85ee296a9675e3cbbd63347981a5 to your computer and use it in GitHub Desktop.
Boilerplate code snippets.

Boilerplate

contains common code snippets.

Android Libraries

coroutines:

implementation 'androidx.fragment:fragment:1.4.1'
implementation 'androidx.fragment:fragment-ktx:1.4.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.0-rc01'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1'

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'
implementation 'com.squareup.retrofit2:converter-scalars:2.7.1'

reading response from http connection

fun getData(url: String) : Result<String> {

        val urlObj = URL(url)
        (urlObj.openConnection() as? HttpURLConnection)?.run {
            requestMethod = "GET"
            val reader = BufferedReader(InputStreamReader(inputStream))
            val result = StringBuffer()
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                result.append(line)
            }

            return Result.Success(result.toString())
        }
        return Result.Error(Exception("Cannot open HttpURLConnection"))
    }
    }
    
    sealed class Result<out R> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}
        

Directions array

int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};

int[][] dirs = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};

Reverse array

void reverse(int[] nums){
    int i = 0;
    int j = nums.length - 1;
    while(i < j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

PriorityQueue with Key Value Pair

// usage - PriorityQueue<MapTypePQ<Integer, int[]>> maxQue = new PriorityQueue<>((a,b) -> b.key - a.key);
// PriorityQueue<MapTypePQ<Integer, int[]>> minQue = new PriorityQueue<>((a,b) -> a.key - b.key);

class MapTypePQ<T,K> {
        public T key;
        public K value;
        
        public MapTypePQ(T key, K value){
            this.key = key;
            this.value = value;
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment