path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/example/administrator/buildings/Building.kt
YouerSu
136,327,071
false
{"Kotlin": 41755, "Java": 7860}
package com.example.administrator.buildings import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.util.Log import com.example.administrator.character.Employee import com.example.administrator.item.Item import com.example.administrator.item.Tool import com.example.administrator.utils.Info import com.example.administrator.utils.Sql import android.content.ContentValues.TAG import java.util.* class Building(var name: String, var capacity: Int, var master: String?){ var items = HashMap<String, Item>() val employees = ArrayList<Employee>() init { buildings.add(this) } private fun saveBuildingDate() { Log.i(TAG, "saveBuildingDate: count") createNewBuilding(Sql.getDateBase()) for (item in items.values) item.saveIndexDate(name) } fun addEmployee(employee: Employee) { employee.workSpace = name employees.add(employee) } fun findWorker(item: Item): Employee? { for (employee in employees) if (employee.receive(item)) return employee return null } private fun createNewBuilding(db: SQLiteDatabase) { Item.createIndex(name) db.execSQL("insert into " + Info.BUILDING + " (" + Info.NAME + "," + Info.MASTER + "," + Info.capacity + ") values ('" + name + "','" + master + "'," + capacity + ")") } companion object { var buildings = LinkedList<Building>() fun saveDate() { Sql.operating(arrayOf("DELETE FROM " + Info.BUILDING)) for (building in getBuildings()) building.saveBuildingDate() } fun findWorkSpace(workSpace: String): Building{ for (building in buildings) if (building.name == workSpace) return building error("$workSpace No Found") } fun getDate() { val iDate = Sql.getAllInfo(Info.BUILDING) ?: return while (iDate.moveToNext()) { Log.i(TAG, "getBuildingDate: count") val building = Building(iDate.getString(iDate.getColumnIndex(Info.NAME)), iDate.getInt(iDate.getColumnIndex(Info.capacity)), iDate.getString(iDate.getColumnIndex(Info.MASTER))) building.items = Item.getIndexDate(building.name) } iDate.close() } fun getWhere(x: Int): Building { return buildings.get(x) } fun getBuildings(): List<Building> { return buildings } } }
0
Kotlin
0
0
9c15d254a4d232434dd4e8cc55bc43523e86185f
2,537
PineLeafTownStory
MIT License
domain/src/main/java/ru/rznnike/eyehealthmanager/domain/model/DaltonismTestQuestionsMap.kt
RznNike
207,148,781
false
{"Kotlin": 539909}
package ru.rznnike.eyehealthmanager.domain.model import ru.rznnike.eyehealthmanager.domain.R import ru.rznnike.eyehealthmanager.domain.model.enums.DaltonismAnomalyType object DaltonismTestQuestionsMap { val questions: Map<Int, DaltonismTestQuestion> = mapOf( 0 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_1, answerResIds = listOf( R.string.rabkin_96, R.string.rabkin_9, R.string.rabkin_80, R.string.rabkin_86 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(0), DaltonismAnomalyType.DEITERANOPIA to listOf(0) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to true, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to true, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to true ) ), 1 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_2, answerResIds = listOf( R.string.rabkin_circle_and_triangle, R.string.rabkin_circle, R.string.rabkin_triangle, R.string.rabkin_square ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(0), DaltonismAnomalyType.DEITERANOPIA to listOf(0) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to true, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to true, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to true ) ), 2 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_3, answerResIds = listOf( R.string.rabkin_9, R.string.rabkin_5, R.string.rabkin_3, R.string.rabkin_8 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1), DaltonismAnomalyType.DEITERANOPIA to listOf(1) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to false, DaltonismAnomalyType.PATHOLOGY to true ) ), 3 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_4, answerResIds = listOf( R.string.rabkin_triangle, R.string.rabkin_circle, R.string.rabkin_square, R.string.rabkin_circle_and_triangle ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1), DaltonismAnomalyType.DEITERANOPIA to listOf(1) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to false, DaltonismAnomalyType.PATHOLOGY to false ) ), 4 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_5, answerResIds = listOf( R.string.rabkin_13, R.string.rabkin_6, R.string.rabkin_8, R.string.rabkin_2 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1), DaltonismAnomalyType.DEITERANOPIA to listOf(1) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to false, DaltonismAnomalyType.PATHOLOGY to false ) ), 5 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_6, answerResIds = listOf( R.string.rabkin_circle_and_triangle, R.string.rabkin_circle, R.string.rabkin_triangle, R.string.rabkin_nothing ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(3), DaltonismAnomalyType.DEITERANOPIA to listOf(3) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to false, DaltonismAnomalyType.PATHOLOGY to false ) ), 6 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_7, answerResIds = listOf( R.string.rabkin_96, R.string.rabkin_9, R.string.rabkin_6, R.string.rabkin_nothing ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(0), DaltonismAnomalyType.DEITERANOPIA to listOf(2) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to true, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 7 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_8, answerResIds = listOf( R.string.rabkin_5, R.string.rabkin_6, R.string.rabkin_8, R.string.rabkin_9 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(0), DaltonismAnomalyType.DEITERANOPIA to listOf(0) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to true, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to true, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 8 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_9, answerResIds = listOf( R.string.rabkin_9, R.string.rabkin_6, R.string.rabkin_8, R.string.rabkin_5 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1, 2), DaltonismAnomalyType.DEITERANOPIA to listOf(0) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to true, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to true ) ), 9 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_10, answerResIds = listOf( R.string.rabkin_136, R.string.rabkin_66, R.string.rabkin_68, R.string.rabkin_69 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(2, 3), DaltonismAnomalyType.DEITERANOPIA to listOf(1, 3) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to false, DaltonismAnomalyType.PATHOLOGY to false ) ), 10 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_11, answerResIds = listOf( R.string.rabkin_circle_and_triangle, R.string.rabkin_circle, R.string.rabkin_triangle, R.string.rabkin_square ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(2), DaltonismAnomalyType.DEITERANOPIA to listOf(0, 1) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to true, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to true ) ), 11 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_12, answerResIds = listOf( R.string.rabkin_12, R.string.rabkin_13, R.string.rabkin_8, R.string.rabkin_nothing ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(3), DaltonismAnomalyType.DEITERANOPIA to listOf(0) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to true, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 12 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_13, answerResIds = listOf( R.string.rabkin_circle_and_triangle, R.string.rabkin_circle, R.string.rabkin_triangle, R.string.rabkin_square ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1), DaltonismAnomalyType.DEITERANOPIA to listOf(2) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to true ) ), 13 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_14, answerResIds = listOf( R.string.rabkin_30, R.string.rabkin_106, R.string.rabkin_16, R.string.rabkin_18 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1), DaltonismAnomalyType.DEITERANOPIA to listOf(2) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to false, DaltonismAnomalyType.PATHOLOGY to false ) ), 14 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_15, answerResIds = listOf( R.string.rabkin_circle_and_triangle, R.string.rabkin_triangle, R.string.rabkin_triangle_and_square, R.string.rabkin_square ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1, 2), DaltonismAnomalyType.DEITERANOPIA to listOf(2) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to false, DaltonismAnomalyType.PATHOLOGY to false ) ), 15 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_16, answerResIds = listOf( R.string.rabkin_96, R.string.rabkin_9, R.string.rabkin_6, R.string.rabkin_nothing ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1), DaltonismAnomalyType.DEITERANOPIA to listOf(2) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 16 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_17, answerResIds = listOf( R.string.rabkin_circle_and_triangle, R.string.rabkin_circle, R.string.rabkin_triangle, R.string.rabkin_square ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(2), DaltonismAnomalyType.DEITERANOPIA to listOf(1) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 17 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_18, answerResIds = listOf( R.string.rabkin_horizontal_lines, R.string.rabkin_vertical_lines, R.string.rabkin_diagonal_lines, R.string.rabkin_no_color_lines ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1), DaltonismAnomalyType.DEITERANOPIA to listOf(1) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to true ) ), 18 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_19, answerResIds = listOf( R.string.rabkin_95, R.string.rabkin_5, R.string.rabkin_96, R.string.rabkin_6 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1), DaltonismAnomalyType.DEITERANOPIA to listOf(1) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to true, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to true ) ), 19 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_20, answerResIds = listOf( R.string.rabkin_circle_and_triangle, R.string.rabkin_circle, R.string.rabkin_triangle_and_square, R.string.rabkin_nothing ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(3), DaltonismAnomalyType.DEITERANOPIA to listOf(3) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to false, DaltonismAnomalyType.PATHOLOGY to false ) ), 20 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_21, answerResIds = listOf( R.string.rabkin_vertical_lines, R.string.rabkin_horizontal_lines, R.string.rabkin_diagonal_lines, R.string.rabkin_no_color_lines ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1), DaltonismAnomalyType.DEITERANOPIA to listOf(1) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 21 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_22, answerResIds = listOf( R.string.rabkin_66, R.string.rabkin_6, R.string.rabkin_96, R.string.rabkin_69 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(1), DaltonismAnomalyType.DEITERANOPIA to listOf(1) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to false, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 22 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_23, answerResIds = listOf( R.string.rabkin_36, R.string.rabkin_66, R.string.rabkin_96, R.string.rabkin_69 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(0), DaltonismAnomalyType.DEITERANOPIA to listOf(0) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to true, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to true, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 23 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_24, answerResIds = listOf( R.string.rabkin_14, R.string.rabkin_4, R.string.rabkin_16, R.string.rabkin_nothing ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(0), DaltonismAnomalyType.DEITERANOPIA to listOf(0) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to true, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to true, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 24 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_25, answerResIds = listOf( R.string.rabkin_9, R.string.rabkin_6, R.string.rabkin_96, R.string.rabkin_69 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(0), DaltonismAnomalyType.DEITERANOPIA to listOf(0) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to true, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to true, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 25 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_26, answerResIds = listOf( R.string.rabkin_4, R.string.rabkin_14, R.string.rabkin_16, R.string.rabkin_5 ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(0), DaltonismAnomalyType.DEITERANOPIA to listOf(0) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to true, DaltonismAnomalyType.PROTANOMALY_B to true, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to true, DaltonismAnomalyType.DEITERANOMALY_B to true, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ), 26 to DaltonismTestQuestion( testImageResId = R.drawable.rabkin_27, answerResIds = listOf( R.string.rabkin_13, R.string.rabkin_136, R.string.rabkin_8, R.string.rabkin_nothing ), answerVariantsMap = mapOf( DaltonismAnomalyType.PROTANOPIA to listOf(3), DaltonismAnomalyType.DEITERANOPIA to listOf(3) ), answerBooleanMap = mapOf( DaltonismAnomalyType.PROTANOMALY_A to false, DaltonismAnomalyType.PROTANOMALY_B to false, DaltonismAnomalyType.PROTANOMALY_C to true, DaltonismAnomalyType.DEITERANOMALY_A to false, DaltonismAnomalyType.DEITERANOMALY_B to false, DaltonismAnomalyType.DEITERANOMALY_C to true, DaltonismAnomalyType.PATHOLOGY to false ) ) ) }
0
Kotlin
0
0
6f319237d56f99a836fe3481efd32908e28c3d56
26,233
EyeHealthManager
MIT License
library/src/main/kotlin/me/proxer/library/entity/user/UserHistoryEntry.kt
proxer
43,981,937
false
{"Kotlin": 492567}
package me.proxer.library.entity.ucp import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import me.proxer.library.entity.ProxerDateItem import me.proxer.library.entity.ProxerIdItem import me.proxer.library.enums.Category import me.proxer.library.enums.MediaLanguage import me.proxer.library.enums.Medium import java.util.Date /** * Entity representing a single entry in the history list. * * @property entryId The id of the associated [me.proxer.library.entity.info.Entry]. * @property name The name. * @property language The language. * @property medium The medium. * @property category The category. * @property episode The episode. * * @author <NAME> */ @JsonClass(generateAdapter = true) data class UcpHistoryEntry( @Json(name = "id") override val id: String, @Json(name = "eid") val entryId: String, @Json(name = "name") val name: String, @Json(name = "language") val language: MediaLanguage, @Json(name = "medium") val medium: Medium, @Json(name = "kat") val category: Category, @Json(name = "episode") val episode: Int, @Json(name = "timestamp") override val date: Date ) : ProxerIdItem, ProxerDateItem
0
Kotlin
2
13
f55585b485c8eff6da944032690fe4de40a58e65
1,170
ProxerLibJava
MIT License
client/app/src/main/java/com/healthc/app/presentation/auth/login/LoginFragment.kt
Team-HealthC
601,915,784
false
{"Kotlin": 175023}
package com.healthc.app.presentation.auth.login import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.healthc.app.R import com.healthc.app.databinding.FragmentLoginBinding import com.healthc.app.presentation.auth.AuthViewModel import com.healthc.app.presentation.auth.AuthViewModel.AuthEvent import com.healthc.app.presentation.main.MainActivity import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach @AndroidEntryPoint class LoginFragment : Fragment() { private var _binding: FragmentLoginBinding? = null private val binding get() = requireNotNull(_binding) private val viewModel by activityViewModels<AuthViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false) binding.viewModel = viewModel binding.lifecycleOwner = viewLifecycleOwner return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observeData() initView() } private fun observeData(){ viewModel.signInEvent.flowWithLifecycle(viewLifecycleOwner.lifecycle) .onEach { when(it){ is AuthEvent.Success -> { startMainActivity() } is AuthEvent.Failure -> { Toast.makeText(requireContext(), "로그인에 실패하였습니다.", Toast.LENGTH_SHORT).show() } } }.launchIn(viewLifecycleOwner.lifecycleScope) } private fun initView(){ binding.goToSignUpButton.setOnClickListener { navigateSignUp() } viewModel.clearUserInput() } private fun navigateSignUp(){ val direction = LoginFragmentDirections.actionLoginFragmentToRegisterInformationFragment() findNavController().navigate(direction) } private fun startMainActivity(){ val intent = Intent(requireContext(), MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) } override fun onDestroyView() { _binding = null super.onDestroyView() } }
17
Kotlin
1
2
6e392aa1ed937bef5fd79abc6fe7653b2bad7bf9
2,819
HealthC_Android
MIT License
app/src/main/java/com/fourteenrows/p2pcs/model/database/ModelDatabase.kt
FourteenRows
185,977,617
false
null
package com.fourteenrows.p2pcs.model.database import com.fourteenrows.p2pcs.model.database.reservation.ReservationRequestToDB import com.fourteenrows.p2pcs.objects.boosters.ActiveBoosterToDB import com.fourteenrows.p2pcs.objects.cars.FetchedVehicle import com.fourteenrows.p2pcs.objects.cars.Vehicle import com.fourteenrows.p2pcs.objects.items.ItemAvatar import com.fourteenrows.p2pcs.objects.reservations.Reservation import com.fourteenrows.p2pcs.objects.trips.ToDatabaseTrip import com.fourteenrows.p2pcs.objects.user.User import com.google.android.gms.tasks.Task import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseUser import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.QuerySnapshot import java.util.* interface ModelDatabase { fun activateBooster(bid: String, quantity: Long): Task<Void> fun addEmailData(email: String): Task<Void> fun addUserData(uid: String?, name: String, surname: String, email: String): Task<Void> fun authenticateUser(email: String, pwd: String): Task<AuthResult> fun buildUser(it: DocumentSnapshot): User fun changeQuest(newQuest: String, qid: String): Task<Void> fun checkNewPlate(plate: String): Task<QuerySnapshot> fun deactivateBooster(bid: String): Task<Void> fun delete(collection: String, document: String): Task<Void> fun editVehicle(car: FetchedVehicle): Task<Void> fun fetchBusyVehicleOf(date: Long, timeSlot: String): Task<QuerySnapshot> fun fetchAvailableVehicles(date: Date): Task<QuerySnapshot> fun fetchItemShop(): Task<QuerySnapshot> fun fetchUsers(email: String): Task<QuerySnapshot> fun getActiveQuests(): Task<QuerySnapshot> fun getCarReservations(carId: String): Task<QuerySnapshot> fun getCurrentUser(): FirebaseUser? fun getQuest(quest: String): Task<DocumentSnapshot> fun getReservation(rid: String): Task<DocumentSnapshot> fun getTrips(): Task<QuerySnapshot> fun getUid(): String? fun getUserBoosters(): Task<QuerySnapshot> fun getUserBoostersWithBID(bid: String): Task<DocumentSnapshot> fun getUserDocument(): Task<DocumentSnapshot> fun getUserVehicles(): Task<QuerySnapshot> fun insert(collection: String, document: String = "", obj: Any): Task<Void> fun insertQuest(newQuest: String, uid: String?): Task<Void> fun insertReservation(reservation: Reservation): Task<Void> fun insertVehicle(car: Vehicle): Task<DocumentReference> fun insertUser(email: String, pwd: String): Task<AuthResult> fun isEmailRegistered(email: String): Task<QuerySnapshot> fun isEmailVerified(): Boolean fun removeUserBooster(bid: String): Task<Void> fun sendResetEmail(email: String) fun sendResetEmailKnown(): Task<Void> fun sendVerificationEmail() fun signOut() fun updateField(field: String, value: Any): Task<Void> fun updateLongUserField(field: String, value: Long): Task<Void> fun getOwnedAvatarParts(): Task<QuerySnapshot> fun fetchAvatarPieces(): Task<QuerySnapshot> fun getBoosters(): Task<QuerySnapshot> fun addOwnershipAvatar(iid: String, itemAvatarToDB: ItemAvatar) fun addOwnershipBooster(iid: String, itemBoosterToDB: ActiveBoosterToDB): Task<Void> fun updateBoosterQuantity(bid: String, quantity: Long): Task<Void> fun updateStringUserField(field: String, value: String): Task<Void> fun getUidFromEmail(userEMail: String): Task<QuerySnapshot> fun getActiveBoosters(): Task<QuerySnapshot> fun addUserPoints(exp: Long, gaiaCoins: Long, weekPoints: Long) fun addTripData(trip: ToDatabaseTrip): Task<DocumentReference> fun getActivePrenotation(): Task<QuerySnapshot> fun getCarActiveReservations(cid: String): Task<QuerySnapshot> fun updateProgressQuest(qid: String, progress: Long): Task<Void> fun resetLastFreeChangeQuest(): Task<Void> fun getCar(cid: String): Task<DocumentSnapshot> fun pastChangeQuest(): Task<Void> fun getBox(box: String): Task<DocumentSnapshot> fun getAvatarItem(item: String): Task<DocumentSnapshot> fun getBooster(booster: String): Task<DocumentSnapshot> fun fetchLeaderboard(): Task<QuerySnapshot> fun deleteReservation(rid: String): Task<Void> fun hideTrip(tid: String): Task<Void> fun updateCarField(cid: String, field: String, input: Any): Task<Void> fun getOwner(owner: String): Task<DocumentSnapshot> fun addReservationRequest(carId: String, reservationRequest: ReservationRequestToDB): Task<Void> fun accept(rid: String): Task<Void> fun reject(rid: String): Task<Void> fun getUserRequests(): Task<QuerySnapshot> fun removeRequest(id: String): Task<Void> fun getReservationOf(date: Date): Task<QuerySnapshot> fun getCars(): Task<QuerySnapshot> }
0
Kotlin
0
0
b88364cb6775aa24ef005845943d1086a7f76bbe
4,873
P2PCS
MIT License
app/src/main/java/com/sergiolopez/runningpacecalculator/view/result/ResulPaceViewModel.kt
sergiolpzgmz
687,035,641
false
{"Kotlin": 22356}
package com.sergiolopez.runningpacecalculator.view.result import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.sergiolopez.runningpacecalculator.model.RunPaceModel class ResulPaceViewModel : ViewModel() { val resultPace = MutableLiveData<Double>(0.0) fun calculatePace(distance:Int, hours:Double, minutes:Double, seconds:Double) { val runPaceObject: RunPaceModel = RunPaceModel(distance,hours,minutes,seconds) resultPace.value = runPaceObject.calculatePace() } }
0
Kotlin
0
1
0645ad91409e67b23c1db49b32c2fe304a7796ee
528
running-pace-calculator-android
Apache License 2.0
app/src/main/java/com/berkaykurtoglu/worktracker/data/di/AppModule.kt
BerkayyKurtoglu
678,305,681
false
{"Kotlin": 175019}
package com.berkaykurtoglu.worktracker.data.di import com.berkaykurtoglu.worktracker.data.FriendsTaskRepository import com.berkaykurtoglu.worktracker.data.MainRepository import com.berkaykurtoglu.worktracker.data.NoteInputRepository import com.berkaykurtoglu.worktracker.data.SearchRepository import com.berkaykurtoglu.worktracker.data.SignInRepository import com.berkaykurtoglu.worktracker.data.TaskDetailRepository import com.berkaykurtoglu.worktracker.data.TaskItemViewRepository import com.berkaykurtoglu.worktracker.data.YourTaskRepository import com.berkaykurtoglu.worktracker.domain.usecases.AddACommentUseCase import com.berkaykurtoglu.worktracker.domain.usecases.AddATask import com.berkaykurtoglu.worktracker.domain.usecases.CurrentUserUseCase import com.berkaykurtoglu.worktracker.domain.usecases.DeleteATask import com.berkaykurtoglu.worktracker.domain.usecases.GetCurrentUsersMarkedTasksUseCase import com.berkaykurtoglu.worktracker.domain.usecases.GetCurrentUsersUnmarkedTasksUseCase import com.berkaykurtoglu.worktracker.domain.usecases.GetFriendsTasksMarkedUseCase import com.berkaykurtoglu.worktracker.domain.usecases.GetFriendsUnmarkedTasksUseCase import com.berkaykurtoglu.worktracker.domain.usecases.GetTaskDetailUseCase import com.berkaykurtoglu.worktracker.domain.usecases.GetTasksOnceUseCase import com.berkaykurtoglu.worktracker.domain.usecases.GetUserInfo import com.berkaykurtoglu.worktracker.domain.usecases.MarkAsDoneUseCase import com.berkaykurtoglu.worktracker.domain.usecases.SearchTasksUseCase import com.berkaykurtoglu.worktracker.domain.usecases.SignInUseCase import com.berkaykurtoglu.worktracker.domain.usecases.SignOutUseCase import com.berkaykurtoglu.worktracker.domain.usecases.UseCases import com.google.firebase.ktx.Firebase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Singleton @Provides fun provideFirebase( ) : Firebase = Firebase @Singleton @Provides fun provideSignInRepo( firebase : Firebase, ) : SignInRepository = SignInRepository(firebase) @Singleton @Provides fun provideMainRepository( firebase: Firebase ) : MainRepository = MainRepository(firebase) @Singleton @Provides fun provideYourTaskRepository( firebase: Firebase ) : YourTaskRepository = YourTaskRepository(firebase) @Singleton @Provides fun provideNoteInputRepository( firebase: Firebase ) : NoteInputRepository = NoteInputRepository(firebase) @Singleton @Provides fun provideFriendsTaskRepository( firebase: Firebase ) : FriendsTaskRepository = FriendsTaskRepository(firebase) @Singleton @Provides fun provideTaskDetailRepository( firebase: Firebase ) : TaskDetailRepository = TaskDetailRepository(firebase) @Singleton @Provides fun provideSearchRepository( firebase: Firebase ) : SearchRepository = SearchRepository(firebase) @Singleton @Provides fun provideTaskItemRepository( firebase: Firebase ) : TaskItemViewRepository = TaskItemViewRepository(firebase) @Singleton @Provides fun provideUseCases( signInRepository: SignInRepository, noteInputRepository: NoteInputRepository, yourTaskRepository: YourTaskRepository, friendsTaskRepository: FriendsTaskRepository, taskDetailRepository: TaskDetailRepository, mainRepository: MainRepository, searchRepository: SearchRepository, taskItemViewRepository: TaskItemViewRepository, firebase: Firebase ) : UseCases = UseCases( signIn = SignInUseCase(signInRepository), getCurrentUser = CurrentUserUseCase(firebase), signOutUseCase = SignOutUseCase(firebase), addATask = AddATask(noteInputRepository), getCurrentUsersMarkedTasks = GetCurrentUsersMarkedTasksUseCase(yourTaskRepository), getFriendsMarkedTasksUseCase = GetFriendsTasksMarkedUseCase(friendsTaskRepository), getFriendsUnmarkedTasksUseCase = GetFriendsUnmarkedTasksUseCase(friendsTaskRepository), getTaskDetailUseCase = GetTaskDetailUseCase(taskDetailRepository), addACommentUseCase = AddACommentUseCase(taskDetailRepository), getCurrentUsersUnmarkedTasksUseCase = GetCurrentUsersUnmarkedTasksUseCase(yourTaskRepository), markAsDoneUseCase = MarkAsDoneUseCase(taskDetailRepository), getTasksOnceUseCase = GetTasksOnceUseCase(mainRepository), searchTasksUseCase = SearchTasksUseCase(mainRepository), deleteATask = DeleteATask(taskItemViewRepository), getUserInfo = GetUserInfo(mainRepository) ) }
0
Kotlin
0
1
249c58e727fb34ef6f553a9917803cb479ccd6dc
4,825
TaskManager
Apache License 2.0
cloud-storage-service/src/test/kotlin/com/samsung/healthcare/cloudstorageservice/adapter/storage/AzureStorageAdapterTest.kt
S-HealthStack
520,365,362
false
{"Kotlin": 894766, "Dockerfile": 1358, "ANTLR": 1066}
package com.samsung.healthcare.cloudstorageservice.adapter.storage import com.samsung.healthcare.cloudstorageservice.POSITIVE_TEST import com.samsung.healthcare.cloudstorageservice.application.config.AzureProperties import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test import java.text.SimpleDateFormat import java.util.concurrent.TimeUnit internal class AzureStorageAdapterTest { private val azureProperties = AzureProperties("account", "key", "test-container") private val azureStorageAdapter = AzureStorageAdapter(azureProperties) private val signedUrlDuration = 120L @Test @Tag(POSITIVE_TEST) fun `getUploadSignedUrl should work properly`() { val blobName = "test-name" val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH'%3A'mm'%3A'ss'Z&'") val url = azureStorageAdapter.getUploadSignedUrl(blobName, signedUrlDuration) val startDate = dateFormat.parse("""st=[0-9-%A-Za-z]+&""".toRegex().find(url.query)?.value?.removePrefix("st=")) val endDate = dateFormat.parse("""se=[0-9-%A-Za-z]+&""".toRegex().find(url.query)?.value?.removePrefix("se=")) Assertions.assertEquals("account.blob.core.windows.net", url.host) Assertions.assertEquals("/${azureProperties.containerName}/$blobName", url.path) Assertions.assertEquals(signedUrlDuration, TimeUnit.MILLISECONDS.toSeconds(endDate.time - startDate.time)) Assertions.assertTrue(url.query.contains("sp=w")) } @Test @Tag(POSITIVE_TEST) fun `getDownloadSignedUrl should work properly`() { val blobName = "test-name" val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH'%3A'mm'%3A'ss'Z&'") val url = azureStorageAdapter.getDownloadSignedUrl(blobName, signedUrlDuration) val startDate = dateFormat.parse("""st=[0-9-%A-Za-z]+&""".toRegex().find(url.query)?.value?.removePrefix("st=")) val endDate = dateFormat.parse("""se=[0-9-%A-Za-z]+&""".toRegex().find(url.query)?.value?.removePrefix("se=")) Assertions.assertEquals("account.blob.core.windows.net", url.host) Assertions.assertEquals("/${azureProperties.containerName}/$blobName", url.path) Assertions.assertEquals(signedUrlDuration, TimeUnit.MILLISECONDS.toSeconds(endDate.time - startDate.time)) Assertions.assertTrue(url.query.contains("sp=r")) } @Test @Tag(POSITIVE_TEST) fun `getDeleteSignedUrl should work properly`() { val blobName = "test-name" val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH'%3A'mm'%3A'ss'Z&'") val url = azureStorageAdapter.getDeleteSignedUrl(blobName, signedUrlDuration) val startDate = dateFormat.parse("""st=[0-9-%A-Za-z]+&""".toRegex().find(url.query)?.value?.removePrefix("st=")) val endDate = dateFormat.parse("""se=[0-9-%A-Za-z]+&""".toRegex().find(url.query)?.value?.removePrefix("se=")) Assertions.assertEquals("account.blob.core.windows.net", url.host) Assertions.assertEquals("/${azureProperties.containerName}/$blobName", url.path) Assertions.assertEquals(signedUrlDuration, TimeUnit.MILLISECONDS.toSeconds(endDate.time - startDate.time)) Assertions.assertTrue(url.query.contains("sp=d")) } }
2
Kotlin
7
28
b7e7d0b4cc8d1f1123c9f3bd08fa5cc66fbc9920
3,269
backend-system
Apache License 2.0
app/src/main/java/ke/derrick/steps/data/local/database/AppDatabase.kt
Sciederrick
607,208,726
false
null
package ke.derrick.steps.data.local.database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import ke.derrick.steps.data.local.daos.StepsDao import ke.derrick.steps.data.local.entities.Steps @Database(entities = [Steps::class], exportSchema = true, version = 1) abstract class AppDatabase: RoomDatabase() { abstract fun Steps(): StepsDao companion object { @Volatile private var instance: AppDatabase? = null fun getInstance(context: Context): AppDatabase { return instance ?: synchronized(this) { instance ?: buildDatabase(context).also { instance = it } } } private fun buildDatabase(context: Context): AppDatabase { return Room.databaseBuilder(context, AppDatabase::class.java, "steps_database") .build() } } }
7
Kotlin
0
0
af5508c296b3c4fb982f5c779a5ea575b3ca0c6d
921
Steps
MIT License
plugins/hh-geminio/src/main/kotlin/ru/hh/plugins/geminio/model/mapping/GeminioRecipeParameterConverter.kt
tafa11Z
316,900,357
true
{"Kotlin": 369732, "Shell": 87}
package ru.hh.plugins.geminio.model.mapping import com.android.tools.idea.wizard.template.booleanParameter import com.android.tools.idea.wizard.template.stringParameter import ru.hh.plugins.geminio.model.temp_data.GeminioIdParameterPair import ru.hh.plugins.geminio.model.GeminioRecipe import ru.hh.plugins.geminio.model.aliases.AndroidStudioTemplateParameter fun GeminioRecipe.RecipeParameter.toAndroidStudioTemplateIdParameterPair( existingParametersMap: Map<String, AndroidStudioTemplateParameter> ): GeminioIdParameterPair { val androidStudioTemplateParameter = when (this) { is GeminioRecipe.RecipeParameter.StringParameter -> { this.toAndroidStudioTemplateParameter(existingParametersMap) } is GeminioRecipe.RecipeParameter.BooleanParameter -> { this.toAndroidStudioTemplateParameter(existingParametersMap) } is GeminioRecipe.RecipeParameter.EnumParameter<*> -> { throw UnsupportedOperationException("Not supported enum parameters yet") } } return GeminioIdParameterPair( id = this.id, parameter = androidStudioTemplateParameter ) } private fun GeminioRecipe.RecipeParameter.StringParameter.toAndroidStudioTemplateParameter( existingParametersMap: Map<String, AndroidStudioTemplateParameter> ): AndroidStudioTemplateParameter { val geminioParameter = this return stringParameter { name = geminioParameter.name help = geminioParameter.help default = geminioParameter.default constraints = geminioParameter.constraints.map { it.toAndroidStudioStringParameterConstraint() } visible = geminioParameter.visibilityExpression?.toBooleanLambda(existingParametersMap) ?: { true } enabled = geminioParameter.availabilityExpression?.toBooleanLambda(existingParametersMap) ?: { true } suggest = geminioParameter.suggestExpression?.toStringLambda(existingParametersMap) ?: { null } } } private fun GeminioRecipe.RecipeParameter.BooleanParameter.toAndroidStudioTemplateParameter( existingParametersMap: Map<String, AndroidStudioTemplateParameter> ): AndroidStudioTemplateParameter { val geminioParameter = this return booleanParameter { name = geminioParameter.name help = geminioParameter.help default = geminioParameter.default visible = geminioParameter.visibilityExpression?.toBooleanLambda(existingParametersMap) ?: { true } enabled = geminioParameter.availabilityExpression?.toBooleanLambda(existingParametersMap) ?: { true } } }
0
null
0
0
5e91da74e5101c31dccab69776c90696a213d5dc
2,588
android-multimodule-plugin
MIT License
src/main/kotlin/com/kanelai/eris/eventapi/interfaces/httpserver/api/Enqueue.kt
kanelai
145,534,723
false
null
package com.kanelai.eris.eventapi.interfaces.httpserver.api import com.kanelai.eris.eventapi.interfaces.erisclient.api.ContractFunctionWrapper import com.kanelai.eris.eventapi.interfaces.erisclient.api.ErisApiClient import com.kanelai.eris.eventapi.interfaces.erisclient.dto.ErisApi import com.kanelai.eris.eventapi.interfaces.httpserver.api.ApiServer.logger import com.kanelai.eris.eventapi.interfaces.httpserver.api.ApiServer.txLogger import com.kanelai.eris.eventapi.interfaces.httpserver.dto.HttpApi import io.ktor.application.call import io.ktor.http.HttpStatusCode import io.ktor.request.receiveText import io.ktor.response.respond import io.ktor.routing.Route import io.ktor.routing.post import io.ktor.routing.route import java.time.Instant fun Route.enqueue() { route("/event-queue/{topic}/enqueue") { post { logger.info { "Server enqueue API invoked" } val topic = call.parameters["topic"]!! val timestamp = Instant.now() val payload = call.receiveText() logger.debug { "Enqueue to blockchain: $payload" } // enqueue val data = ErisApiClient.gson.toJson(ErisApi.QueueMessageDataDto(timestamp = timestamp, payload = payload)) ContractFunctionWrapper.enqueue(topic, data) logger.debug { "Enqueue to blockchain (topic: $topic): $data" } val enqueueResponse = HttpApi.EnqueueResponseDto("ok", HttpApi.EnqueueResponseDataDto(timestamp)) logger.debug { "HTTP enqueueResponse: $enqueueResponse" } call.respond(HttpStatusCode.OK, enqueueResponse) txLogger.info { "[PUB] ENQUEUE: topic=[$topic] data=[$data]" } } } }
0
Kotlin
0
0
2bb5214c0b7b74ef2f8946700c6da8dd25457e19
1,703
eris-event-api
MIT License
amazon/eventbridge/client/src/main/kotlin/org/http4k/connect/amazon/eventbridge/EventBridge.kt
http4k
295,641,058
false
{"Kotlin": 1624385, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675}
package org.http4k.connect.amazon.eventbridge import dev.forkhandles.result4k.Result import org.http4k.connect.Http4kConnectApiClient import org.http4k.connect.RemoteFailure import org.http4k.connect.amazon.AwsServiceCompanion /** * Docs: https://docs.aws.amazon.com/eventbridge/latest/APIReference/Welcome.html */ @Http4kConnectApiClient interface EventBridge { operator fun <R : Any> invoke(action: EventBridgeAction<R>): Result<R, RemoteFailure> companion object : AwsServiceCompanion("events") }
7
Kotlin
17
37
3522f4a2bf5e476b849ec367700544d89e006f71
513
http4k-connect
Apache License 2.0
module/src/main/java/com/authsignal/email/AuthsignalEmail.kt
authsignal
616,768,479
false
{"Kotlin": 51331}
package com.authsignal.email import com.authsignal.TokenCache import com.authsignal.email.api.EmailAPI import com.authsignal.models.AuthsignalResponse import com.authsignal.models.ChallengeResponse import com.authsignal.models.EnrollResponse import com.authsignal.models.VerifyResponse import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.future.future import java.util.concurrent.CompletableFuture class AuthsignalEmail( tenantID: String, baseURL: String ) { private val api = EmailAPI(tenantID, baseURL) private val cache = TokenCache.shared suspend fun enroll(email: String): AuthsignalResponse<EnrollResponse> { val token = cache.token ?: return cache.handleTokenNotSetError() return api.enroll(token, email) } suspend fun challenge(): AuthsignalResponse<ChallengeResponse> { val token = cache.token ?: return cache.handleTokenNotSetError() return api.challenge(token) } suspend fun verify(code: String): AuthsignalResponse<VerifyResponse> { val token = cache.token ?: return cache.handleTokenNotSetError() val verifyResponse = api.verify(token, code) verifyResponse.data?.token.let { cache.token = it } return verifyResponse } @OptIn(DelicateCoroutinesApi::class) fun enrollAsync(email: String): CompletableFuture<AuthsignalResponse<EnrollResponse>> = GlobalScope.future { enroll(email) } @OptIn(DelicateCoroutinesApi::class) fun challengeAsync(): CompletableFuture<AuthsignalResponse<ChallengeResponse>> = GlobalScope.future { challenge() } @OptIn(DelicateCoroutinesApi::class) fun verifyAsync(code: String): CompletableFuture<AuthsignalResponse<VerifyResponse>> = GlobalScope.future { verify(code) } }
0
Kotlin
0
0
83ef9bc82fec7273c485a08b036aa2096af834e8
1,766
authsignal-android
MIT License
resources-generator/src/main/kotlin/dev/icerock/gradle/generator/GenerationResult.kt
icerockdev
204,874,263
false
{"Kotlin": 456033, "Shell": 1362}
/* * Copyright 2024 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.gradle.generator import com.squareup.kotlinpoet.TypeSpec import dev.icerock.gradle.metadata.container.ContainerMetadata internal data class GenerationResult( val typeSpec: TypeSpec, val metadata: ContainerMetadata )
147
Kotlin
121
1,077
2c484808c928a13ab4d0523b82db3b5ab4e90db5
352
moko-resources
Apache License 2.0
logic/src/main/kotlin/de/dem/localchat/conversation/service/impl/EventSubscriptionServiceImpl.kt
Deminder
397,549,006
false
{"TypeScript": 186533, "Kotlin": 113491, "HTML": 18218, "JavaScript": 9567, "SCSS": 7400, "Shell": 5235, "CSS": 419, "Dockerfile": 212}
package de.dem.localchat.conversation.service.impl import de.dem.localchat.conversation.model.ConversationEvent import de.dem.localchat.conversation.service.EventSubscriptionService import de.dem.localchat.security.dataaccess.UserRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.util.* import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingQueue @Service class EventSubscriptionServiceImpl( @Autowired val userRepository: UserRepository ) : EventSubscriptionService { val userQueues = HashMap<String, Map<String, BlockingQueue<ConversationEvent>>>() @Synchronized override fun notifyMembers(event: ConversationEvent, conversationId: Long, vararg excluded: String) { userRepository.findByConversationId(conversationId) .map { it.username }.toSet() .minus(excluded.toSet()) .forEach { name -> userQueues.getOrDefault(name, emptyMap()).forEach { it.value.put(event) } } } @Synchronized override fun subscribeFor(username: String, sessionId: String): BlockingQueue<ConversationEvent> = LinkedBlockingQueue<ConversationEvent>().also { userQueues[username] = userQueues.getOrDefault(username, emptyMap()) .plus(sessionId to it) } @Synchronized override fun unsubscribeFor(username: String, sessionId: String) { userQueues[username] = userQueues.getOrDefault(username, emptyMap()).filterKeys { sessionId !== it } if (userQueues.isEmpty()) { userQueues.remove(username) } } }
0
TypeScript
0
1
df36170ee512fa1a7d5d36a0f4e6e06ac7d9bbfa
1,765
LocalChat
MIT License
app/src/main/java/com/duckduckgo/app/di/component/DownloadConfirmationFragmentComponent.kt
Rachelmorrell
132,979,208
true
{"Kotlin": 3143821, "HTML": 42259, "Ruby": 7252, "JavaScript": 6544, "C++": 1820, "CMake": 1298, "Shell": 712}
/* * Copyright (c) 2021 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.app.di.component import com.duckduckgo.app.browser.DownloadConfirmationFragment import com.duckduckgo.app.di.ActivityScoped import com.duckduckgo.di.scopes.AppObjectGraph import com.duckduckgo.di.scopes.ActivityObjectGraph import com.squareup.anvil.annotations.ContributesTo import com.squareup.anvil.annotations.MergeSubcomponent import dagger.Binds import dagger.Module import dagger.Subcomponent import dagger.android.AndroidInjector import dagger.multibindings.ClassKey import dagger.multibindings.IntoMap @ActivityScoped @MergeSubcomponent( scope = ActivityObjectGraph::class ) interface DownloadConfirmationFragmentComponent : AndroidInjector<DownloadConfirmationFragment> { @Subcomponent.Factory interface Factory : AndroidInjector.Factory<DownloadConfirmationFragment> } @ContributesTo(AppObjectGraph::class) interface DownloadConfirmationFragmentComponentProvider { fun provideDownloadConfirmationFragmentComponentFactory(): DownloadConfirmationFragmentComponent.Factory } @Module @ContributesTo(AppObjectGraph::class) abstract class DownloadConfirmationFragmentBindingModule { @Binds @IntoMap @ClassKey(DownloadConfirmationFragment::class) abstract fun bindDownloadConfirmationFragmentComponentFactory(factory: DownloadConfirmationFragmentComponent.Factory): AndroidInjector.Factory<*> }
4
Kotlin
0
3
c03633f7faee192948e68c3897c526c323ee0f2e
1,957
Android
Apache License 2.0
fate/src/main/kotlin/com/kotcrab/fate/patcher/extra/file/ExtraChrDatFilePatcher.kt
RikuNoctis
165,883,449
false
null
/* * Copyright 2017-2018 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kotcrab.fate.patcher.extra.file import com.kotcrab.fate.patcher.extra.ExtraTranslation import com.kotcrab.fate.util.writeDatString import kio.KioInputStream import kio.KioOutputStream import kio.LERandomAccessFile import kio.util.WINDOWS_932 import kio.util.align import kio.util.getSubArrayPos import kio.util.toWHex import java.io.ByteArrayOutputStream import java.io.File import java.nio.charset.Charset /** @author Kotcrab */ class ExtraChrDatFilePatcher( origBytes: ByteArray, outFile: File, translation: ExtraTranslation, origTranslation: ExtraTranslation, translationOffset: Int, count: Int, charset: Charset = Charsets.WINDOWS_932 ) { init { outFile.writeBytes(origBytes) val raf = LERandomAccessFile(outFile) val attachedTextMap = mutableMapOf<String, Long>() repeat(count) { offset -> val en = translation.getTranslation(offset, translationOffset) val origEn = origTranslation.getTranslation(offset, translationOffset) if (en != origEn) { val enByteLen = KioOutputStream(ByteArrayOutputStream()).writeDatString(en, charset = charset) val origByteLen = KioOutputStream(ByteArrayOutputStream()).writeDatString(origEn, charset = charset) if (enByteLen <= origByteLen) { raf.seek(getSubArrayPos(origBytes, origEn.toByteArray()).toLong()) raf.writeDatString(en, charset = charset) } else { val pos = getSubArrayPos(origBytes, origEn.toByteArray()) if (pos == -1) error("$origEn not found") var written = false with(KioInputStream(origBytes)) { while (!eof()) { val pointerPos = pos() if (readInt() == pos) { var attachedPointer = attachedTextMap[en] if (attachedPointer == null) { attachedPointer = raf.length() raf.seek(raf.length()) raf.writeDatString(en, charset = charset) attachedTextMap[en] = attachedPointer } raf.seek(pointerPos.toLong()) raf.writeInt(attachedPointer.toInt()) if (written) { println("TN WARN: Written in-dungeon twice: at ${pointerPos.toWHex()}, $en") } written = true } } } if (written == false) { println("$en not written") } } } } raf.seek(raf.length()) raf.align(16) raf.close() } }
0
Kotlin
0
1
04d0a219269e17c97cca54f71ae11e348c9fb070
3,615
fate-explorer
Apache License 2.0
src/test/kotlin/com/qomolangma/infra/TestPing.kt
highsoft-shanghai
386,574,483
false
null
package com.qomolangma.infra import com.qomolangma.frameworks.gateways.core.AntiCorruptionLayer import com.qomolangma.frameworks.payload.core.Payload import com.qomolangma.frameworks.payload.core.StringFieldType.Companion.asString import javax.annotation.Resource @AntiCorruptionLayer class TestPing : Ping { @Resource private val pings: Pings? = null override fun pong(payload: Payload): Payload { return Payload.append(pings!!.get(), payload.get("data", asString())) .append("message", "ok") .build() } }
0
Kotlin
2
4
d2622ea653baccd9a68cedc0b3daf60957f00dae
557
qomolangma
MIT License
src/main/java/com/andres_k/lib/library/output/PdfToByteStream.kt
Draym
319,586,872
false
null
package com.andres_k.lib.library.output import org.apache.pdfbox.pdmodel.PDDocument import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream /** * Created on 2020/10/22. * * @author <NAME> */ class PdfToByteStream : OutputBuilder { private val output: ByteArrayOutputStream = ByteArrayOutputStream() override fun validateOutput() { } override fun save(document: PDDocument) { document.save(output) } fun get(): ByteArrayInputStream { return ByteArrayInputStream(output.toByteArray()) } override fun close() { output.close() } }
0
Kotlin
0
1
5084ca91cf25328afa3238abc19d1f0e3c095fe1
614
PDF-Flex
MIT License
app/main/arenaoppslag/dsop/VedtakResponse.kt
navikt
690,073,639
false
{"Kotlin": 25186, "Shell": 574, "Dockerfile": 150}
package arenaoppslag.dsop data class VedtakResponse( val uttrekksperiode: Periode, val vedtaksliste: List<DsopVedtak> ) data class DsopVedtak( val vedtakId: Int, val virkningsperiode: Periode, val vedtakstype: Kodeverdi, val vedtaksvariant: Kodeverdi, val vedtakstatus: Kodeverdi, val rettighetstype: Kodeverdi, val utfall: Kodeverdi, val aktivitetsfase: Kodeverdi, )
0
Kotlin
0
0
02fd8f5fe4932ddcf7a5cbb11b88789514729d48
410
aap-arenaoppslag
MIT License
core/testing/src/main/java/com/niyaj/testing/repository/TestAddOnItemRepository.kt
skniyajali
644,752,474
false
{"Kotlin": 4254026, "Shell": 5353, "Java": 232}
/* * Copyright 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.niyaj.testing.repository import com.niyaj.common.result.Resource import com.niyaj.data.repository.AddOnItemRepository import com.niyaj.model.AddOnItem import com.niyaj.model.searchAddOnItem import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.mapLatest import org.jetbrains.annotations.TestOnly class TestAddOnItemRepository : AddOnItemRepository { /** * The backing addon item list for testing */ private val addOnItems = MutableStateFlow(mutableListOf<AddOnItem>()) override suspend fun getAllAddOnItem(searchText: String): Flow<List<AddOnItem>> { return addOnItems.mapLatest { it.searchAddOnItem(searchText) } } override suspend fun getAddOnItemById(itemId: Int): Resource<AddOnItem?> { return Resource.Success(addOnItems.value.find { it.itemId == itemId }) } override suspend fun upsertAddOnItem(newAddOnItem: AddOnItem): Resource<Boolean> { val result = addOnItems.value.find { it.itemId == newAddOnItem.itemId } return Resource.Success( if (result == null) { addOnItems.value.add(newAddOnItem) } else { addOnItems.value.remove(result) addOnItems.value.add(newAddOnItem) }, ) } override suspend fun deleteAddOnItems(itemIds: List<Int>): Resource<Boolean> { return Resource.Success(addOnItems.value.removeAll { it.itemId in itemIds }) } override suspend fun findAddOnItemByName(name: String, addOnItemId: Int?): Boolean { return addOnItems.value.any { if (addOnItemId != null) { it.itemName == name && it.itemId != addOnItemId } else { it.itemName == name } } } override suspend fun importAddOnItemsToDatabase(addOnItems: List<AddOnItem>): Resource<Boolean> { addOnItems.forEach { upsertAddOnItem(it) } return Resource.Success(true) } @TestOnly fun updateAddOnData(items: List<AddOnItem>) { addOnItems.value = items.toMutableList() } @TestOnly suspend fun createTestItem(): AddOnItem { val newItem = AddOnItem( itemId = 1, itemName = "Test Item", itemPrice = 10, isApplicable = true, createdAt = System.currentTimeMillis(), updatedAt = null, ) upsertAddOnItem(newItem) return newItem } }
42
Kotlin
0
1
e6c13d3175e83ba4eac80426edf6942f46518f11
3,109
PoposRoom
Apache License 2.0
src/cds/src/main/kotlin/org/icpclive/cds/adapters/EmulationAdapter.kt
icpc
447,849,919
false
null
package org.icpclive.cds.adapters import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import kotlinx.datetime.Instant import org.icpclive.api.ContestStatus import org.icpclive.cds.* import org.icpclive.util.* import kotlin.random.Random import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds internal class EmulationAdapter private val logger = getLogger(EmulationAdapter::class) internal fun Flow<ContestUpdate>.toEmulationFlow(startTime: Instant, emulationSpeed: Double) = flow { val scope = CoroutineScope(currentCoroutineContext()) val stateFlow = contestState().stateIn(scope) scope.launch { delay(1.seconds) while (stateFlow.value.infoAfterEvent?.status != ContestStatus.FINALIZED) { logger.info("Waiting for contest to become Finalized to start emulation...") delay(1.seconds) } } val state = stateFlow.first { it.infoAfterEvent?.status == ContestStatus.FINALIZED } val finalContestInfo = state.infoAfterEvent!! val runs = state.runs.values.toList() val analyticsMessages = state.analyticsMessages.values.toList() logger.info("Running in emulation mode with speed x${emulationSpeed} and startTime = ${startTime.humanReadable}") val contestInfo = finalContestInfo.copy( startTime = startTime, emulationSpeed = emulationSpeed ) emit(-Duration.INFINITE to InfoUpdate(contestInfo.copy(status = ContestStatus.BEFORE))) buildList { add(Duration.ZERO to InfoUpdate(contestInfo.copy(status = ContestStatus.RUNNING))) add(contestInfo.contestLength to InfoUpdate(contestInfo.copy(status = ContestStatus.OVER))) for (run in runs) { var percentage = Random.nextDouble(0.1) var timeShift = 0 if (run.result != null) { do { val submittedRun = run.copy( percentage = percentage, result = null ) add((run.time + timeShift.milliseconds) to RunUpdate(submittedRun)) percentage += Random.nextDouble(1.0) timeShift += Random.nextInt(20000) } while (percentage < 1.0) } add((run.time + timeShift.milliseconds) to RunUpdate(run)) } addAll(analyticsMessages.map { it.relativeTime to AnalyticsUpdate(it) }) }.sortedBy { it.first }.forEach { emit(it) } }.map { (startTime + it.first / emulationSpeed) to it.second } .toTimedFlow { logger.info("Processed events upto ${(it - startTime) * emulationSpeed}") }
18
null
7
36
e3cb0165d86f7dc0d1232cb35988743d44fe80c9
2,676
live-v3
MIT License
app/src/main/java/com/wagarcdev/der/di/DataStoreModule.kt
wagarcdev
546,044,448
false
null
package com.wagarcdev.der.di import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStoreFile import com.wagarcdev.der.utils.CoroutinesDispatchers import com.wagarcdev.der.utils.CreatePdf import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import javax.inject.Singleton /** * Hilt module for [DataStore]. */ @Module @InstallIn(SingletonComponent::class) object DataStoreModule { @Provides @Singleton fun providesAppPreferences( @ApplicationContext context: Context, coroutinesDispatchers: CoroutinesDispatchers ): DataStore<Preferences> = PreferenceDataStoreFactory.create( scope = CoroutineScope(context = coroutinesDispatchers.io + SupervisorJob()), produceFile = { context.preferencesDataStoreFile(name = "app_preferences") } ) }
0
Kotlin
0
0
2578dde2f1bb801b2fd04f49964878ac4159dc25
1,211
DER
MIT License
src/main/kotlin/dev/akkinoc/spring/boot/logback/access/joran/LogbackAccessJoranSpringPropertyAction.kt
akkinoc
47,953,830
false
null
package dev.akkinoc.spring.boot.logback.access.joran import ch.qos.logback.core.joran.action.Action import ch.qos.logback.core.joran.action.ActionUtil.setProperty import ch.qos.logback.core.joran.action.ActionUtil.stringToScope import ch.qos.logback.core.joran.spi.InterpretationContext import org.springframework.core.env.Environment import org.xml.sax.Attributes /** * The Joran [Action] to support `<springProperty>` tags. * Allows properties to be sourced from the environment. * * @property environment The environment. * @see org.springframework.boot.logging.logback.SpringPropertyAction */ class LogbackAccessJoranSpringPropertyAction(private val environment: Environment) : Action() { override fun begin(ic: InterpretationContext, elem: String, attrs: Attributes) { val name = attrs.getValue(NAME_ATTRIBUTE) val scope = stringToScope(attrs.getValue(SCOPE_ATTRIBUTE)) val source = attrs.getValue("source") val defaultValue = attrs.getValue("defaultValue") val value = environment.getProperty(source, defaultValue) setProperty(ic, name, value, scope) } override fun end(ic: InterpretationContext, elem: String) = Unit }
12
Kotlin
30
154
38fd570201dec55949f7bf1073fddb3d7455befd
1,197
logback-access-spring-boot-starter
Apache License 2.0
feature/topics/src/main/kotlin/uk/govuk/app/topics/data/local/TopicsLocalDataSource.kt
alphagov
788,896,208
false
{"Kotlin": 278530}
package uk.govuk.app.topics.data.local import io.realm.kotlin.ext.query import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import uk.govuk.app.topics.data.local.model.LocalTopicItem import javax.inject.Inject import javax.inject.Singleton @Singleton internal class TopicsLocalDataSource @Inject constructor( private val realmProvider: TopicsRealmProvider ) { val topics: Flow<List<LocalTopicItem>> = flow { emitAll(realmProvider.open().query<LocalTopicItem>().asFlow().map { it.list }) } suspend fun selectAll(refs: List<String>) { insertOrUpdate( refs.map { ref -> Pair(ref, true) } ) } suspend fun select(ref: String) { insertOrUpdate(listOf(Pair(ref, true))) } suspend fun deselect(ref: String) { insertOrUpdate(listOf(Pair(ref, false))) } private suspend fun insertOrUpdate(topics: List<Pair<String, Boolean>>) { realmProvider.open().write { for ((ref, isSelected) in topics) { val localTopic = query<LocalTopicItem>("ref = $0", ref).first().find() localTopic?.apply { this.isSelected = isSelected } ?: copyToRealm( LocalTopicItem().apply { this.ref = ref this.isSelected = isSelected } ) } } } }
1
Kotlin
0
1
f6dae0132f1a5b96950c36f0333beea0f6bbcc74
1,511
govuk-mobile-android-app
MIT License
app/src/main/java/com/tilkiweb/foodrecipes/services/CategoryService.kt
murat1347
641,579,114
false
null
package com.tilkiweb.foodrecipes.services import com.tilkiweb.foodrecipes.models.ApiResponse import com.tilkiweb.foodrecipes.models.res.CategoryResponse import com.tilkiweb.foodrecipes.utils.HelperService import com.tilkiweb.foodrecipes.utils.RetrofitClient class CategoryService { companion object { val retrofit = RetrofitClient.getClient()!! val reqServices: DAOInterface = retrofit!!.create(DAOInterface::class.java) suspend fun getCategories(): ApiResponse<CategoryResponse> { try { val res = reqServices.getCategories() if (!res.isSuccessful) return HelperService.handleApiError(res) var body = res.body() return ApiResponse(true, body, null) } catch (ex: Exception) { return HelperService.handleException(ex) } } } }
0
Kotlin
0
0
29ae0e008574e9ceabae2b9cdc7b0618db18f140
884
FoodAppMobile
MIT License
if-rpc/src/main/kotlin/com/interactionfields/rpc/provider/MeetingServiceRPC.kt
Ashinch
397,369,377
false
null
package com.interactionfields.rpc.provider import com.interactionfields.common.response.R import com.interactionfields.rpc.interceptor.FeignClientInterceptor import org.springframework.cloud.openfeign.FeignClient import org.springframework.web.bind.annotation.PostMapping /** * RPC function about the meeting service. */ @FeignClient(value = "meeting-service", configuration = [FeignClientInterceptor::class]) interface MeetingServiceRPC { @PostMapping("/meeting/create") fun create(): R }
0
Kotlin
0
0
997910700454d7e36242a7871292535ca5b62ca6
503
interaction-fields
Apache License 2.0
app/src/main/java/com/example/smilie/model/service/backend/generateStudentUserWeightsStrategy.kt
SarmanAulakh
645,078,598
false
null
package com.example.smilie.model.service.backend import com.example.smilie.model.Metric class generateStudentUserWeightsStrategy : generateUserWeightsStrategy { override suspend fun generateWeights(metrics: ArrayList<Metric>): ArrayList<Double> { var weights : ArrayList<Double> = ArrayList<Double>() for (metric in metrics) { if (metric.name == "Productivity (School)" || metric.name == "Time spent on Assignments") { weights += 2.5 } else { weights += 2.0 } } return weights } }
1
Kotlin
0
0
8d22bbb7ab3aa44590750782b3f6301a513e6b71
591
ece452-group2
Apache License 2.0
forage-android/src/main/java/com/joinforage/forage/android/collect/BTPinCollector.kt
teamforage
554,343,430
false
{"Kotlin": 441887}
package com.joinforage.forage.android.collect import com.basistheory.android.service.BasisTheoryElements import com.basistheory.android.service.ProxyRequest import com.basistheory.android.view.TextElement import com.joinforage.forage.android.VaultType import com.joinforage.forage.android.core.StopgapGlobalState import com.joinforage.forage.android.core.telemetry.Log import com.joinforage.forage.android.core.telemetry.NetworkMonitor import com.joinforage.forage.android.core.telemetry.UserAction import com.joinforage.forage.android.core.telemetry.VaultProxyResponseMonitor import com.joinforage.forage.android.model.EncryptionKeys import com.joinforage.forage.android.model.PaymentMethod import com.joinforage.forage.android.network.ForageConstants import com.joinforage.forage.android.network.data.BaseVaultRequestParams import com.joinforage.forage.android.network.model.ForageApiError import com.joinforage.forage.android.network.model.ForageApiResponse import com.joinforage.forage.android.network.model.ForageError import com.joinforage.forage.android.ui.ForagePINEditText import com.verygoodsecurity.vgscollect.core.HTTPMethod import org.json.JSONException import java.util.* internal data class ProxyRequestObject(val pin: TextElement, val card_number_token: String) internal class BTPinCollector( private val pinForageEditText: ForagePINEditText, private val merchantAccount: String ) : PinCollector { private val logger = Log.getInstance() private val vaultType = VaultType.BT_VAULT_TYPE override fun getVaultType(): VaultType { return vaultType } override suspend fun submitBalanceCheck( paymentMethodRef: String, vaultRequestParams: BaseVaultRequestParams ): ForageApiResponse<String> { val logAttributes = mapOf( "merchant_ref" to merchantAccount, "payment_method_ref" to paymentMethodRef ) // If the PIN isn't valid (less than 4 numbers) then return a response here. if (!pinForageEditText.getElementState().isComplete) { return returnIncompletePinError(logAttributes, logger) } val bt = buildBt() val measurement = setupMeasurement(balancePath(paymentMethodRef), UserAction.BALANCE) val proxyRequest: ProxyRequest = ProxyRequest().apply { headers = buildHeaders(vaultRequestParams.encryptionKey, merchantAccount, traceId = logger.getTraceIdValue()) body = ProxyRequestObject( pin = pinForageEditText.getTextElement(), card_number_token = vaultRequestParams.cardNumberToken ) path = balancePath(paymentMethodRef) } logger.i( "[BT] Sending balance check to BasisTheory", attributes = logAttributes ) measurement.start() val response = runCatching { bt.proxy.post(proxyRequest) } measurement.end() // MUST reset the PIN value after submitting pinForageEditText.getTextElement().setText("") if (response.isSuccess) { val forageResponse = response.getOrNull() try { val forageApiError = ForageApiError.ForageApiErrorMapper.from(forageResponse.toString()) // Error code hardcoded as 400 because of lack of information val httpStatusCode = 400 measurement.setHttpStatusCode(httpStatusCode).logResult() val error = forageApiError.errors[0] logger.e( "[BT] Received an error while submitting balance request to BasisTheory: $error.message", attributes = logAttributes ) return ForageApiResponse.Failure( listOf( ForageError( httpStatusCode, error.code, error.message ) ) ) } catch (_: JSONException) { } logger.i( "[BT] Received successful response from BasisTheory", attributes = logAttributes ) measurement.setHttpStatusCode(200).logResult() return ForageApiResponse.Success(forageResponse.toString()) } val btErrorResponse = response.exceptionOrNull() logger.e( "[BT] Received BasisTheory API exception on balance check: $btErrorResponse", attributes = logAttributes ) val unknownBtStatusCode = 500 measurement.setHttpStatusCode(unknownBtStatusCode).logResult() return ForageApiResponse.Failure( listOf( ForageError(unknownBtStatusCode, "unknown_server_error", "Unknown Server Error") ) ) } override suspend fun submitPaymentCapture( paymentRef: String, vaultRequestParams: BaseVaultRequestParams ): ForageApiResponse<String> { val logAttributes = mapOf( "merchant_ref" to merchantAccount, "payment_ref" to paymentRef ) // If the PIN isn't valid (less than 4 numbers) then return a response here. if (!pinForageEditText.getElementState().isComplete) { return returnIncompletePinError(logAttributes, logger) } val bt = buildBt() val measurement = setupMeasurement(capturePaymentPath(paymentRef), UserAction.CAPTURE) val proxyRequest: ProxyRequest = ProxyRequest().apply { headers = buildHeaders(vaultRequestParams.encryptionKey, merchantAccount, paymentRef, traceId = logger.getTraceIdValue()) body = ProxyRequestObject( pin = pinForageEditText.getTextElement(), card_number_token = vaultRequestParams.cardNumberToken ) path = capturePaymentPath(paymentRef) } logger.i( "[BT] Sending payment capture to BasisTheory", attributes = logAttributes ) measurement.start() val response = runCatching { bt.proxy.post(proxyRequest) } measurement.end() // MUST reset the PIN value after submitting pinForageEditText.getTextElement().setText("") if (response.isSuccess) { val forageResponse = response.getOrNull() try { val forageApiError = ForageApiError.ForageApiErrorMapper.from(forageResponse.toString()) val error = forageApiError.errors[0] logger.e( "[BT] Received an error while submitting capture request to BasisTheory: $error.message", attributes = logAttributes ) // Error code hardcoded as 400 because of lack of information val httpStatusCode = 400 measurement.setHttpStatusCode(httpStatusCode).setForageErrorCode(error.code).logResult() return ForageApiResponse.Failure( listOf( ForageError( httpStatusCode, error.code, error.message ) ) ) } catch (_: JSONException) { } logger.i( "[BT] Received successful response from BasisTheory", attributes = logAttributes ) // Status Code hardcoded because of lack of knowledge val httpStatusCode = 200 measurement.setHttpStatusCode(httpStatusCode).logResult() return ForageApiResponse.Success(forageResponse.toString()) } val btErrorResponse = response.exceptionOrNull() logger.e( "[BT] Received BasisTheory API exception on payment capture: $btErrorResponse", attributes = logAttributes ) val unknownBtStatusCode = 500 measurement.setHttpStatusCode(unknownBtStatusCode).logResult() return ForageApiResponse.Failure( listOf( ForageError(500, "unknown_server_error", "Unknown Server Error") ) ) } override suspend fun submitDeferPaymentCapture( paymentRef: String, vaultRequestParams: BaseVaultRequestParams ): ForageApiResponse<String> { val logAttributes = mapOf( "merchant_ref" to merchantAccount, "payment_ref" to paymentRef ) // If the PIN isn't valid (less than 4 numbers) then return a response here. if (!pinForageEditText.getElementState().isComplete) { return returnIncompletePinError(logAttributes, logger) } val bt = buildBt() val proxyRequest: ProxyRequest = ProxyRequest().apply { headers = buildHeaders( vaultRequestParams.encryptionKey, merchantAccount, paymentRef, traceId = logger.getTraceIdValue() ) body = ProxyRequestObject( pin = pinForageEditText.getTextElement(), card_number_token = vaultRequestParams.cardNumberToken ) path = deferPaymentCapturePath(paymentRef) } val measurement = setupMeasurement(deferPaymentCapturePath(paymentRef), UserAction.DEFER_CAPTURE) logger.i( "[BT] Sending defer payment capture to BasisTheory", attributes = logAttributes ) measurement.start() val response = runCatching { bt.proxy.post(proxyRequest) } measurement.end() // MUST reset the PIN value after submitting pinForageEditText.getTextElement().setText("") if (response.isSuccess) { val forageResponse = response.getOrNull() try { val forageApiError = ForageApiError.ForageApiErrorMapper.from(forageResponse.toString()) val error = forageApiError.errors[0] logger.e( "[BT] Received an error while submitting defer payment capture request to BasisTheory: $error.message", attributes = logAttributes ) // Error code hardcoded as 400 because of lack of information val httpStatusCode = 400 measurement.setHttpStatusCode(httpStatusCode).setForageErrorCode(error.code).logResult() return ForageApiResponse.Failure( listOf( ForageError( httpStatusCode, error.code, error.message ) ) ) } catch (_: JSONException) { } logger.i( "[BT] Received successful response from BasisTheory", attributes = logAttributes ) // Status Code hardcoded because of lack of knowledge val httpStatusCode = 200 measurement.setHttpStatusCode(httpStatusCode).logResult() return ForageApiResponse.Success(forageResponse.toString()) } val btErrorResponse = response.exceptionOrNull() logger.e( "[BT] Received BasisTheory API exception while calling deferPaymentCapture: $btErrorResponse", attributes = logAttributes ) val unknownBtStatusCode = 500 measurement.setHttpStatusCode(unknownBtStatusCode).logResult() return ForageApiResponse.Failure( listOf( ForageError(unknownBtStatusCode, "unknown_server_error", "Unknown Server Error") ) ) } override fun parseEncryptionKey(encryptionKeys: EncryptionKeys): String { return encryptionKeys.btAlias } override fun parseVaultToken(paymentMethod: PaymentMethod): String { val token = paymentMethod.card.token if (token.contains(CollectorConstants.TOKEN_DELIMITER)) { return token.split(CollectorConstants.TOKEN_DELIMITER)[1] } logger.e( "[BT] BT Token wasn't found on card", attributes = mapOf( "merchant_ref" to merchantAccount, "payment_method_ref" to paymentMethod.ref ) ) throw RuntimeException("BT token not found on card!") } private fun setupMeasurement(path: String, action: UserAction): NetworkMonitor { return VaultProxyResponseMonitor.newMeasurement( vault = vaultType, userAction = action, logger ) .setPath(path) .setMethod(HTTPMethod.POST.toString()) } companion object { // this code assumes that .setForageConfig() has been called // on a Forage***EditText before PROXY_ID or API_KEY get // referenced private val PROXY_ID = StopgapGlobalState.envConfig.btProxyID private val API_KEY = StopgapGlobalState.envConfig.btAPIKey private fun buildBt(): BasisTheoryElements { return BasisTheoryElements.builder() .apiKey(API_KEY) .build() } private fun buildHeaders( encryptionKey: String, merchantAccount: String, idempotencyKey: String = UUID.randomUUID().toString(), traceId: String = "" ): Map<String, String> { val headers = HashMap<String, String>() headers[ForageConstants.Headers.X_KEY] = encryptionKey headers[ForageConstants.Headers.MERCHANT_ACCOUNT] = merchantAccount headers[ForageConstants.Headers.IDEMPOTENCY_KEY] = idempotencyKey headers[ForageConstants.Headers.BT_PROXY_KEY] = PROXY_ID headers[ForageConstants.Headers.CONTENT_TYPE] = "application/json" headers[ForageConstants.Headers.TRACE_ID] = traceId return headers } internal fun returnIncompletePinError(logAttributes: Map<String, String>, logger: Log): ForageApiResponse.Failure { logger.w( "[BT] User attempted to submit an invalid PIN", attributes = logAttributes ) return ForageApiResponse.Failure( ForageConstants.ErrorResponseObjects.INCOMPLETE_PIN_ERROR ) } private fun balancePath(paymentMethodRef: String) = "/api/payment_methods/$paymentMethodRef/balance/" private fun capturePaymentPath(paymentRef: String) = "/api/payments/$paymentRef/capture/" private fun deferPaymentCapturePath(paymentRef: String) = "/api/payments/$paymentRef/collect_pin/" } }
6
Kotlin
0
0
27555338350553fc5dc65e325b9672f63509a3d3
14,883
forage-android-sdk
MIT License
android/app/src/main/java/app/candash/cluster/CarState.kt
nmullaney
449,826,855
false
{"Kotlin": 218103, "Java": 10602}
package app.candash.cluster import androidx.lifecycle.MutableLiveData typealias CarState = MutableMap<String, Float?> fun createCarState(carData: MutableMap<String, Float> = mutableMapOf()): CarState { return HashMap(carData) } typealias LiveCarState = Map<String, MutableLiveData<Float?>> fun createLiveCarState(): LiveCarState { val liveCarState: MutableMap<String, MutableLiveData<Float?>> = mutableMapOf() // Create live data for each signal name SName.javaClass.declaredFields.forEach { field -> if (field.type == String::class.java) { val name = field.get(null) as String liveCarState[name] = MutableLiveData(null) } } // Make it immutable return liveCarState.toMap() } fun LiveCarState.clear() { this.forEach { it.value.postValue(null) } }
6
Kotlin
19
66
f7a6b06418c35d703a48844c144d83e904b1a950
837
candash
MIT License
core/designsystem/src/main/kotlin/com/ngapps/phototime/core/designsystem/component/CategorySelector.kt
ngapp-dev
752,386,763
false
{"Kotlin": 1840502, "Shell": 10136}
/* * Copyright 2024 NGApps Dev (https://github.com/ngapp-dev). All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ngapps.phototime.core.designsystem.component import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.rememberScrollState import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.vectorResource import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.tooling.preview.PreviewParameterProvider import androidx.compose.ui.unit.dp import com.ngapps.phototime.core.designsystem.icon.PtIcons import com.ngapps.phototime.core.designsystem.theme.PtTheme /** * Location category selector with selection change state. Wraps Material 3 * [Button] and [Icon]. * * @param modifier Modifier to be applied to this item. * @param categories The list of String of category items. * @param onCategorySelected Whether the category is selected. * @param onEditCategories Whether the category is need to be created. */ @Composable fun PtCategorySelector( modifier: Modifier = Modifier, categories: List<String>, categoriesTitleRes: String, onCategorySelected: (String) -> Unit, onEditCategories: () -> Unit, ) { var selectedCategory by rememberSaveable { mutableStateOf<String?>(if (categories.isNotEmpty()) categories[0] else "") } val scrollState = rememberScrollState() onCategorySelected(selectedCategory.orEmpty()) Column( modifier = modifier .fillMaxWidth() .wrapContentHeight(), ) { Text( style = MaterialTheme.typography.titleMedium, text = categoriesTitleRes, color = MaterialTheme.colorScheme.onSurface, ) Row( modifier = Modifier .fillMaxSize() .horizontalScroll(scrollState) .padding(top = 10.dp), ) { categories.forEach { category -> PtTextButton( onClick = { selectedCategory = category onCategorySelected(category) }, modifier = Modifier .defaultMinSize(minWidth = 1.dp, minHeight = 28.dp) .clickable { selectedCategory = category onCategorySelected(category) }, colors = ButtonDefaults.buttonColors( containerColor = Color.Transparent, contentColor = MaterialTheme.colorScheme.onSurface, disabledContainerColor = Color.Transparent, disabledContentColor = MaterialTheme.colorScheme.onSurface, ), shape = MaterialTheme.shapes.extraSmall, contentPadding = PaddingValues(all = 0.dp), enabled = selectedCategory != category, leadingIcon = { Icon( imageVector = ImageVector.vectorResource(id = PtIcons.LeftBracket), contentDescription = categoriesTitleRes, tint = MaterialTheme.colorScheme.inversePrimary, modifier = Modifier, ) }, trailingIcon = { Icon( imageVector = ImageVector.vectorResource(id = PtIcons.RightBracket), contentDescription = categoriesTitleRes, tint = MaterialTheme.colorScheme.inversePrimary, modifier = Modifier, ) }, text = { Text( text = category, style = MaterialTheme.typography.bodyMedium, ) }, ) Spacer(modifier = Modifier.width(12.dp)) } PtCreateCategoryTextButton(onClick = onEditCategories) } } } @ThemePreviews @Composable fun LocationCategorySelectorPreview( @PreviewParameter(CategoryProvider::class) categories: List<String> = listOf( "Nature", "City", "Studio", ), ) { PtTheme { Surface { PtCategorySelector( categoriesTitleRes = "Location category", categories = categories, onCategorySelected = {}, onEditCategories = {}, ) } } } class CategoryProvider : PreviewParameterProvider<List<String>> { override val values: Sequence<List<String>> get() = sequenceOf( listOf("City", "Nature", "Studio"), listOf("Sport", "Art", "Restaurants"), // Add more category lists for preview variations ) }
0
Kotlin
0
3
2aa95af22a6912031c930404af39f38c158bb720
6,681
phototime
Apache License 2.0
app/src/main/java/es/nauticapps/spotymedia/ui/artist/albums/ArtistAlbumFragment.kt
diegomonje8
340,968,608
false
null
package es.nauticapps.spotymedia.ui.artist.albums import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import es.nauticapps.spotymedia.base.BaseExtraData import es.nauticapps.spotymedia.base.BaseFragment import es.nauticapps.spotymedia.base.BaseState import es.nauticapps.spotymedia.databinding.FragmentArtistAlbumBinding import es.nauticapps.spotymedia.datalayer.models.AlbumItem import retrofit2.HttpException import java.net.UnknownHostException class ArtistAlbumFragment(private val artistId: String, private var listener: (Album: AlbumItem) -> Unit) : BaseFragment<ArtistAlbumListState, ArtistAlbumViewModel, FragmentArtistAlbumBinding>() { /** * Base Vars */ override var viewModelClass: Class<ArtistAlbumViewModel> = ArtistAlbumViewModel::class.java lateinit var vm: ArtistAlbumViewModel override val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> FragmentArtistAlbumBinding = FragmentArtistAlbumBinding::inflate /** * Custom Vars */ lateinit var myAdapter : ArtistAlbumFragmentAdapter /** * Setup View */ override fun setupView(viewModel: ArtistAlbumViewModel) { vm = viewModel viewModel.requestAlbums(artistId) myAdapter = ArtistAlbumFragmentAdapter(listOf<AlbumItem>(), listener) val myRecyclerView : RecyclerView = binding.albumdRecyclerList myRecyclerView.apply { adapter = myAdapter layoutManager = LinearLayoutManager(context) itemAnimator = DefaultItemAnimator() } } /** * State Management Functions */ override fun onNormal(data: ArtistAlbumListState) { binding.albumProgressBar.visibility = View.GONE myAdapter.updateList((data).listAlbums) } override fun onLoading(dataLoading: BaseExtraData?) { binding.albumProgressBar.visibility = View.VISIBLE } override fun onError(dataError: Throwable) { val msg = when (dataError) { is HttpException -> "Network Error: " + dataError.code().toString() is UnknownHostException -> "Please, Internet connection needed !!" else -> "Oops Unknown Error, Please try later !!" } Toast.makeText(requireActivity(), msg, Toast.LENGTH_LONG).show() } }
0
Kotlin
0
0
7014fe9d2f90f810a09b543a8ce5a1f78ad89062
2,622
SpotyMedia
Apache License 2.0
announcify/src/main/java/io/announcify/AnnouncifyClient.kt
announcify
273,592,679
false
null
package io.announcify import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.os.Handler import android.os.Looper import android.util.Log import com.google.gson.Gson import com.google.gson.JsonSyntaxException import io.announcify.model.Announcement import okhttp3.* import java.io.IOException import java.util.* class AnnouncifyClient(private val host: String, private val apiKey: String, private val projectId: Int, private val locale: Locale, private val listener: ResultListener) { companion object { val LOG_TAG = AnnouncifyClient::class.simpleName } fun request() { val request = Request.Builder() .get() .url("https://$host/projects/$projectId/active-announcement/active-message") .header("x-api-key", apiKey) .header("accept-language", toLanguageTag(locale)) .header("user-agent", "Android/v${Build.VERSION.RELEASE} " + "Announcify/v${BuildConfig.VERSION_NAME}+${BuildConfig.VERSION_CODE}") .build() val httpClient = OkHttpClient() Log.i(LOG_TAG, "Search for active announcements.") httpClient.newCall(request).enqueue(object: Callback { override fun onResponse(call: Call, response: Response) { if (response.code() == 404) { Log.i(LOG_TAG, "No active announcement available.") Handler(Looper.getMainLooper()).post { listener.onNoMessage() } return } if (response.code() != 200) { Log.e(LOG_TAG, "Request active announcement failed with HTTP error (${response.code()}!") fail(Exception("Request active announcement failed. Status code: ${response.code()}")) return } response.body()?.string()?.let { json -> try { val announcement = Gson().fromJson(json, Announcement::class.java) Log.i(LOG_TAG, "Found active announcement $announcement.") Handler(Looper.getMainLooper()).post { listener.onMessage(announcement) } } catch (e: JsonSyntaxException) { Log.e(LOG_TAG, "Parsing announcement response failed!", e) fail(e) } } } override fun onFailure(call: Call, e: IOException) { Log.e(LOG_TAG, "Request active announcement failed!", e) fail(e) } }) } private fun fail(exception: Exception) { Handler(Looper.getMainLooper()).post { listener.onFail(exception) } } private fun toLanguageTag(locale: Locale): String { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return locale.toLanguageTag() } val language = locale.language val country = locale.country return "${language}_$country" } class Builder(private val context: Context) { companion object { const val DEFAULT_HOST = "api.announcify.io" const val META_PREFIX = "announcify" const val META_API_KEY_KEY = "${META_PREFIX}_api_key" const val META_PROJECT_ID_KEY = "${META_PREFIX}_project_id" } private var host: String? = null private var apiKey: String? = null private var projectId: Int? = null private var locale: Locale? = null private var listener: ResultListener? = null fun host(host: String): Builder { this.host = host return this } fun apiKey(key: String): Builder { this.apiKey = key return this } fun projectId(id: Int): Builder { this.projectId = id return this } fun resultListener(listener: ResultListener): Builder { this.listener = listener return this } // TODO: read fields from meta fields by app's manifest (like facebook lib) fun build(): AnnouncifyClient { val applicationInfo = context.packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA) val metaData = applicationInfo.metaData val host = host ?: DEFAULT_HOST val apiKey = when { apiKey != null -> apiKey!! metaData.getString(META_API_KEY_KEY) != null -> metaData.getString( META_API_KEY_KEY) else -> throw IllegalArgumentException("Field `apiKey` is required and must be set!") }!! val projectId = when { projectId != null -> projectId metaData.getInt(META_PROJECT_ID_KEY, -1) != -1 -> metaData.getInt( META_PROJECT_ID_KEY) else -> throw IllegalArgumentException("Field `projectId` is required and must be set!") }!! val locale = locale ?: Locale.getDefault() val listener = listener ?: throw IllegalArgumentException("Field `resultListener` is required and must be set!") return AnnouncifyClient(host, apiKey, projectId, locale, listener) } } interface ResultListener { fun onMessage(announcement: Announcement) fun onNoMessage() fun onFail(e: Exception) } }
0
Kotlin
0
1
c0b42bbfb4c2e36630b2061df46af3fc882c747e
5,667
android
Apache License 2.0
aTalk/src/main/java/net/java/sip/communicator/impl/muc/MUCActivator.kt
cmeng-git
704,328,019
false
{"Kotlin": 14364024, "Java": 2718723, "C": 275021, "Shell": 49203, "Makefile": 28273, "C++": 13642, "HTML": 7793, "CSS": 3127, "JavaScript": 2758, "AIDL": 375}
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package net.java.sip.communicator.impl.muc import net.java.sip.communicator.service.contactsource.ContactSourceService import net.java.sip.communicator.service.credentialsstorage.CredentialsStorageService import net.java.sip.communicator.service.globaldisplaydetails.GlobalDisplayDetailsService import net.java.sip.communicator.service.gui.AlertUIService import net.java.sip.communicator.service.gui.UIService import net.java.sip.communicator.service.msghistory.MessageHistoryService import net.java.sip.communicator.service.muc.MUCService import net.java.sip.communicator.service.protocol.AccountManager import net.java.sip.communicator.service.protocol.OperationSetMultiUserChat import net.java.sip.communicator.service.protocol.ProtocolProviderFactory import net.java.sip.communicator.service.protocol.ProtocolProviderService import net.java.sip.communicator.util.ServiceUtils.getService import org.atalk.service.configuration.ConfigurationService import org.atalk.service.resources.ResourceManagementService import org.osgi.framework.Bundle import org.osgi.framework.BundleActivator import org.osgi.framework.BundleContext import org.osgi.framework.InvalidSyntaxException import org.osgi.framework.ServiceEvent import org.osgi.framework.ServiceListener import org.osgi.framework.ServiceReference import java.util.* /** * The activator for the chat room contact source bundle. * * @author Hristo Terezov * @author Eng Chong Meng */ class MUCActivator : BundleActivator { /** * Starts this bundle. * *Collection<EventObject?> context the bundle context where we register and obtain services. */ @Throws(Exception::class) override fun start(context: BundleContext) { bundleContext = context if (configurationService!!.getBoolean(DISABLED_PROPERTY, false)) return bundleContext!!.registerService(ContactSourceService::class.java.name, contactSource, null) mucService = MUCServiceImpl() bundleContext!!.registerService(MUCService::class.java.name, mucService, null) } @Throws(Exception::class) override fun stop(context: BundleContext) { if (protocolProviderRegListener != null) { bundleContext!!.removeServiceListener(protocolProviderRegListener) } if (chatRoomProviders != null) chatRoomProviders!!.clear() } /** * Listens for `ProtocolProviderService` registrations. */ private class ProtocolProviderRegListener : ServiceListener { /** * Handles service change events. */ override fun serviceChanged(event: ServiceEvent) { val serviceRef = event.serviceReference // if the event is caused by a bundle being stopped, we don't want to know if (serviceRef.bundle.state == Bundle.STOPPING) { return } val service = bundleContext!!.getService(serviceRef) as? ProtocolProviderService ?: return // we don't care if the source service is not a protocol provider when (event.type) { ServiceEvent.REGISTERED -> handleProviderAdded(service) ServiceEvent.UNREGISTERING -> handleProviderRemoved(service) } } } companion object { /** * The configuration property to disable */ private const val DISABLED_PROPERTY = "muc.MUCSERVICE_DISABLED" /** * The bundle context. */ var bundleContext: BundleContext? = null /** * The configuration service. */ private var configService: ConfigurationService? = null /** * Providers of contact info. */ private var chatRoomProviders: MutableList<ProtocolProviderService>? = null /** * Returns the chat room contact source. * * @return the chat room contact source */ /** * The chat room contact source. */ val contactSource = ChatRoomContactSourceService() /** * Returns a reference to the ResourceManagementService implementation currently registered in * the bundle context or null if no such implementation was found. * * @return a reference to a ResourceManagementService implementation currently registered in * the bundle context or null if no such implementation was found. */ /** * The resource service. */ var resources: ResourceManagementService? = null get() { if (field == null) { field = getService(bundleContext, ResourceManagementService::class.java) } return field } private set /** * Returns the MUC service instance. * * @return the MUC service instance. */ /** * The MUC service. */ lateinit var mucService: MUCServiceImpl private set /** * Returns the `AccountManager` obtained from the bundle context. * * @return the `AccountManager` obtained from the bundle context */ /** * The account manager. */ var accountManager: AccountManager? = null get() { if (field == null) { field = getService(bundleContext, AccountManager::class.java) } return field } private set /** * Returns the `AlertUIService` obtained from the bundle context. * * @return the `AlertUIService` obtained from the bundle context */ /** * The alert UI service. */ var alertUIService: AlertUIService? = null get() { if (field == null) { field = getService(bundleContext, AlertUIService::class.java) } return field } private set /** * The credential storage service. */ private var credentialsService: CredentialsStorageService? = null /** * The UI service. */ private var uiService: UIService? = null /** * Listens for ProtocolProviderService registrations. */ private var protocolProviderRegListener: ProtocolProviderRegListener? = null /** * Gets the service giving access to message history. * * @return the service giving access to message history. */ /** * The message history service. */ var messageHistoryService: MessageHistoryService? = null get() { if (field == null) field = getService(bundleContext, MessageHistoryService::class.java) return field } private set /** * Returns the `GlobalDisplayDetailsService` obtained from the bundle context. * * @return the `GlobalDisplayDetailsService` obtained from the bundle context */ /** * The global display details service instance. */ var globalDisplayDetailsService: GlobalDisplayDetailsService? = null get() { if (field == null) { field = getService(bundleContext, GlobalDisplayDetailsService::class.java) } return field } private set /** * Returns the `ConfigurationService` obtained from the bundle context. * * @return the `ConfigurationService` obtained from the bundle context */ val configurationService: ConfigurationService? get() { if (configService == null) { configService = getService(bundleContext, ConfigurationService::class.java) } return configService } /** * Returns a reference to a CredentialsStorageService implementation currently registered in * the bundle context or null if no such implementation was found. * * @return a currently valid implementation of the CredentialsStorageService. */ val credentialsStorageService: CredentialsStorageService? get() { if (credentialsService == null) { credentialsService = getService(bundleContext, CredentialsStorageService::class.java) } return credentialsService } /** * Returns a list of all currently registered providers. * * @return a list of all currently registered providers */ fun getChatRoomProviders(): List<ProtocolProviderService>? { if (chatRoomProviders != null) return chatRoomProviders chatRoomProviders = LinkedList() protocolProviderRegListener = ProtocolProviderRegListener() bundleContext!!.addServiceListener(protocolProviderRegListener) var serRefs: Array<ServiceReference<*>?>? = null try { serRefs = bundleContext!!.getServiceReferences(ProtocolProviderFactory::class.java.name, null) } catch (e: InvalidSyntaxException) { e.printStackTrace() } if (serRefs != null && serRefs.isNotEmpty()) { for (ppfSerRef in serRefs) { val providerFactory = bundleContext!!.getService<ProtocolProviderFactory>(ppfSerRef as ServiceReference<ProtocolProviderFactory>) for (accountID in providerFactory.getRegisteredAccounts()) { val ppsSerRef = providerFactory.getProviderForAccount(accountID) val protocolProvider = bundleContext!!.getService(ppsSerRef) handleProviderAdded(protocolProvider) } } } return chatRoomProviders } /** * Handles the registration of a new `ProtocolProviderService`. Adds the given * `protocolProvider` to the list of queried providers. * *Collection<EventObject?> protocolProvider the `ProtocolProviderService` to add */ private fun handleProviderAdded(protocolProvider: ProtocolProviderService) { if (protocolProvider.getOperationSet(OperationSetMultiUserChat::class.java) != null && !chatRoomProviders!!.contains(protocolProvider)) { chatRoomProviders!!.add(protocolProvider) } } /** * Handles the un-registration of a `ProtocolProviderService`. Removes the given * `protocolProvider` from the list of queried providers. * *Collection<EventObject?> protocolProvider the `ProtocolProviderService` to remove */ private fun handleProviderRemoved(protocolProvider: ProtocolProviderService) { chatRoomProviders!!.remove(protocolProvider) } /** * Returns the `UIService` obtained from the bundle context. * * @return the `UIService` obtained from the bundle context */ val uIService: UIService? get() { if (uiService == null) { uiService = getService(bundleContext, UIService::class.java) } return uiService } } }
0
Kotlin
0
0
90e83dd8c054a5f480d03e8b0b1912b41bd79b0c
12,228
atalk-hmos_kotlin
Apache License 2.0
kafkakewl-domain/src/main/kotlin/com/mwam/kafkakewl/domain/Deployments.kt
MarshallWace
313,626,541
false
{"Kotlin": 64850, "Java": 9675}
/* * SPDX-FileCopyrightText: 2024 <NAME> <<EMAIL>> * * SPDX-License-Identifier: Apache-2.0 */ package com.mwam.kafkakewl.domain import arrow.core.NonEmptyList import kotlinx.serialization.Serializable @Serializable data class DeploymentOptions( val dryRun: Boolean = true, // TODO make allowing unsafe operations more granular if needed val allowUnsafe: Boolean = false ) /** A deployment to be done, contains options, topologies to be deployed and topology-ids to be removed. * * @param options * the deployment options * @param deploy * the topologies to deploy * @param delete * the topology-ids to remove */ @Serializable data class Deployments( val options: DeploymentOptions = DeploymentOptions(), val deploy: List<Topology> = emptyList(), val delete: List<TopologyId> = emptyList() ) @Serializable data class TopologyDeploymentQuery( val topologyIdFilterRegex: String?, val offset: Int?, val limit: Int? ) @Serializable data class TopologyDeploymentStatus( val result: String = "" // TODO we may need to replace it in the future with something more appropriate ) /** The deployment of a topology * * @param topologyId * the topology id * @param status * the deployment status * @param topology * the optional topology, null means the topology is removed */ @Serializable data class TopologyDeployment( val topologyId: TopologyId, val status: TopologyDeploymentStatus, val topology: Topology? ) { fun toCompact(): TopologyDeploymentCompact = TopologyDeploymentCompact(topologyId, status, topology != null) } typealias TopologyDeployments = Map<TopologyId, TopologyDeployment> /** The compact deployment of a topology (it does not contain the topology) * * @param topologyId * the topology id * @param status * the deployment status * @param isDeployed * true if the topology is deployed, false if it's removed */ @Serializable data class TopologyDeploymentCompact( val topologyId: TopologyId, val status: TopologyDeploymentStatus, val isDeployed: Boolean ) typealias TopologyDeploymentsCompact = Map<TopologyId, TopologyDeploymentCompact> /** Base interface for failures while querying deployments. */ sealed interface QueryDeploymentsFailure /** Base interface for failures while performing deployments. */ sealed interface PostDeploymentsFailure /** All failures relating to performing/querying deployments. */ object DeploymentsFailure { @Serializable data class Validation(val validationFailed: List<String>) : PostDeploymentsFailure @Serializable data class Deployment(val deploymentFailed: List<String>) : PostDeploymentsFailure fun validation(errors: NonEmptyList<String>): Validation = Validation(errors) fun deployment(throwable: Throwable): Deployment = Deployment(errors(throwable)) } /** All generic failures */ object Failure { @Serializable data class NotFound(val notFound: List<String>) : QueryDeploymentsFailure @Serializable data class Authorization(val authorizationFailed: List<String>) : PostDeploymentsFailure, QueryDeploymentsFailure fun notFound(vararg notFound: String): NotFound = NotFound(notFound.toList()) fun authorization(throwable: Throwable): Authorization = Authorization(errors(throwable)) } private fun errors(throwable: Throwable): List<String> = listOf(throwable.message ?: "???") /** The result of a successful deployment. * * @param statuses * the statuses of the topology deployments. */ @Serializable data class DeploymentsSuccess(val statuses: Map<TopologyId, TopologyDeploymentStatus>) : QueryDeploymentsFailure
2
Kotlin
3
9
acb480929b5164b37d6bd6e94b2091971f4eb1b5
3,651
kafkakewl
Apache License 2.0
payment-notifications/src/test/kotlin/com/mobilabsolutions/payment/notifications/data/repository/BaseRepositoryTest.kt
mobilabsolutions
159,817,607
false
null
/* * Copyright © MobiLab Solutions GmbH */ package com.mobilabsolutions.payment.notifications.data.repository import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import java.time.Instant /** * Test the custom repository configuration and implementation. Also ensures that obtaining the result type with * reflection at runtime works as expected. * * @author <a href="mailto:<EMAIL>"><NAME></a> */ class BaseRepositoryTest : AbstractRepositoryTest() { @Autowired lateinit var testRecordRepository: TestRecordRepository @Test fun testSaveAndUpdate() { var record: TestRecord = recordWithQuantity(0) val createdAt: Instant? = record.createdDate Assertions.assertNotNull(createdAt) Assertions.assertEquals(createdAt, record.lastModifiedDate) Thread.sleep(1) record.quantity = 1 record = testRecordRepository.saveAndFlush(record) if (createdAt != null) { Assertions.assertTrue(createdAt.isBefore(record.lastModifiedDate)) } } @Test fun testFindAll() { recordWithNameAndOrder("Water", 1) recordWithNameAndOrder("Burger", 2) recordWithNameAndOrder("Pomes", 2) val records: List<TestRecord> = testRecordRepository.findAll() Assertions.assertEquals(3, records.size) } @Test fun testDelete() { val record1 = recordWithNameAndOrder("Water", 1) val record2 = recordWithNameAndOrder("Burger", 2) recordWithNameAndOrder("Pomes", 3) testRecordRepository.delete(record1) Assertions.assertEquals(testRecordRepository.count(), 2) testRecordRepository.delete(record2) Assertions.assertEquals(testRecordRepository.count(), 1) } private fun recordWithQuantity(quantity: Int): TestRecord { val testRecord = TestRecord() testRecord.quantity = quantity return testRecordRepository.save(testRecord) } private fun recordWithNameAndOrder(name: String, order: Int): TestRecord { val record = TestRecord() record.name = name record.order = order return testRecordRepository.save(record) } }
1
Kotlin
1
3
7592abdabb7c05a71366634e5b09f4f08a3f0eff
2,265
stash-sdk-backend
Apache License 2.0
app/src/main/java/com/lq/bestproject/example/activity/RecyclerViewActivity.kt
yuqianglianshou
297,072,745
false
null
package com.lq.bestproject.example.activity import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import com.lq.baselibrary.BaseActivity import com.lq.bestproject.R import kotlinx.android.synthetic.main.activity_recyclerview.* /** * *@author : lq *@date : 2020/9/22 *@desc : * */ class RecyclerViewActivity : BaseActivity() { override fun initContentView(): Int { return R.layout.activity_recyclerview } override fun initUI() { findViewById<ImageView>(R.id.iv_back_base).setOnClickListener { onBackPressed() } findViewById<TextView>(R.id.tv_title_base).text = "recyclerview" rv_activity.layoutManager = LinearLayoutManager(mActivity) // rv_activity.adapter = BaseQuickAdapter } override fun initData() { } }
1
null
1
1
7f648b8a213143ac05fed4a67b42961802331aab
852
BestProject
Apache License 2.0
ext/src/main/kotlin/me/jiangcai/common/ext/json/JsonPath.kt
mingshz
166,675,112
false
{"Gradle": 20, "INI": 11, "Shell": 2, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 10, "XML": 8, "Kotlin": 311, "JavaScript": 1, "HTML": 4, "Java Properties": 10, "Java": 71, "JSON": 2}
@file:Suppress("unused") package me.jiangcai.common.ext.json import com.jayway.jsonpath.Predicate import java.io.File import java.io.InputStream /** * @see com.jayway.jsonpath.JsonPath.read */ fun <X> String?.readJsonPath(path: String, vararg filters: Predicate): X? { return com.jayway.jsonpath.JsonPath.read<X>(this, path, *filters) } /** * @see com.jayway.jsonpath.JsonPath.read */ fun <X> InputStream.readJsonPath(path: String, vararg filters: Predicate): X? { return com.jayway.jsonpath.JsonPath.read<X>(this, path, *filters) } /** * @see com.jayway.jsonpath.JsonPath.read */ fun <X> File.readJsonPath(path: String, vararg filters: Predicate): X? { return com.jayway.jsonpath.JsonPath.read<X>(this, path, *filters) }
1
null
1
1
34060249958f817da4e1668109c37dcf8cbf2600
745
library
MIT License
app/src/main/java/modularity/andres/it/coderdojo/ui/list/mvp/DojoEventsListPresenter.kt
Ryder96
109,853,091
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "HTML": 1, "JSON": 1, "Proguard": 1, "Kotlin": 38, "XML": 31, "Java": 4}
package modularity.andres.it.coderdojo.ui.list.mvp import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import modularity.andres.it.coderdojo.app.mvp.Presenter /** * Created by garu on 14/11/17. */ class DojoEventsListPresenter(model: DojoEventsListModel, view: DojoEventsListView?) : Presenter<DojoEventsListModel, DojoEventsListView>(model, view) { fun searchEvents(refresh: Boolean = false) { if (model.getUserPref().available) { model.getEvents( latitude = model.getUserPref().homeLatitude, longitude = model.getUserPref().homeLongitude, range = model.getUserPref().searchRange, refresh = refresh ).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ view?.showEvents(it) }, { view?.showError(it) }) } else { view?.requestUserPrefs() } } }
0
Kotlin
0
0
2c8afeaacaeb12e3caa0512926f832440b62af7e
1,022
CoderDojo-AndroidApp
MIT License
src/main/kotlin/de/hpi/dbs1/PropertiesConnectionConfig.kt
Computerdores
666,735,391
false
{"INI": 4, "Gradle Kotlin DSL": 3, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 2, "Kotlin": 8, "Java": 6}
package de.hpi.dbs1 import java.io.File import java.util.Properties class PropertiesConnectionConfig(file: File) : ConnectionConfig { val properties = Properties() init { file.inputStream().use { properties.load(it) } } override fun getHost(): String = properties.getProperty("host") override fun getPort(): Int = properties.getProperty("port").toInt() override fun getDatabase(): String = properties.getProperty("database") override fun getUsername(): String = properties.getProperty("username") override fun getPassword(): String = properties.getProperty("password") }
1
null
1
1
75f488b3f36f6a62b8037d303697139e5cf1ec43
615
DBS-Task-04
MIT License
src/main/kotlin/coursera/algorithms1/week1/assignments/interview/UnionFindWithSpecificCanonicalElement.kt
rupeshsasne
359,696,544
false
{"Gradle": 2, "INI": 2, "Shell": 1, "Text": 2, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Kotlin": 42, "Java": 13, "XML": 7}
package coursera.algorithms1.week1.assignments.interview class UnionFindWithSpecificCanonicalElement(n: Int) { private val ids = IntArray(n) { it } private val largestValueAt = IntArray(n) { it } private val size = IntArray(n) { 1 } private fun root(p: Int): Int { var trav = p while (ids[trav] != trav) { ids[trav] = ids[ids[trav]] trav = ids[trav] } return trav } fun find(i: Int): Int = largestValueAt[root(i)] fun connected(p: Int, q: Int): Boolean = root(p) == root(q) fun union(p: Int, q: Int) { val pRoot = root(p) val qRoot = root(q) if (pRoot == qRoot) return val newRoot: Int val oldRoot: Int if (size[pRoot] > size[qRoot]) { ids[qRoot] = pRoot size[pRoot] += size[qRoot] newRoot = pRoot oldRoot = qRoot } else { ids[pRoot] = qRoot size[qRoot] += size[pRoot] newRoot = qRoot oldRoot = pRoot } if (largestValueAt[newRoot] < largestValueAt[oldRoot]) largestValueAt[newRoot] = largestValueAt[oldRoot] } }
0
Kotlin
0
0
e5a9b1f2d1c497ad7925fb38d9e4fc471688298b
1,213
algorithms-sedgewick-wayne
MIT License
app/src/main/java/com/william/bulletscreen/SimpleTextWatcher.kt
WeiLianYang
278,868,151
false
null
/* * Copyright WeiLianYang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.william.bulletscreen import android.text.Editable import android.text.TextWatcher /** * @author William * @date 12/4/20 7:56 PM * Class Comment: */ open class SimpleTextWatcher : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { } }
0
null
1
9
0f873ab262c793be7d61d92cd631c5db8c262190
1,054
BulletScreenText
Apache License 2.0
src/kt/exceptions.kt
Bigsby
80,818,352
false
{"TypeScript": 27140, "HTML": 26340, "JavaScript": 24007, "C++": 11850, "C#": 11016, "Java": 10692, "Visual Basic": 9513, "CSS": 9125, "Erlang": 8821, "Scala": 6692, "Go": 6512, "PHP": 5937, "C": 5561, "Python": 5105, "F#": 5051, "PowerShell": 5000, "Perl": 4981, "Ruby": 4669, "Kotlin": 3315, "OCaml": 2726, "Rust": 2312, "Shell": 2238, "Haskell": 1802, "Assembly": 837, "Perl 6": 637, "Forth": 162, "Batchfile": 47}
fun doStuff(inError: Boolean) { if (inError) throw Exception("An error occured!") println("Doing stuff!") } fun main(args: Array<String>) { try { doStuff(false) doStuff(true) doStuff(false) // not reached } catch (e: Exception) { print("ERROR: ${e.message}") } }
10
TypeScript
0
1
baf421fdb7b4c60bbdea32d1c80886b37cdb0854
324
langs
Apache License 2.0
app/src/main/java/modularity/andres/it/coderdojo/ui/userlocation/map/DojoMap.kt
Ryder96
109,853,091
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "HTML": 1, "JSON": 1, "Proguard": 1, "Kotlin": 38, "XML": 31, "Java": 4}
package modularity.andres.it.coderdojo.ui.userlocation.map import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.* /** * Created by garu on 07/12/17. */ class DojoMap(val map: GoogleMap) { fun addMarker(position: LatLng, title: String):Marker{ return this.map.addMarker( MarkerOptions() .position(position) .title(title) ) } fun setLocation(position: LatLng, zoom: Float = 10.0F, bearing: Float = 90.0F) { val cameraPos = CameraPosition.builder() .target(position) .zoom(zoom) .bearing(bearing) .build() this.map.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPos)) } fun clear(){ this.map.clear() } fun addCircle(circle: CircleOptions):Circle { return this.map.addCircle(circle) } }
0
Kotlin
0
0
2c8afeaacaeb12e3caa0512926f832440b62af7e
980
CoderDojo-AndroidApp
MIT License
compiler/testData/codegen/box/strings/kt2592.kt
JetBrains
3,432,266
false
null
// IGNORE_BACKEND: WASM // WASM_MUTE_REASON: STDLIB fun box(): String { String() return String() + "OK" + String() }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
125
kotlin
Apache License 2.0
core-kotlin/src/main/kotlin/com/baeldung/dataclass/Movie.kt
rey5137
197,136,853
false
null
package com.baeldung.dataclass data class Movie(val name: String, val studio: String, var rating: Float)
8
null
18
3
9566b4d5e4c6686f603f370ea676c22ee653d406
105
tutorials-1
MIT License
app/src/main/java/com/example/yassirtest/ui/theme/Color.kt
AssoulYasser
805,504,032
false
{"Gradle Kotlin DSL": 3, "Java Properties": 5, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "TOML": 1, "Proguard": 1, "Kotlin": 37, "XML": 24, "INI": 3, "Java": 28}
package com.example.yassirtest.ui.theme import androidx.compose.ui.graphics.Color val PureRed = Color(0xFFFF0000) val PureBlack = Color(0xFF000000) val PureWhite = Color(0xFFFFFFFF) val Gray = Color(0xFF292929)
0
Java
0
0
513512399a7a12366c698961181854c57c25bad3
212
YassirTest
MIT License
src/main/kotlin/net/civmc/kira/command/Command.kt
Huskydog9988
762,771,211
false
{"INI": 2, "Text": 2, "JSON": 1, "Shell": 1, "YAML": 4, "Markdown": 1, "Dockerfile": 1, "Batchfile": 1, "Ignore List": 1, "Gradle Kotlin DSL": 1, "Kotlin": 23, "Java": 110, "XML": 1}
package net.civmc.kira.command import com.github.maxopoly.kira.command.model.discord.DiscordCommandChannelSupplier import com.github.maxopoly.kira.command.model.top.InputSupplier import com.github.maxopoly.kira.user.UserManager import net.dv8tion.jda.api.events.interaction.SlashCommandEvent import net.dv8tion.jda.api.hooks.ListenerAdapter import net.dv8tion.jda.api.interactions.commands.OptionMapping import net.dv8tion.jda.api.interactions.commands.build.CommandData import org.apache.logging.log4j.Logger abstract class Command(val logger: Logger, val userManager: UserManager) : ListenerAdapter() { abstract val name: String open val requireUser = false open val requireIngameAccount = false open val requiredPermission = "default" open val global = true abstract fun getCommandData(): CommandData abstract fun dispatchCommand(event: SlashCommandEvent, sender: InputSupplier) override fun onSlashCommand(event: SlashCommandEvent) { if (event.name != name) { return } val user = userManager.getOrCreateUserByDiscordID(event.user.idLong) val supplier: InputSupplier = DiscordCommandChannelSupplier(user, event.guild!!.idLong, event.channel.idLong) if (requireUser && supplier.user == null) { event.reply("You have to be a user to run this command").queue() return } if (requireIngameAccount && !supplier.user.hasIngameAccount()) { event.reply("You need to have an in-game account linked to use this command").queue() return } if (!supplier.hasPermission(requiredPermission)) { event.reply("You don't have the required permission to do this").queue() logger.info(supplier.identifier + " attempted to run forbidden command: " + name) return } dispatchCommand(event, supplier) } }
1
null
1
1
fb36361e36cc6ffd929bce8bc5ab4b9f374286ab
1,929
Kira
MIT License
app/src/main/java/jp/mihailskuzmins/sugoinihongoapp/persistence/repos/firestore/extensions/Word.kt
MihailsKuzmins
240,947,625
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 10, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 323, "XML": 156, "Java": 1, "JSON": 1}
package jp.mihailskuzmins.sugoinihongoapp.persistence.repos.firestore.extensions import com.google.firebase.firestore.DocumentSnapshot import jp.mihailskuzmins.sugoinihongoapp.extensions.toLowerCaseEx import jp.mihailskuzmins.sugoinihongoapp.resources.FirestoreConstants import java.util.* fun createWordListComparator(): Comparator<DocumentSnapshot> = compareByDescending<DocumentSnapshot> { x -> x.getDate(FirestoreConstants.Keys.Words.dateCreated) } .thenBy { x -> x.getString(FirestoreConstants.Keys.Words.original)?.toLowerCaseEx() }
1
null
1
1
57e19b90b4291dc887a92f6d57f9be349373a444
543
sugoi-nihongo-android
Apache License 2.0
ealvalog/src/main/java/com/ealva/ealvalog/NullMarkerFactory.kt
badmannersteam
316,855,021
true
{"Java": 194509, "Kotlin": 163683}
/* * Copyright 2017 <NAME> * * This file is part of eAlvaLog. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ealva.ealvalog /** * A no-op implementation of the [MarkerFactory] interface * * Created by <NAME> on 2/28/17. */ object NullMarkerFactory : MarkerFactory { override fun get(name: String) = NullMarker override fun exists(name: String) = false override fun orphan(name: String) = false override fun makeOrphan(name: String) = NullMarker }
0
null
0
0
e84667908ca203043226364f98b20bb1d915aa5e
991
ealvalog
Apache License 2.0
quoteexampleviewmodel/app/src/test/java/br/com/flaviogf/example/quoteexampleviewmodel/quotes/QuoteViewModelTests.kt
flaviogf
164,208,503
false
{"JavaScript": 102857, "C#": 87323, "Python": 77881, "Kotlin": 66337, "Java": 56751, "Ruby": 55965, "HTML": 55308, "Jupyter Notebook": 44978, "Swift": 23622, "CSS": 18132, "TypeScript": 17537, "Go": 5627, "EJS": 2760, "Starlark": 1756, "Dockerfile": 678, "Mako": 494, "Shell": 444, "SCSS": 360, "Gherkin": 353, "Stylus": 86, "Procfile": 47}
package br.com.flaviogf.example.quoteexampleviewmodel.quotes import androidx.arch.core.executor.testing.InstantTaskExecutorRule import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test class QuoteViewModelTests { @get:Rule val rule = InstantTaskExecutorRule() private val quoteDao = FakeQuoteDao() private val quoteRepository = QuoteRepository(quoteDao) private lateinit var model: QuoteViewModel @Before fun setUp() { model = QuoteViewModel(quoteRepository) } @Test fun `should return live data of list quote list all quotes`() { model.listAllQuotes().observeForever { assertEquals(0, it?.count()) } } @Test fun `should add quote when add quote`() { val quote = Quote("Hello", "<NAME>") model.addQuote(quote) model.listAllQuotes().observeForever { assertEquals(1, it?.count()) } } class FakeQuoteDao : QuoteDao { private val quotes: MutableList<Quote> = mutableListOf() override fun all(): List<Quote> { return quotes } override fun add(quote: Quote) { quotes.add(quote) } } }
18
JavaScript
0
0
8a5619d815c705ec7b1a48a9d5f942252acc5528
1,246
examples
MIT License
common/declarative/src/main/kotlin/br/com/zup/beagle/widget/ui/TabView.kt
thosantunes
269,216,984
false
null
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.com.zup.beagle.widget.ui import br.com.zup.beagle.core.ServerDrivenComponent /** * TabView is a component responsible for the navigation between views. * It works by displaying tabs corresponding to the different views that can be accessed. * * @param tabItems define yours view has in tab * @param style reference a native style in your local styles file to be applied on this view. * */ data class TabView( val tabItems: List<TabItem>, val style: String? = null ) : ServerDrivenComponent /** * Define the view has in the tab view * * @param title displays the text on the TabView component. If it is null or not declared it won't display any text. * @param content * inflate a view on the TabView according to the Tab item clicked. * It could receive any view (Server Driven). * @param icon * display an icon image on the TabView component. * If it is left as null or not declared it won't display any icon. * */ data class TabItem( val title: String? = null, val content: ServerDrivenComponent, val icon: String? = null )
1
null
1
1
046531e96d0384ae2917b0fd790f09d1a8142912
1,772
beagle
Apache License 2.0
vector/src/main/java/im/vector/app/features/analytics/DecryptionFailure.kt
SchildiChat
263,362,993
false
null
/* * Copyright (c) 2024 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.app.features.analytics import im.vector.app.features.analytics.plan.Error import org.matrix.android.sdk.api.session.crypto.MXCryptoError data class DecryptionFailure( val timeStamp: Long, val roomId: String, val failedEventId: String, val error: MXCryptoError, val wasVisibleOnScreen: Boolean, val ownIdentityTrustedAtTimeOfDecryptionFailure: Boolean, // If this is set, it means that the event was decrypted but late. Will be -1 if // the event was not decrypted after the maximum wait time. val timeToDecryptMillis: Long? = null, val isMatrixDotOrg: Boolean, val isFederated: Boolean? = null, val eventLocalAgeAtDecryptionFailure: Long? = null ) fun DecryptionFailure.toAnalyticsEvent(): Error { val errorMsg = (error as? MXCryptoError.Base)?.technicalMessage ?: error.message return Error( context = "mxc_crypto_error_type|${errorMsg}", domain = Error.Domain.E2EE, name = this.toAnalyticsErrorName(), // this is deprecated keep for backward compatibility cryptoModule = Error.CryptoModule.Rust, cryptoSDK = Error.CryptoSDK.Rust, eventLocalAgeMillis = eventLocalAgeAtDecryptionFailure?.toInt(), isFederated = isFederated, isMatrixDotOrg = isMatrixDotOrg, timeToDecryptMillis = timeToDecryptMillis?.toInt() ?: -1, wasVisibleToUser = wasVisibleOnScreen, userTrustsOwnIdentity = ownIdentityTrustedAtTimeOfDecryptionFailure, ) } private fun DecryptionFailure.toAnalyticsErrorName(): Error.Name { val error = this.error val name = if (error is MXCryptoError.Base) { when (error.errorType) { MXCryptoError.ErrorType.UNKNOWN_INBOUND_SESSION_ID, MXCryptoError.ErrorType.KEYS_WITHHELD -> Error.Name.OlmKeysNotSentError MXCryptoError.ErrorType.OLM -> Error.Name.OlmUnspecifiedError MXCryptoError.ErrorType.UNKNOWN_MESSAGE_INDEX -> Error.Name.OlmIndexError else -> Error.Name.UnknownError } } else { Error.Name.UnknownError } // check if it's an expected UTD! val localAge = this.eventLocalAgeAtDecryptionFailure val isHistorical = localAge != null && localAge < 0 if (isHistorical && !this.ownIdentityTrustedAtTimeOfDecryptionFailure) { return Error.Name.HistoricalMessage } return name }
79
null
702
381
4cf3ff606e32d93ce99a3a03e26ba8fcc8b07250
3,158
SchildiChat-android
Apache License 2.0
rxjava_library/src/main/java/com/ls/rxjava_library/Observables.kt
Kyoto36
281,307,648
false
{"Java": 852737, "Kotlin": 448639, "Shell": 483}
package com.ls.rxjava_library import io.reactivex.Observable /** * @ClassName: Observables * @Description: * @Author: ls * @Date: 2020/9/14 12:53 */ class Observables{ companion object{ /** * 创建Observable * @receiver Observable<T> * @param provideT Function0<T> * @return Observable<T> */ @JvmStatic fun <T> create(provideT: () -> T): Observable<T> { return Observable.create<T>{ it.onNext(provideT.invoke()) } } @JvmStatic fun <T> result(observableT : () -> Observable<T>): Observable<T>{ return Observable.just(1).flatMap { observableT.invoke() } } } }
1
null
1
1
eab64603b4365fd62e394e0ffe94553be9b2e495
724
AndroidUtil
Apache License 2.0
j2k/testData/fileOrElement/assignmentExpression/or.kt
JakeWharton
99,388,807
true
null
x = x or 2
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
10
kotlin
Apache License 2.0
app/src/main/java/com/vipulasri/jetinstagram/ui/home/PostPage.kt
priyanka-pixel
592,113,181
false
null
package com.vipulasri.jetinstagram.ui.home import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.ClickableText import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.annotation.ExperimentalCoilApi import coil.compose.rememberImagePainter import com.vipulasri.jetinstagram.data.PostsRepository import com.vipulasri.jetinstagram.model.currentUser import com.vipulasri.jetinstagram.model.names @Preview(showBackground = true, widthDp = 360, heightDp = 640) @Composable fun PostPage() { Column(Modifier.verticalScroll(rememberScrollState())) { AddPostTopBar() Post() Divider() TagPeople() Divider() AddLocation() Divider() AddFundraiser() Divider() PostToOtherInstagramAccounts() Divider() MediaPlatformTogglesList() Divider() Spacer(modifier = Modifier.weight(1f)) AdvancedSettings() } } @Composable private fun AddPostTopBar() { TopAppBar(backgroundColor = MaterialTheme.colors.surface) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { IconButton(onClick = { /*TODO*/ }) { Icon(Icons.Default.ArrowBack, contentDescription = "") } Text(text = "New Post", style = MaterialTheme.typography.h5) ClickableText( text = AnnotatedString("Share", SpanStyle(Color.Blue)), style = MaterialTheme.typography.h6, onClick = {}, ) } } } @OptIn(ExperimentalCoilApi::class) @Composable private fun Post() { var text by remember { mutableStateOf(TextFieldValue("")) } Row() { Image( rememberImagePainter(PostsRepository.posts.value[0].image), "", Modifier .size(100.dp) .padding(12.dp), contentScale = ContentScale.Crop ) TextField( modifier = Modifier.padding(top = 4.dp), value = text, onValueChange = { text = it }, colors = TextFieldDefaults.textFieldColors( textColor = Color.Gray, disabledTextColor = Color.Transparent, backgroundColor = Color.White, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, disabledIndicatorColor = Color.Transparent ), placeholder = { Text(text = "Write a caption") } ) } } @Composable private fun TagPeople() { ExpandableSection(name = "Tag People") { InstagramAccountToggle( name = names[2], image = "https://randomuser.me/api/portraits/men/2.jpg" ) InstagramAccountToggle( name = names[3], image = "https://randomuser.me/api/portraits/men/3.jpg" ) InstagramAccountToggle( name = names[4], image = "https://randomuser.me/api/portraits/men/4.jpg" ) } } @Preview(showBackground = true) @Composable private fun AddLocation() { ExpandableSection(name = "Add Location") { Text( text = "Tap here to show location suggestions", color = Color.Gray, modifier = Modifier.padding(12.dp) ) } } @Composable private fun AddFundraiser() { ExpandableSection(name = "Add Fundraiser") { Spacer(Modifier.height(40.dp)) } } @Composable private fun PostToOtherInstagramAccounts() { ExpandableSection(name = "Post To Other Instagram Accounts") { InstagramAccountToggle(name = currentUser.name, image = currentUser.image) InstagramAccountToggle( name = names[0], image = "https://randomuser.me/api/portraits/men/1.jpg" ) InstagramAccountToggle( name = names[1], image = "https://randomuser.me/api/portraits/men/2.jpg" ) } } @OptIn(ExperimentalCoilApi::class) @Composable private fun InstagramAccountToggle(name: String, image: String) { var selected by remember { mutableStateOf(false) } Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Box( modifier = Modifier .size(50.dp) .padding(6.dp) .background(color = Color.LightGray, shape = CircleShape) .clip(CircleShape) ) { Image( painter = rememberImagePainter(image), contentDescription = "", contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize() ) } Text(text = name) Spacer(modifier = Modifier.weight(1f)) Switch( checked = selected, onCheckedChange = { selected = !selected }, ) } } @Composable private fun ExpandableSection(name: String, content: @Composable () -> Unit) { var shouldExpand by remember { mutableStateOf(false) } Column() { Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .fillMaxWidth() .clickable { shouldExpand = !shouldExpand }) { Text( text = name, style = MaterialTheme.typography.subtitle1, modifier = Modifier.padding(12.dp) ) IconButton(onClick = { shouldExpand = !shouldExpand }) { Icon( if (!shouldExpand) Icons.Default.KeyboardArrowRight else Icons.Default.KeyboardArrowDown, contentDescription = "" ) } } if (shouldExpand) content() } } @Composable private fun MediaPlatformTogglesList() { Column( modifier = Modifier .fillMaxWidth() .padding(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { MediaPlatformToggle(name = "Face Book") MediaPlatformToggle(name = "Twitter") } } @Composable private fun MediaPlatformToggle(name: String) { var selected by remember { mutableStateOf(false) } Row( horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .fillMaxWidth() .padding(start = 12.dp) ) { Text(text = name) Switch(checked = selected, onCheckedChange = { selected = !selected }) } } @Composable private fun AdvancedSettings() { var shouldExpand by remember { mutableStateOf(false) } Column { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .padding(start = 12.dp) .clickable { shouldExpand = !shouldExpand } ) { Text(text = "Advanced Settings") IconButton(onClick = { shouldExpand = !shouldExpand }) { Icon( if (!shouldExpand) Icons.Default.KeyboardArrowRight else Icons.Default.KeyboardArrowDown, contentDescription = "", modifier = Modifier.size(20.dp) ) } } if (shouldExpand) { Spacer(modifier = Modifier.size(40.dp)) Divider() } } }
0
Kotlin
0
0
ccbb6f24f4265e3f8f0898afbe28fed376fada31
8,225
JetInstagram
Apache License 2.0
neuroph-plugin/src/com/thomas/needham/neurophidea/designer/editor/tset/TsetFileEditorProvider.kt
morristech
105,013,222
true
{"Kotlin": 738619, "Java": 172563, "Groovy": 112846, "Scala": 97266}
/* The MIT License (MIT) Copyright (c) 2016 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.thomas.needham.neurophidea.designer.editor.tset import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorPolicy import com.intellij.openapi.fileEditor.FileEditorProvider import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.thomas.needham.neurophidea.designer.psi.tset.TsetFileType import org.jetbrains.annotations.NonNls /** * Created by thoma on 12/07/2016. */ class TsetFileEditorProvider : FileEditorProvider{ companion object Data { @JvmStatic val LOG = Logger.getInstance("#com.thomas.needham.neurophidea.designer.editor.tset.TsetFileEditorProvider") @JvmStatic val TSET_EDITOR_KEY : Key<TsetEditor> = Key.create("tsetEditor") @JvmStatic @NonNls val TYPE_ID : String = "tset-editor" @JvmStatic @NonNls val LINE_ATTR : String = "line" @JvmStatic @NonNls val COLUMN_ATTR : String = "column" @JvmStatic @NonNls val SELECTION_START_LINE_ATTR : String = "selection-start-line" @JvmStatic @NonNls val SELECTION_START_COLUMN_ATTR : String = "selection-start-column" @JvmStatic @NonNls val SELECTION_END_LINE_ATTR : String = "selection-end-line" @JvmStatic @NonNls val SELECTION_END_COLUMN_ATTR : String = "selection-end-column" @JvmStatic @NonNls val RELATIVE_CARET_POSITION_ATTR : String = "relative-caret-position" @JvmStatic @NonNls val CARET_ELEMENT : String = "caret" @JvmStatic fun GetInstance() : TsetFileEditorProvider? { return ApplicationManager.getApplication().getComponent(TsetFileEditorProvider::class.java) } fun putTsetEditor(editor: Editor?, tsetEditor : TsetEditorImpl?){ editor?.putUserData(TSET_EDITOR_KEY,tsetEditor) } } override fun createEditor(p0 : Project, p1 : VirtualFile) : FileEditor { LOG.assertTrue(accept(p0,p1)) return TsetEditorImpl(p0,p1,this) } override fun getPolicy() : FileEditorPolicy { return FileEditorPolicy.NONE } override fun getEditorTypeId() : String { return TYPE_ID } override fun accept(p0 : Project, p1 : VirtualFile) : Boolean { return p1.fileType is TsetFileType } }
0
Kotlin
0
0
d9ec77c2b34e9b45bb57fd08386ae73e27c96880
3,513
Neuroph-Intellij-Plugin
MIT License
dsl/jpql/src/test/kotlin/com/linecorp/kotlinjdsl/dsl/jpql/expression/TrimTrailingDslTest.kt
line
442,633,985
false
{"Kotlin": 1959613, "JavaScript": 5144, "Shell": 1023}
package com.linecorp.kotlinjdsl.dsl.jpql.expression import com.linecorp.kotlinjdsl.dsl.jpql.queryPart import com.linecorp.kotlinjdsl.querymodel.jpql.expression.Expression import com.linecorp.kotlinjdsl.querymodel.jpql.expression.Expressions import org.assertj.core.api.WithAssertions import org.junit.jupiter.api.Test class TrimTrailingDslTest : WithAssertions { private val char1 = 'c' private val string1 = "string1" private val charExpression1 = Expressions.value(char1) private val stringExpression1 = Expressions.value(string1) @Test fun `trimTrailing() without a char, from() with a string`() { // when val expression = queryPart { trimTrailing().from(string1) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.trimTrailing( value = stringExpression1, ) assertThat(actual.toExpression()).isEqualTo(expected) } @Test fun `trimTrailing() without a char, from() with a string expression`() { // when val expression = queryPart { trimTrailing().from(stringExpression1) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.trimTrailing( value = stringExpression1, ) assertThat(actual.toExpression()).isEqualTo(expected) } @Test fun `trimTrailing() with a char, from() with a string`() { // when val expression = queryPart { trimTrailing(char1).from(string1) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.trimTrailing( character = charExpression1, value = stringExpression1, ) assertThat(actual.toExpression()).isEqualTo(expected) } @Test fun `trimTrailing() with a char, from() with a string expression`() { // when val expression = queryPart { trimTrailing(char1).from(stringExpression1) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.trimTrailing( character = charExpression1, value = stringExpression1, ) assertThat(actual.toExpression()).isEqualTo(expected) } @Test fun `trimTrailing() with a char expression, from() with a string`() { // when val expression = queryPart { trimTrailing(charExpression1).from(string1) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.trimTrailing( character = charExpression1, value = stringExpression1, ) assertThat(actual.toExpression()).isEqualTo(expected) } @Test fun `trimTrailing() with a char expression, from() with a string expression`() { // when val expression = queryPart { trimTrailing(charExpression1).from(stringExpression1) }.toExpression() val actual: Expression<String> = expression // for type check // then val expected = Expressions.trimTrailing( character = charExpression1, value = stringExpression1, ) assertThat(actual.toExpression()).isEqualTo(expected) } }
4
Kotlin
86
705
3a58ff84b1c91bbefd428634f74a94a18c9b76fd
3,537
kotlin-jdsl
Apache License 2.0
android/src/main/java/com/google/samples/apps/iosched/sync/userdata/gms/DriveHelper.kt
brentwatson
70,599,432
true
{"Gradle": 11, "Java Properties": 9, "Shell": 3, "Ignore List": 6, "Batchfile": 2, "Text": 10, "YAML": 2, "Markdown": 11, "HTML": 24, "CSS": 4, "JavaScript": 3, "Java": 206, "XML": 277, "JSON": 1, "Kotlin": 172, "SVG": 3, "Makefile": 2, "Ant Build System": 1, "INI": 7, "Maven POM": 2}
/* * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.sync.userdata.gms import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.common.api.Status import com.google.android.gms.drive.* import com.google.android.gms.drive.query.* import com.google.samples.apps.iosched.util.IOUtils import com.google.samples.apps.iosched.util.LogUtils.LOGD import com.google.samples.apps.iosched.util.LogUtils.makeLogTag import java.io.IOException import java.util.* /** * A helper class for creating, fetching and editing Drive AppData files */ class DriveHelper /** * Construct the helper with a [GoogleApiClient] that is connected. * @param apiClient The [GoogleApiClient] that is either connected or unconnected. */ (private val mGoogleApiClient: GoogleApiClient) { /** * Connect the [GoogleApiClient] if not already connected. * Note that this assumes you're already running in a background thread * and issues a `GoogleApiClient#blockingConnect()` call to connect. * @return ConnectionResult or null if already connected. */ fun connectIfNecessary(): ConnectionResult? { if (!mGoogleApiClient.isConnected) { return mGoogleApiClient.blockingConnect() } else { return null } } /** * This is essential to ensure that the Google Play services cache is up-to-date. * Call [com.google.android.gms.drive.DriveApi.requestSync] * @return [com.google.android.gms.common.api.Status] */ fun requestSync(): Status { return Drive.DriveApi.requestSync(mGoogleApiClient).await() } /** * Get or create the [DriveFile] named with `fileName` with * the specific `mimeType`. * @return Return the `DriveId` of the fetched or created file. */ fun getOrCreateFile(fileName: String, mimeType: String): DriveId { LOGD(TAG, "getOrCreateFile $fileName mimeType $mimeType") val file = getDriveFile(fileName, mimeType) LOGD(TAG, "getDriveFile returned " + file!!) if (file == null) { return createEmptyDriveFile(fileName, mimeType) } else { return file } } /** * Save the `DriveFile` with the specific driveId. * @param id [DriveId] of the file. * * * @param content The content to be saved in the `DriveFile`. * * * @return Return value indicates whether the save was successful. */ @Throws(IOException::class) fun saveDriveFile(id: DriveId, content: String): Boolean { val theFile = Drive.DriveApi.getFile(mGoogleApiClient, id) val result = theFile.open(mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).await() try { IOUtils.writeToStream(content, result.driveContents.outputStream) // Update the last viewed. val changeSet = MetadataChangeSet.Builder().setLastViewedByMeDate(Date()).build() return result.driveContents.commit(mGoogleApiClient, changeSet).await().isSuccess } catch (io: IOException) { result.driveContents.discard(mGoogleApiClient) throw io } } @Throws(IOException::class) fun getContentsFromDrive(id: DriveId): String? { val theFile = Drive.DriveApi.getFile(mGoogleApiClient, id) val result = theFile.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).await() val driveContents = result.driveContents try { if (driveContents != null) { return IOUtils.readAsString(driveContents.inputStream) } } finally { driveContents?.discard(mGoogleApiClient) } return null } /** * Create an empty file with the given `fileName` and `mimeType`. * @return [DriveId] of the specific file. */ private fun createEmptyDriveFile(fileName: String, mimeType: String): DriveId { val result = Drive.DriveApi.newDriveContents(mGoogleApiClient).await() val changeSet = MetadataChangeSet.Builder().setTitle(fileName).setMimeType(mimeType).setStarred(true).build() // Create a new file with the given changeSet in the AppData folder. val driveFileResult = Drive.DriveApi.getAppFolder(mGoogleApiClient).createFile(mGoogleApiClient, changeSet, result.driveContents).await() return driveFileResult.driveFile.driveId } /** * Search for a file with the specific name and mimeType * @return driveId for the file it if exists. */ private fun getDriveFile(fileName: String, mimeType: String): DriveId? { // Find the named file with the specific Mime type. val query = Query.Builder().addFilter(Filters.and( Filters.eq(SearchableField.TITLE, fileName), Filters.eq(SearchableField.MIME_TYPE, mimeType))).setSortOrder(SortOrder.Builder().addSortDescending(SortableField.MODIFIED_DATE).build()).build() var buffer: MetadataBuffer? = null try { buffer = Drive.DriveApi.getAppFolder(mGoogleApiClient).queryChildren(mGoogleApiClient, query).await().metadataBuffer if (buffer != null && buffer.count > 0) { LOGD(TAG, "got buffer " + buffer.count) return buffer.get(0).driveId } return null } finally { if (buffer != null) { buffer.close() } } } companion object { private val TAG = makeLogTag(DriveHelper::class.java) } }
0
Kotlin
0
0
e6f4a8ad4d1c84f55bfb5c3140c171af1792343b
6,201
iosched
Apache License 2.0
idea/testData/refactoring/introduceLambdaParameter/lambdaParamOfUnit.kt
JakeWharton
99,388,807
true
null
// WITH_DEFAULT_VALUE: false fun foo(a: Int) { } fun bar(a: Int) { <selection>foo(a + 1)</selection> } fun test() { bar(1) }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
135
kotlin
Apache License 2.0
godot-kotlin/godot-library/src/nativeGen/kotlin/godot/VisualShaderNodeFaceForward.kt
utopia-rise
238,721,773
false
{"Kotlin": 655494, "Shell": 171}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! ALL CHANGES TO IT WILL BE OVERWRITTEN ON EACH BUILD package godot import godot.internal.utils.invokeConstructor import kotlinx.cinterop.COpaquePointer open class VisualShaderNodeFaceForward : VisualShaderNode() { override fun __new(): COpaquePointer = invokeConstructor("VisualShaderNodeFaceForward", "VisualShaderNodeFaceForward") }
17
Kotlin
17
286
8d51f614df62a97f16e800e6635ea39e7eb1fd62
396
godot-kotlin-native
MIT License
app/src/main/java/org/stepic/droid/concurrency/IMainHandler.kt
ppbao
66,552,816
true
{"Java Properties": 2, "Gradle": 3, "Shell": 1, "Text": 3, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 2, "Proguard": 1, "Java": 310, "Kotlin": 156, "XML": 154, "JavaScript": 162}
package org.stepic.droid.concurrency interface IMainHandler : IHandler
0
Java
0
0
ce56a7abb6f18b1525d34cc0b12ec07c7df5dda9
72
stepic-android
Apache License 2.0
Laboratorio-10/app/src/main/java/com/example/laboratorio10/data/dao/MovieDao.kt
cabrera-evil
618,555,990
false
null
package com.example.laboratorio10.data.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import androidx.room.Transaction import com.example.laboratorio10.data.model.MovieModel import com.example.laboratorio10.data.model.MovieWithActor @Dao interface MovieDao { @Query("SELECT * FROM movie_table") suspend fun getAllMovies(): List<MovieModel> @Transaction @Insert suspend fun insertMovie(movie: MovieModel) @Query("SELECT * FROM movie_table WHERE movieId = :movieId") suspend fun getMovieWithActorsById(movieId: Int): MovieWithActor? }
0
Kotlin
0
0
8190d084d16b20b68a66334b30e0498bee676bdc
602
mobile-laboratories
MIT License
app/src/main/java/com/zmunm/oscilloscope/SampleActivity.kt
zmunm
333,462,536
false
null
package com.zmunm.oscilloscope import android.app.Activity import com.zmunm.generated.validate class SampleActivity: Activity() { @OscilloscopeEvent val event: Boolean = true.validate() }
0
Kotlin
0
0
6005a503162ee2eeb34d11e4be4dcd9c38a2a104
197
oscilloscope
Apache License 2.0
library/src/commonMain/kotlin/stackState.kt
kyay10
791,451,737
false
{"Kotlin": 182846, "JavaScript": 287}
public typealias StackState<T> = State<List<T>> public suspend operator fun <T> StackState<T>.plusAssign(value: T) = modify { it + value } public suspend fun <T> StackState<T>.getLast() = ask().value.last() public suspend inline fun <T> StackState<T>.modifyLast(f: (T) -> T) = plusAssign(f(getLast())) public suspend fun <T, R> runStackState(value: T, body: suspend StackState<T>.() -> R): R = runState(listOf(value), body) public suspend fun <T, R> StackState<T>.pushStackState(value: T, body: suspend () -> R): R = pushState(listOf(value), body) public suspend fun <T, R> StackState<T>.pushStackStateWithCurrent(value: T, body: suspend () -> R): R { val current = askOrNull()?.value ?: emptyList() return pushState(current + value, body) }
5
Kotlin
0
8
f608d6f3e3aab65774eb86eaeb09ce0a57698ce4
754
KonTinuity
Apache License 2.0
app/src/main/java/com/ealva/toque/ui/library/smart/RatingEditor.kt
pandasys
311,981,753
false
null
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ealva.toque.ui.library.smart import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.LocalContentColor import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.testTag import androidx.compose.ui.unit.dp import com.ealva.toque.R import com.ealva.toque.common.Rating import com.ealva.toque.common.StarRating import com.ealva.toque.common.toRating import com.ealva.toque.common.toStarRating import com.ealva.toque.db.smart.MatcherData import com.ealva.toque.db.smart.RatingMatcher import com.ealva.toque.ui.theme.toqueTypography import com.gowtham.ratingbar.RatingBar import com.gowtham.ratingbar.RatingBarConfig import com.gowtham.ratingbar.RatingBarStyle import com.gowtham.ratingbar.StepSize @Composable fun RatingEditor( editorRule: EditorRule, ruleDataChanged: (EditorRule, MatcherData) -> Unit, modifier: Modifier = Modifier ) { when (editorRule.rule.matcher as RatingMatcher) { RatingMatcher.IsInTheRange -> RatingRangeEditor(editorRule, ruleDataChanged, modifier) else -> SingleRatingEditor(editorRule, ruleDataChanged, modifier) } } @Composable private fun SingleRatingEditor( editorRule: EditorRule, ruleDataChanged: (EditorRule, MatcherData) -> Unit, modifier: Modifier ) { Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) .then(modifier), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { RatingBar( modifier = Modifier .wrapContentSize() .clearAndSetSemantics { testTag = "RatingBar" }, value = editorRule.firstStarRating.value, config = RatingBarConfig() .size(22.dp) .padding(2.dp) .isIndicator(false) .activeColor(LocalContentColor.current) .inactiveColor(LocalContentColor.current) .stepSize(StepSize.HALF) .style(RatingBarStyle.HighLighted), onValueChange = { ruleDataChanged( editorRule, editorRule.rule.data.copy(first = StarRating(it).toRating().value.toLong()) ) }, onRatingChanged = { }, ) } } @Composable private fun RatingRangeEditor( editorRule: EditorRule, ruleDataChanged: (EditorRule, MatcherData) -> Unit, modifier: Modifier ) { var low: Float by remember { mutableStateOf(editorRule.firstStarRating.value) } var high: Float by remember { mutableStateOf(editorRule.secondStarRating.value) } fun lowChanged(newLow: Float) { if (newLow >= high) { if (newLow == StarRating.STAR_5.value) { high = StarRating.STAR_5.value low = StarRating.STAR_4_5.value } else { low = newLow high = newLow + StarRating.STAR_0_5.value } } else { low = newLow } } fun highChanged(newHigh: Float) { if (low >= newHigh) { if (newHigh == StarRating.STAR_0.value) { low = StarRating.STAR_0.value high = StarRating.STAR_0_5.value } else { high = newHigh low = newHigh - StarRating.STAR_0_5.value } } else { high = newHigh } } fun ratingChanged(rule: EditorRule) { ruleDataChanged( rule, MatcherData( "", StarRating(low).toRating().value.toLong(), StarRating(high).toRating().value.toLong() ) ) } Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) .then(modifier), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { RatingBar( modifier = Modifier .wrapContentSize() .clearAndSetSemantics { testTag = "RatingBarLow" }, value = low, config = RatingBarConfig() .size(22.dp) .padding(2.dp) .isIndicator(false) .activeColor(LocalContentColor.current) .inactiveColor(LocalContentColor.current) .stepSize(StepSize.HALF) .style(RatingBarStyle.HighLighted), onValueChange = { lowChanged(it) }, onRatingChanged = { ratingChanged(editorRule) }, ) Text( modifier = Modifier.padding(horizontal = 8.dp), text = stringResource(id = R.string.to), style = toqueTypography.caption ) RatingBar( modifier = Modifier .wrapContentSize() .clearAndSetSemantics { testTag = "RatingBarHigh" }, value = high, config = RatingBarConfig() .size(22.dp) .padding(2.dp) .isIndicator(false) .activeColor(LocalContentColor.current) .inactiveColor(LocalContentColor.current) .stepSize(StepSize.HALF) .style(RatingBarStyle.HighLighted), onValueChange = { highChanged(it) }, onRatingChanged = { ratingChanged(editorRule) }, ) } } private val EditorRule.firstStarRating: StarRating get() = Rating(rule.data.first.toInt()).toStarRating() private val EditorRule.secondStarRating: StarRating get() = Rating(rule.data.second.toInt()).toStarRating()
0
Kotlin
0
0
f64ca9023f2384d322d924ceeb0cf3c8c5a1809d
6,201
toque
Apache License 2.0
paging/src/commonMain/kotlin/org/mobilenativefoundation/store/paging5/LaunchPagingStore.kt
MobileNativeFoundation
226,169,258
false
null
@file:Suppress("UNCHECKED_CAST") package org.mobilenativefoundation.store.paging5 import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import org.mobilenativefoundation.store.core5.ExperimentalStoreApi import org.mobilenativefoundation.store.core5.StoreData import org.mobilenativefoundation.store.core5.StoreKey import org.mobilenativefoundation.store.store5.MutableStore import org.mobilenativefoundation.store.store5.Store import org.mobilenativefoundation.store.store5.StoreReadRequest import org.mobilenativefoundation.store.store5.StoreReadResponse private class StopProcessingException : Exception() /** * Initializes and returns a [StateFlow] that reflects the state of the Store, updating by a flow of provided keys. * @param scope A [CoroutineScope]. * @param keys A flow of keys that dictate how the Store should be updated. * @param stream A lambda that invokes [Store.stream]. * @return A read-only [StateFlow] reflecting the state of the Store. */ @ExperimentalStoreApi private fun <Id : Any, Key : StoreKey<Id>, Output : StoreData<Id>> launchPagingStore( scope: CoroutineScope, keys: Flow<Key>, stream: (key: Key) -> Flow<StoreReadResponse<Output>>, ): StateFlow<StoreReadResponse<Output>> { val stateFlow = MutableStateFlow<StoreReadResponse<Output>>(StoreReadResponse.Initial) scope.launch { try { val firstKey = keys.first() if (firstKey !is StoreKey.Collection<*>) throw IllegalArgumentException("Invalid key type") stream(firstKey).collect { response -> if (response is StoreReadResponse.Data<Output>) { val joinedDataResponse = joinData(firstKey, stateFlow.value, response) stateFlow.emit(joinedDataResponse) } else { stateFlow.emit(response) } if (response is StoreReadResponse.Data<Output> || response is StoreReadResponse.Error || response is StoreReadResponse.NoNewData ) { throw StopProcessingException() } } } catch (_: StopProcessingException) { } keys.drop(1).collect { key -> if (key !is StoreKey.Collection<*>) throw IllegalArgumentException("Invalid key type") val firstDataResponse = stream(key).first { it.dataOrNull() != null } as StoreReadResponse.Data<Output> val joinedDataResponse = joinData(key, stateFlow.value, firstDataResponse) stateFlow.emit(joinedDataResponse) } } return stateFlow.asStateFlow() } /** * Initializes and returns a [StateFlow] that reflects the state of the [Store], updating by a flow of provided keys. * @see [launchPagingStore]. */ @ExperimentalStoreApi fun <Id : Any, Key : StoreKey<Id>, Output : StoreData<Id>> Store<Key, Output>.launchPagingStore( scope: CoroutineScope, keys: Flow<Key>, ): StateFlow<StoreReadResponse<Output>> { return launchPagingStore(scope, keys) { key -> this.stream(StoreReadRequest.fresh(key)) } } /** * Initializes and returns a [StateFlow] that reflects the state of the [Store], updating by a flow of provided keys. * @see [launchPagingStore]. */ @ExperimentalStoreApi fun <Id : Any, Key : StoreKey<Id>, Output : StoreData<Id>> MutableStore<Key, Output>.launchPagingStore( scope: CoroutineScope, keys: Flow<Key>, ): StateFlow<StoreReadResponse<Output>> { return launchPagingStore(scope, keys) { key -> this.stream<Any>(StoreReadRequest.fresh(key)) } } @ExperimentalStoreApi private fun <Id : Any, Key : StoreKey.Collection<Id>, Output : StoreData<Id>> joinData( key: Key, prevResponse: StoreReadResponse<Output>, currentResponse: StoreReadResponse.Data<Output>, ): StoreReadResponse.Data<Output> { val lastOutput = when (prevResponse) { is StoreReadResponse.Data<Output> -> prevResponse.value as? StoreData.Collection<Id, StoreData.Single<Id>> else -> null } val currentData = currentResponse.value as StoreData.Collection<Id, StoreData.Single<Id>> val joinedOutput = (lastOutput?.insertItems(key.insertionStrategy, currentData.items) ?: currentData) as Output return StoreReadResponse.Data(joinedOutput, currentResponse.origin) }
57
null
202
3,174
f9072fc59cc8bfe95cfe008cc8a9ce999301b242
4,609
Store
Apache License 2.0
pleo-antaeus-core/src/main/kotlin/io/pleo/antaeus/core/utils/TimeService.kt
jjaimez
204,093,390
true
{"Kotlin": 42847, "Shell": 861, "Dockerfile": 249}
package io.pleo.antaeus.core.utils import java.time.* class TimeService(timeZone:String) { val timeZone = timeZone fun isFirst(): Boolean{ //return true to fake first return LocalDate.now(ZoneId.of(this.timeZone)).dayOfMonth == 1 } fun getDistanceToFirstOfNextMonth(): Long { val nextMonth = LocalDateTime.now(ZoneId.of(timeZone)).plusMonths(1) val midNight = LocalTime.of(0,0) val firstOfNextMonth = LocalDateTime.of(LocalDate.of(nextMonth.year, nextMonth.month, 1),midNight) //return 1000 to see how delay works return Duration.between(LocalDateTime.now(ZoneId.of(timeZone)), firstOfNextMonth).toMillis() } }
0
Kotlin
0
0
bd37516d71403ab2cbfe5f25324c46fb3141928f
699
antaeus
Creative Commons Zero v1.0 Universal
src/main/kotlin/org/jetbrains/academy/test/system/models/Visibility.kt
jetbrains-academy
632,174,674
false
null
package org.jetbrains.academy.test.system.models import java.lang.reflect.Field import java.lang.reflect.Modifier /** * Represents visibility of variables, methods, classes. etc. */ enum class Visibility(val key: String) { PUBLIC("public"), PRIVATE("private"), ; } fun Field.getVisibility() = this.modifiers.getVisibility() fun Int.getVisibility(): Visibility? { if (Modifier.isPublic(this)) { return Visibility.PUBLIC } if (Modifier.isPrivate(this)) { return Visibility.PRIVATE } return null }
0
Kotlin
0
0
ea06c9a3db4268b6b58790662519845f0388785c
549
kotlin-test-framework
MIT License
src/main/kotlin/net/casualuhc/uhc/minigame/uhc/UHCPhase.kt
CasualUHC
334,382,250
false
null
package net.casualuhc.uhc.minigame.uhc import net.casualuhc.arcade.minigame.MinigamePhase enum class UHCPhase: MinigamePhase { Setup, Lobby, Ready, Start, Active, End; override val id: String = name.lowercase() }
0
Kotlin
0
3
3e4645fa33ea24584b0e9cf9c77008fa694f80d5
223
UHC-Mod
MIT License
src/main/kotlin/data/UserInfo.kt
gordinmitya
416,109,553
false
null
package data class UserInfo( val rating: Int, val topPosition: Int ) { init { require(topPosition >= 0) } }
0
Kotlin
1
1
386188b6bd322a3e449db5796175812fa8874d67
133
PingRatingBot
MIT License
shared/src/commonMain/kotlin/ml/dev/kotlin/minigames/shared/util/SerializationUtil.kt
avan1235
455,960,870
false
{"Kotlin": 302039, "HTML": 5977, "Swift": 3530, "Dockerfile": 1521, "JavaScript": 1278, "Shell": 883, "Ruby": 115}
package ml.dev.kotlin.minigames.shared.util import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.cbor.Cbor @OptIn(ExperimentalSerializationApi::class) val GameSerialization = Cbor
0
Kotlin
2
57
cc6696090b503b36e5289834ac83ae1ce57cb84e
216
mini-games
MIT License
presentation/src/test/kotlin/com/popalay/cardme/business/CardInteractorTest.kt
Popalay
83,484,077
false
null
package com.popalay.cardme.business import com.nhaarman.mockito_kotlin.argumentCaptor import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import com.popalay.cardme.domain.interactor.CardInteractor import com.popalay.cardme.data.models.Card import com.popalay.cardme.data.models.Holder import com.popalay.cardme.data.repositories.CardRepository import com.popalay.cardme.data.repositories.DebtRepository import com.popalay.cardme.data.repositories.HolderRepository import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Single import org.junit.Before import org.junit.Test import org.mockito.Mockito.verify import kotlin.test.assertEquals class CardInteractorTest { private lateinit var cardRepository: CardRepository private lateinit var holderRepository: HolderRepository private lateinit var debtRepository: DebtRepository private lateinit var cardInteractor: CardInteractor @Before fun beforeEachTest() { cardRepository = mock<CardRepository>() holderRepository = mock<HolderRepository>() debtRepository = mock<DebtRepository>() cardInteractor = CardInteractor(cardRepository, holderRepository, debtRepository) } @Test fun get_Success() { val cardNumber = "6767 8989 5454 5555" val card = Card(number = cardNumber) whenever(cardRepository.get(cardNumber)).thenReturn(Flowable.just(card)) val testObserver = cardInteractor.get(cardNumber).test() testObserver.awaitTerminalEvent() verify(cardRepository).get(cardNumber) testObserver .assertNoErrors() .assertValue { it == card } .assertComplete() } @Test fun validateCard_Success() { val cardNumber = "8876437654376548" whenever(cardRepository.cardIsNew(cardNumber)).thenReturn(Single.just(true)) val testObserver = cardInteractor.checkCardExist(cardNumber).test() testObserver.awaitTerminalEvent() verify(cardRepository).cardIsNew(cardNumber) testObserver .assertNoErrors() .assertComplete() } @Test fun validateCard_Failed() { val cardNumber = "8876437654376548" whenever(cardRepository.cardIsNew(cardNumber)).thenReturn(Single.just(false)) val testObserver = cardInteractor.checkCardExist(cardNumber).test() testObserver.awaitTerminalEvent() verify(cardRepository).cardIsNew(cardNumber) testObserver .assertError(AppException::class.java) .assertTerminated() } @Test fun hasAllData_True() { val holder = Holder(name = "Denis") val card = Card(holder = holder) val testObserver = cardInteractor.hasAllData(card, holder.name).test() testObserver.awaitTerminalEvent() testObserver .assertNoErrors() .assertValue { it } .assertComplete() } @Test fun hasAllData_False() { val holder = Holder(name = "") val card = Card(holder = holder) val testObserver = cardInteractor.hasAllData(card, holder.name).test() testObserver.awaitTerminalEvent() testObserver .assertNoErrors() .assertValue { !it } .assertComplete() } @Test fun getAll_Success() { val cards = (1..5).map { Card() }.toMutableList() val trashedCard = Card(isTrash = true) cards.add(trashedCard) whenever(cardRepository.getAll()).thenReturn(Flowable.fromCallable { cards.remove(trashedCard) cards }) val testObserver = cardInteractor.getAll().test() testObserver.awaitTerminalEvent() verify(cardRepository).getAll() testObserver .assertNoErrors() .assertValue { it.count() == 5 } .assertComplete() } @Test fun getTrashed_Success() { val cards = (1..5).map { Card() }.toMutableList() val trashedCard = Card(isTrash = true) cards.add(trashedCard) whenever(cardRepository.getAllTrashed()).thenReturn(Flowable.fromCallable { listOf(trashedCard) }) val testObserver = cardInteractor.getAllTrashed().test() testObserver.awaitTerminalEvent() verify(cardRepository).getAllTrashed() testObserver .assertNoErrors() .assertValue { it.count() == 1 } .assertComplete() } @Test fun updateCards_Success() { val cards = (1..5).map { Card(position = it * 3, generatedBackgroundSeed = 1L) }.toMutableList() val cardsRePositioned = (1..5).map { Card(position = it - 1, generatedBackgroundSeed = 1L) }.toMutableList() whenever(cardRepository.update(cards)).thenReturn(Completable.complete()) val testObserver = cardInteractor.update(cards).test() testObserver.awaitTerminalEvent() argumentCaptor<List<Card>>().apply { verify(cardRepository).update(capture()) assertEquals(cardsRePositioned, firstValue) } testObserver .assertNoErrors() .assertComplete() } @Test fun markAsTrash_Success() { val card = Card() whenever(cardRepository.markAsTrash(card)).thenReturn(Completable.complete()) whenever(holderRepository.removeCard(card)).thenReturn(Completable.complete()) val testObserver = cardInteractor.markAsTrash(card).test() testObserver.awaitTerminalEvent() verify(cardRepository).markAsTrash(card) verify(holderRepository).removeCard(card) testObserver .assertNoErrors() .assertComplete() } @Test fun restart_Success() { val card = Card(isTrash = true) whenever(holderRepository.addCard(card.holder.name, card)).thenReturn(Completable.complete()) whenever(cardRepository.restore(card)).thenReturn(Completable.complete()) val testObserver = cardInteractor.restore(card).test() testObserver.awaitTerminalEvent() verify(cardRepository).restore(card) verify(holderRepository).addCard(card.holder.name, card) testObserver .assertNoErrors() .assertComplete() } @Test fun removeTrashed_Success() { whenever(cardRepository.removeTrashed()).thenReturn(Completable.complete()) whenever(holderRepository.removeTrashed()).thenReturn(Completable.complete()) whenever(debtRepository.removeTrashed()).thenReturn(Completable.complete()) val testObserver = cardInteractor.emptyTrash().test() testObserver.awaitTerminalEvent() verify(cardRepository).removeTrashed() verify(holderRepository).removeTrashed() verify(debtRepository).removeTrashed() testObserver .assertNoErrors() .assertComplete() } @Test fun prepareForSharing_Success() { val card = Card() whenever(cardRepository.prepareForSharing(card)).thenReturn(Single.just("card.json")) val testObserver = cardInteractor.prepareForSharing(card).test() testObserver.awaitTerminalEvent() verify(cardRepository).prepareForSharing(card) testObserver .assertNoErrors() .assertComplete() } @Test fun getFromJson_Success() { val card = Card() val cardJson = "card.json" whenever(cardRepository.getFromJson(cardJson)).thenReturn(Single.just(card)) val testObserver = cardInteractor.getFromJson(cardJson).test() testObserver.awaitTerminalEvent() verify(cardRepository).getFromJson(cardJson) testObserver .assertNoErrors() .assertComplete() } }
1
Kotlin
3
20
271b0697095ebe5b532726ffb66826243a0b6f3b
7,955
Cardme
Apache License 2.0
oss-sdk/src/main/java/com/fzm/oss/sdk/model/PutObjectRequest.kt
txchat
507,831,442
false
{"Kotlin": 2234450, "Java": 384844}
package com.fzm.oss.sdk.model import android.net.Uri import java.io.File import java.io.InputStream /** * @author zhengjy * @since 2021/08/18 * Description: */ class PutObjectRequest( /** * 文件名(包含路径) */ val objectKey: String, /** * 上传文件的二进制 */ val uploadData: ByteArray? = null, /** * 文件Uri */ val uploadUri: Uri? = null, /** * 文件输入流 */ var fileInput: InputStream? = null, /** * 文件 */ var file: File? = null, /** * 文件大小 */ var contentLength: Long = 0L, endPoint: String? = null, ) : OSSRequest(endPoint)
0
Kotlin
1
1
6a3c6edf6ae341199764d4d08dffd8146877678b
621
ChatPro-Android
MIT License
app/src/main/java/com/senex/timetable/di/DaoModule.kt
Senex-x
458,101,117
false
{"Kotlin": 165234}
package com.senex.timetable.di import com.senex.timetable.data.database.AppDatabase import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class DaoModule { @Singleton @Provides fun provideDailyScheduleDao( appDatabase: AppDatabase, ) = appDatabase.dailyScheduleDao() @Singleton @Provides fun provideScheduleDao( appDatabase: AppDatabase, ) = appDatabase.scheduleDao() @Singleton @Provides fun provideGroupDao( appDatabase: AppDatabase, ) = appDatabase.groupDao() @Singleton @Provides fun provideDailySubjectDao( appDatabase: AppDatabase, ) = appDatabase.subjectDao() @Singleton @Provides fun provideElectiveSubjectDao( appDatabase: AppDatabase, ) = appDatabase.electiveSubjectDao() @Singleton @Provides fun provideEnglishSubjectDao( appDatabase: AppDatabase, ) = appDatabase.englishSubjectDao() }
1
Kotlin
1
7
d5ce2dbecaa8a8376de2c541ab18ab3901315c1a
975
itis-timetable
MIT License
features/lock/src/main/java/com/fappslab/features/lock/navigation/LockNavigationImpl.kt
F4bioo
693,834,465
false
{"Kotlin": 304361, "Python": 2171, "Shell": 900}
package com.fappslab.features.lock.navigation import android.content.Context import android.content.Intent import com.fappslab.features.common.navigation.LockNavigation import com.fappslab.features.common.navigation.ScreenTypeArgs import com.fappslab.features.lock.presentation.LockActivity import com.fappslab.features.lock.presentation.LockService internal class LockNavigationImpl : LockNavigation { override fun createLockIntent(context: Context, args: ScreenTypeArgs): Intent = LockActivity.createIntent(context, args) override fun createServiceIntent(context: Context): Intent = LockService.createIntent(context) }
0
Kotlin
0
0
3a4247596555400bf2128ded9f54aaa9491de0a8
649
Seedcake
MIT License
app/src/main/java/com/agnibh/weatherapp/MainActivity.kt
Aritram26
803,481,602
false
{"Kotlin": 10765}
package com.agnibh.weatherapp import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.location.Address import android.location.Geocoder import android.location.LocationManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.WindowManager import android.widget.Toast import androidx.core.app.ActivityCompat import com.agnibh.weatherapp.databinding.ActivityMainBinding import com.android.volley.Request import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import com.squareup.picasso.Picasso import org.json.JSONException import java.io.IOException import java.util.Locale class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var weatherModel: ArrayList<WeatherModel> private lateinit var weatherAdapter: WeatherAdapter private lateinit var locationManager: LocationManager private val PERMISSION_CODE = 1 private lateinit var cityName: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.setFlags( WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS ) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) weatherModel = arrayListOf() weatherAdapter = WeatherAdapter(this, weatherModel) locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ), PERMISSION_CODE ) } val location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) cityName = getCityName(location!!.longitude, location.latitude) binding.cityName.text = cityName getWeatherInfo(cityName) binding.searchBtn.setOnClickListener { val city = binding.cityInputEditText.text if (city!!.isEmpty()) { Toast.makeText(this, "Please Enter City Name", Toast.LENGTH_SHORT).show() } else { binding.cityName.text = city getWeatherInfo(city.toString()) } } binding.weatherRecyclerView.adapter = weatherAdapter } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == PERMISSION_CODE) { if(grantResults.isEmpty() && grantResults[0] != PackageManager.PERMISSION_GRANTED){ Toast.makeText(this,"Please provide the permission",Toast.LENGTH_SHORT).show() finish() } } } private fun getWeatherInfo(cityName: String) { val applicationInfo = applicationContext.packageManager.getApplicationInfo( applicationContext.packageName, PackageManager.GET_META_DATA ) val apiKey = applicationInfo.metaData["keyValue"].toString() val url = "http://api.weatherapi.com/v1/forecast.json?key=$apiKey&q=$cityName&days=1&aqi=yes&alerts=yes" Log.d("location",url) val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null, { response -> weatherModel.clear() try { val temperature = response.getJSONObject("current").getString("temp_c") binding.temperature.text = resources.getString(R.string.temperature_celsius) val isDay = response.getJSONObject("current").getInt("is_day") if (isDay == 0) { Picasso.get() .load("https://unsplash.com/photos/a-person-in-a-field-with-a-light-on-their-head-SNliMkZHVig") .into(binding.backgroundImage) } else { Picasso.get() .load("https://unsplash.com/photos/bCFWTZoQlSQ") .into(binding.backgroundImage) } val condition = response.getJSONObject("current").getJSONObject("condition") .getString("text") binding.weatherCondition.text = condition val icon = response.getJSONObject("current").getJSONObject("condition") .getString("icon") Picasso.get().load("https:".plus(icon)).into(binding.weatherIcon) val windspeed = response.getJSONObject("current").getString("wind_speed") binding.windSpeed.text = resources.getString(R.string.wind_speed, windspeed) val humidity = response.getJSONObject("current").getString("humidity") binding.humidity.text = resources.getString(R.string.humidity, humidity) val cloud = response.getJSONObject("current").getString("cloud") binding.cloudy.text = resources.getString(R.string.cloudy, cloud) val feelsLike = response.getJSONObject("current").getString("feelslike_c") binding.realFeel.text = feelsLike val forecastObj=response.getJSONObject("forecast") val forecast = forecastObj.getJSONArray("forecastday").getJSONObject(0) val hourArray = forecast.getJSONArray("hour") for (i in 0 until hourArray.length()){ val hourObj = hourArray.getJSONObject(i) val time = hourObj.getString("time") val temperature = hourObj.getString("temp_c") val icon = hourObj.getJSONObject("condition").getString("icon") val wind = hourObj.getString("wind_kph") weatherModel.add(WeatherModel(time, temperature, icon, wind)) } weatherAdapter.notifyDataSetChanged() } catch (e: JSONException) { e.printStackTrace() } } ) { Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show() } val requestQueue = Volley.newRequestQueue(this) requestQueue.add(jsonObjectRequest) } private fun getCityName(longitude: Double, latitude: Double): String{ var cityName="Not Found" val geocoder= Geocoder(baseContext, Locale.getDefault()); try { var addresses: List<Address> = geocoder.getFromLocation(latitude, longitude, 10) for (address in addresses){ val city = address.locality if (city!=null&& city.isNotBlank()){ cityName= city } } } catch (e:IOException){ e.printStackTrace() } return cityName } }
0
Kotlin
0
0
cd795e2f486152b6db3b5dee63bca255018e46a2
7,714
Weather-app
MIT License
app/src/main/java/lang_import/org/app/DictCreateActivity.kt
lang-import
138,695,600
false
{"Kotlin": 57803}
package lang_import.org.app import android.os.Bundle import android.preference.PreferenceManager import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.widget.Button import android.widget.EditText import android.widget.Toast import org.jetbrains.anko.db.* import org.jetbrains.anko.startActivity as start class DictCreateActivity : AppCompatActivity() { private lateinit var viewManager: RecyclerView.LayoutManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val env = PreferenceManager.getDefaultSharedPreferences(this) val dictsList = env.getStringSet("customDicts", mutableSetOf()) setContentView(R.layout.dict_create_activity) viewManager = LinearLayoutManager(this) val completeBtn = findViewById<Button>(R.id.dict_complete) val txtInput = findViewById<EditText>(R.id.newDictName) //TODO common fun forceUpdateEnv() { env.edit().putInt("dummy", 0).apply() env.edit().putInt("dummy", 1).apply() } fun failMsg(txt: String): Boolean { val toast = Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_SHORT); toast.show() return true } completeBtn.setOnClickListener { val resTxt = txtInput.text.trim() var fail = false if (resTxt.length > 15) { fail = failMsg("Имя слишком длинное") } if (resTxt.length < 1) { fail = failMsg("Пустое значение") } if (resTxt in dictsList) { fail = failMsg("Словарь уже существует") } if (!fail) { dictsList.add(resTxt.toString()) env.edit().putStringSet("customDicts", dictsList).apply() forceUpdateEnv() database.use { createTable(resTxt.toString(), true, "id" to INTEGER + PRIMARY_KEY + UNIQUE, "ref" to TEXT, "translate" to TEXT) } finish() start<DictActivity>() } } } }
0
Kotlin
2
0
45a0a04cd92492806258de545a1efe5c5f2b8641
2,370
android-app
MIT License
kotlin/src/com/codeforces/round629/B.kt
programmerr47
248,502,040
false
null
package com.codeforces.round629 import java.util.* fun main() { // Creates an instance which takes input from standard input (keyboard) val reader = Scanner(System.`in`) task(reader) } //TODO improve private fun task(input: Scanner) { repeat(input.nextInt()) { val n = input.nextInt() val k = input.nextInt() var b1i = 1 var partialSum = 0 while (partialSum < k) { partialSum += b1i b1i++ } if (partialSum >= k) { b1i-- partialSum -= b1i } val b2i = k - partialSum - 1 println(buildString { repeat(n) { val bi = n - 1 - it append(if (bi == b2i || bi == b1i) 'b' else 'a') } }) } }
0
Kotlin
0
0
0b5fbb3143ece02bb60d7c61fea56021fcc0f069
799
problemsolving
Apache License 2.0
app/src/main/java/me/demo/yandexsimulator/data/remote/service/GoogleApiService.kt
devazimjon
602,052,895
false
null
package me.demo.yandexsimulator.data.remote.service import me.demo.yandexsimulator.data.model.response.LocationDecodeResponse import me.demo.yandexsimulator.data.model.response.ReverseDecodeResponse import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface GoogleApiService { @GET("geocode/json") suspend fun decodeLocation( @Query("address") address: String, @Query("key") key: String ): Response<LocationDecodeResponse> @GET("geocode/json") suspend fun reverseDecodePoint( @Query("latlng") latlng: String, @Query("key") key: String ): Response<ReverseDecodeResponse> @GET("place/textsearch/json") suspend fun searchLocation( @Query("query") query: String, @Query("key") key: String ): Response<LocationDecodeResponse> }
0
Kotlin
0
0
83a6a68f1b13c18c3cb0166100c76feeebe2d26e
842
appliedlabs-task
Apache License 2.0
src/main/kotlin/com/skillw/buffsystem/util/GsonUtils.kt
Skillw
522,222,897
false
{"Kotlin": 123854, "JavaScript": 3718}
package com.skillw.buffsystem.util import com.google.gson.Gson object GsonUtils { private val gson by lazy { Gson() } @JvmStatic fun String.parseToMap(): Map<String, Any> { return runCatching { gson.fromJson(this, Map::class.java) }.getOrNull()?.mapKeys { it.key.toString() } ?.mapValues { it.value.toString() } ?: error("Wrong JSON: $this") } }
0
Kotlin
2
9
006c7479b22dd20e95b08b2fec41bfcda9cef7ee
396
BuffSystem
Creative Commons Zero v1.0 Universal
app/src/main/java/com/mzukic/superhero/data/network/response/SearchResponse.kt
eldarcelik
323,965,070
true
{"Kotlin": 36531}
package com.mzukic.superhero.data.network.response import com.google.gson.annotations.SerializedName data class SearchResponse( @SerializedName("response") val response: String? = null, @SerializedName("results") val superHeroesResponse: List<SuperHeroResponse>? = null, @SerializedName("results-for") val resultsFor: String? = null )
0
null
0
0
a0b96ab7fb36d6c7f0a6cea9a72aefde4d973c46
361
SuperHero
Apache License 2.0
src/main/kotlin/com/github/devlaq/arkitect/command/commands/Basics.kt
TeamArkitect
487,279,270
false
null
package com.github.devlaq.arkitect.command.commands import com.github.devlaq.arkitect.Arkitect import com.github.devlaq.arkitect.command.CommandContext import com.github.devlaq.arkitect.command.buildCommand import mindustry.Vars fun registerBasicCommands() { ArkitectCommand.build() } private object ArkitectCommand { fun build() { buildCommand { name = "arkitect" description = "See arkitect info and change configurations." action { fun sendHelp() { val modMeta = Vars.mods.list().find { it.meta.name.equals("Arkitect", ignoreCase = true) }.meta send("<%command.arkitect%>", modMeta.version) } if(args.isEmpty()) { sendHelp() } else { when(args[0]) { "locale" -> subcommandLocale() } } } } } fun CommandContext.subcommandLocale() { if (args.size <= 1) { send("<%command.arkitect.locale.available%>") Arkitect.bundleManager.availableLocales().forEach { send("<%command.arkitect.locale.available_element%>", it.getDisplayName(it), it.toLanguageTag()) } return } val languageTag = args[1] val locale = Arkitect.bundleManager.availableLocales().find { it.toLanguageTag().equals(languageTag, ignoreCase = true) } if(locale == null) { send("<%not_found.locale%>", languageTag) return } if(Arkitect.bundleManager.localeProvider() == locale) { send("<%command.arkitect.locale.not_changed%>", languageTag) return } Arkitect.settings?.locale = locale.toLanguageTag() send("<%command.arkitect.locale.changed%>", languageTag) } }
0
Kotlin
0
0
86e25416315abe0e83fc60715e4f85937351e394
1,909
Arkitect
MIT License
popkorn/src/commonMain/kotlin/core/model/Instance.kt
corbella83
221,466,107
false
null
package cc.popkorn.core.model import kotlin.reflect.KClass /** * Model class to be used to identify an instance * * @author <NAME> * @since 2.1.0 */ internal data class Instance<T : Any>( val instance: T, val type: KClass<out T> = instance::class, val environment: String? = null )
8
null
5
150
175a0a25efb3a8c484b710d2d48910f27d42a3f4
301
PopKorn
Apache License 2.0
app/src/main/java/com/example/android/databinding/basicsample/ui/testcase/adapter/TestAdapter.kt
SaikCaskey
277,276,459
false
null
package com.example.android.databinding.basicsample.ui.testcase.adapter import android.view.LayoutInflater import android.view.ViewGroup import com.example.android.databinding.basicsample.databinding.TestItemBinding import com.example.android.databinding.basicsample.ui.base.BaseAdapter import com.example.android.databinding.basicsample.ui.base.BaseViewHolder private val comparator = { old: String, new: String -> old.hashCode() == new.hashCode() } class TestAdapter(private val callbacks: AdapterCallbacks) : BaseAdapter<String>( areItemsSame = comparator, areContentsSame = comparator ) { override fun createViewHolder(layoutInflater: LayoutInflater, parent: ViewGroup, viewType: Int): BaseViewHolder<String> = TestItemViewHolder(TestItemBinding.inflate(layoutInflater, parent, false), callbacks) }
0
Kotlin
0
0
972fbf4c16e08315a3a8f0c337777744f9a24da6
839
AutoClearedOnDestroyViewExp
Apache License 2.0
asion-bot/asion-bot-web/src/main/java/org/asion/bot/selenium/processor/TmallPageChromeProcessor.kt
search-cloud
110,517,124
false
null
package org.asion.bot.selenium.processor import org.asion.bot.CaptureItem import org.asion.bot.selenium.processor.executor.ConsumeThread import org.asion.bot.selenium.processor.executor.ProduceThread import org.asion.bot.selenium.processor.executor.ThreadPoolManager import org.asion.bot.selenium.webdirver.ChromeDriverFactory import org.openqa.selenium.By import org.openqa.selenium.WebDriver import org.openqa.selenium.support.ui.WebDriverWait import java.util.* /** * * @author Asion. * @since 2018/5/17. */ class TmallPageChromeProcessor { companion object { @JvmStatic fun main(args: Array<String>) { val urls = ArrayList<String>(100) run { var i = 0 while (i < 100) { urls.add("") } } urls.forEach { url -> ThreadPoolManager.instance.produceThreadPool.submit(PageListProcessor(url)) } for (i in 0..4) { ThreadPoolManager.instance.consumeThreadPool.submit(ConsumeThread<String>()) } // 关闭线程池 ThreadPoolManager.instance.produceThreadPool.shutdown() ThreadPoolManager.instance.consumeThreadPool.shutdown() } } /** * 列表页处理者 * 处理列表页中,商品详情链接 */ private class PageListProcessor(val url: String) : ProduceThread<CaptureItem>(url) { /** * 打开页面 */ private fun openPage(): List<CaptureItem> { val driver = ChromeDriverFactory.chromeDriver // 让浏览器访问 driver.get(url) // 模拟点击销量 // 模拟点击小图模式 // 模拟点击产地中国 // 模拟获取翻页链接,放到队列里 // 获取 网页的 title println(" Page title is: " + driver.title) // 通过 id 找到 input 的 DOM val element = driver.findElement(By.id("mq")) // 输入关键字 element.sendKeys("dubbo") // 提交 input 所在的 form element.submit() // 通过判断 title 内容等待搜索页面加载完毕,间隔秒 WebDriverWait(driver, 5).until { (it as WebDriver).title.toLowerCase().startsWith("dubbo") } // 显示搜索结果页面的 title println(" Page title is: " + driver.title) return arrayListOf() } override fun produce(): List<CaptureItem> { return openPage() } } }
1
null
1
1
7e09a4b3ff04548e34b5e04ead054e8de674eb70
2,401
spring-boot-cloud-microservices-docker
Apache License 2.0
examples/kotlin-diktat/fix/smoke/src/main/kotlin/com/saveourtool/save/IgnoreLinesTest/NoIgnoreLines/Bug1Test.kt
saveourtool
340,654,529
false
{"Kotlin": 391563, "Shell": 601}
package test.smoke.src.main.kotlin fun readFile(foo: Foo) { var bar: Bar } class D {val x = 0 fun bar(): Bar {val qux = 42; return Bar(qux)} } // ;warn:0: [TEST] JUST_A_TEST // IGNORE_ME
68
Kotlin
4
42
677050c543230503a08954d30678c858c10a9ec0
193
save-cli
MIT License
solutions/src/test/kotlin/y2016/Y2016D03Test.kt
Jadarma
324,646,170
false
null
package y2016 import io.github.jadarma.aoc.test.AdventSpec import io.kotest.core.spec.DisplayName @DisplayName("Y2016D03 Squares With Three Sides") class Y2016D03Test : AdventSpec(Y2016D03(), { partOne { " 5 10 25" shouldOutput 0 } partTwo { val exampleInput = """ 101 301 501 102 302 502 103 303 503 201 401 601 202 402 602 203 403 603 """.trimIndent() exampleInput shouldOutput 6 } })
0
Kotlin
0
3
3f36fc11261dee5583947dc1e1fbaa1e7d656b47
527
advent-of-code-kotlin
MIT License
src/main/kotlin/Main.kt
spbu-coding-2023
793,050,222
false
{"Kotlin": 111773, "Shell": 189}
import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.window.Window import androidx.compose.ui.window.WindowPosition import androidx.compose.ui.window.application import androidx.compose.ui.window.rememberWindowState import model.graph.Graph import viewmodel.layouts.ForceAtlas2Layout import view.Canvas import viewmodel.CanvasViewModel import java.awt.Dimension val graph = Graph().apply { addVertex(1,"Thomas") addVertex(2, "Andrew") addVertex(3, "Iakov") addVertex(4, "John") addVertex(5, "Tristan") addVertex(6, "Arthur") addVertex(7, "Ryan") addEdge(1, 2, 1,1) addEdge(3, 4, 2,2) addEdge(1, 3, 3,3) addEdge(2, 3, 4,4) addEdge(5, 3, 5,5) addEdge(3, 7, 6,6) addVertex(8, "Pudge") addVertex(9,"Tiny") addVertex(10, "Lycan") addVertex(11,"Io") addVertex(12,"Lion") addVertex(13,"Sniper") addVertex(14,"Roshan") addEdge(14, 8, 6,7) addEdge(14, 9, 6,8) addEdge(14, 10, 6,9) addEdge(14, 11, 6,10) addEdge(14, 12, 6,11) addEdge(14, 13, 5,12) addEdge(14, 3, 0,13) addVertex(15, "1") addVertex(16,"2") addVertex(17, "3") addVertex(18,"4") addVertex(19,"5") addVertex(20,"6") addVertex(21,"7") addEdge(16, 15, 22,14) addEdge(15, 17, 1,15) addEdge(15, 18, 6,16) addEdge(19, 15, 2,17) addEdge(15, 21, 3,18) addEdge(20, 15, 5,19) addEdge(17, 20, 0,20) addEdge(14, 20, 0,21) } val windowSizeStart = Pair(820,640) @Composable @Preview fun App() { MaterialTheme { val canvasGraph = CanvasViewModel(graph, ForceAtlas2Layout()) MaterialTheme { Canvas(canvasGraph) } } } fun main() = application { Window(onCloseRequest = ::exitApplication, title = "ZeitNot", state = rememberWindowState(position = WindowPosition(Alignment.Center)) ) { window.minimumSize = Dimension(windowSizeStart.first, windowSizeStart.second) App() } }
1
Kotlin
0
0
f6f6416a319954bb9e30cce166ef51009d393b24
2,138
graphs-graph-7
MIT License
core/src/main/java/com/example/core/remote/response/base/BaseResponse.kt
luizcjr
347,671,875
false
null
package com.example.core.remote.response.base class BaseResponse<Data>( val categories: List<Data> )
0
Kotlin
0
0
41c8c1809b95994320e91761ea3758be078565f2
105
solar_system
MIT License
buildSrc/src/main/kotlin/SigningConfigure.kt
ForteScarlet
535,336,835
false
null
import org.gradle.api.Action import org.gradle.api.DomainObjectCollection import org.gradle.api.Project import org.gradle.api.publish.Publication import org.gradle.plugins.signing.SigningExtension import utils.systemProperty fun SigningExtension.setupSigning(publications: DomainObjectCollection<Publication>) { val keyId = systemProperty("GPG_KEY_ID") val secretKey = systemProperty("GPG_SECRET_KEY") val password = systemProperty("GPG_PASSWORD") if (keyId != null) { useInMemoryPgpKeys(keyId, secretKey, password) } setRequired(project.provider { project.gradle.taskGraph.hasTask("publish") }) sign(publications) } internal fun Project.`signing`(configure: Action<SigningExtension>): Unit = (this as org.gradle.api.plugins.ExtensionAware).extensions.configure("signing", configure)
3
null
3
7
c00c14897262a4dea87b6371695e83143d797911
836
kotlin-suspend-transform-compiler-plugin
MIT License
src/main/kotlin/icu/windea/pls/localisation/psi/ParadoxLocalisationExpressionElement.kt
DragonKnightOfBreeze
328,104,626
false
{"Kotlin": 3443954, "Java": 164903, "Lex": 42127, "HTML": 23760, "Shell": 2822}
package icu.windea.pls.localisation.psi import icu.windea.pls.lang.psi.* /** * @see ParadoxLocalisationConceptName */ interface ParadoxLocalisationExpressionElement: ParadoxExpressionElement { override fun setValue(value: String): ParadoxLocalisationExpressionElement }
12
Kotlin
5
41
99e8660a23f19642c7164c6d6fcafd25b5af40ee
278
Paradox-Language-Support
MIT License
src/test/kotlin/com/wikia/tibia/usecases/FixCreaturesTest.kt
benjaminkomen
82,451,650
false
null
package com.wikia.tibia.usecases import com.wikia.tibia.enums.ObjectClass import com.wikia.tibia.enums.Rarity import com.wikia.tibia.objects.Creature import com.wikia.tibia.objects.LootItem import com.wikia.tibia.objects.TibiaObject import com.wikia.tibia.objects.WikiObject import com.wikia.tibia.repositories.CreatureRepository import com.wikia.tibia.repositories.ItemRepository import io.vavr.control.Try import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.ArgumentMatchers.anyString import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import testutils.any internal class FixCreaturesTest { private lateinit var target: FixCreatures private val creatureRat = makeRat() private val creatureBear = makeBear() private val creatureWasp = makeWasp() private val creatureCyclops = makeCyclops() private val itemCheese = makeCheese() private val itemHoneycomb = makeHoneycomb() private val itemOldRag = makeOldRag() private val itemMeat = makeMeat() private lateinit var mockCreatureRepository: CreatureRepository private lateinit var mockItemRepository: ItemRepository @BeforeEach fun setup() { mockCreatureRepository = mock(CreatureRepository::class.java) mockItemRepository = mock(ItemRepository::class.java) target = FixCreatures(mockCreatureRepository, mockItemRepository) } @Test fun `should fix creatures - do nothing`() { // given `when`(mockCreatureRepository.getWikiObjects()).thenReturn(Try.success(listOf(creatureRat))) `when`(mockItemRepository.getWikiObjects()).thenReturn(Try.success(listOf(itemCheese))) // when val result = target.checkCreatures() // then assertEquals(0, result.size) } @Test fun `should fix creatures - add bear to droppedby of honeycomb`() { // given `when`(mockCreatureRepository.getWikiObjects()).thenReturn(Try.success(listOf(creatureBear))) `when`(mockItemRepository.getWikiObjects()).thenReturn(Try.success(listOf(itemHoneycomb))) `when`(mockItemRepository.saveWikiObject(any(WikiObject::class.java), anyString(), anyBoolean())) .thenReturn(Try.success("success")) // when val result = target.checkCreatures() // then assertEquals(1, result.size) assertTrue(result.containsKey("Honeycomb")) assertEquals(5, (result["Honeycomb"] ?: error("")).droppedby?.size) assertTrue((result["Honeycomb"] ?: error("")).droppedby?.contains("Bear") ?: false) assertFalse((result["Honeycomb"] ?: error("")).droppedby?.contains("Wasp") ?: false) } @Test fun `should fix creatures - add bear and wasp to droppedby of honeycomb`() { // given `when`(mockCreatureRepository.getWikiObjects()).thenReturn(Try.success(listOf(creatureBear, creatureWasp))) `when`(mockItemRepository.getWikiObjects()).thenReturn(Try.success(listOf(itemHoneycomb))) `when`(mockItemRepository.saveWikiObject(any(WikiObject::class.java), anyString(), anyBoolean())) .thenReturn(Try.success("success")) // when val result = target.checkCreatures() // then assertEquals(1, result.size) assertTrue(result.containsKey("Honeycomb")) assertEquals(6, (result["Honeycomb"] ?: error("")).droppedby?.size) assertTrue((result["Honeycomb"] ?: error("")).droppedby?.contains("Bear") ?: false) assertTrue((result["Honeycomb"] ?: error("")).droppedby?.contains("Wasp") ?: false) } @Test fun `should fix creatures - not add old rag to loot list of cyclops`() { // given `when`(mockCreatureRepository.getWikiObjects()).thenReturn(Try.success(listOf(creatureCyclops))) `when`(mockItemRepository.getWikiObjects()).thenReturn(Try.success(listOf(itemOldRag, itemMeat))) `when`(mockItemRepository.saveWikiObject(any(WikiObject::class.java), anyString(), anyBoolean())) .thenReturn(Try.success("success")) // when val result = target.checkCreatures() // then assertEquals(1, result.size) assertTrue(result.containsKey("Meat")) assertFalse(result.containsKey("Old Rag")) } private fun makeRat(): Creature { return Creature( actualname = "Rat", name = "Rat", loot = mutableListOf( LootItem(itemName = "Gold Coin", amount = "0-4"), LootItem(itemName = "Cheese") ) ) } private fun makeBear(): Creature { return Creature( actualname = "Bear", name = "Bear", loot = mutableListOf( LootItem(itemName = "Meat", amount = "0-4"), LootItem(itemName = "Ham", amount = "0-3"), LootItem(itemName = "Bear Paw", rarity = Rarity.SEMI_RARE), LootItem(itemName = "Honeycomb", rarity = Rarity.RARE) ) ) } private fun makeWasp(): Creature { return Creature( actualname = "Wasp", name = "Wasp", loot = mutableListOf( LootItem(itemName = "Honeycomb", rarity = Rarity.SEMI_RARE) ) ) } private fun makeCyclops(): Creature { return Creature( actualname = "Cyclops", name = "Cyclops", loot = mutableListOf( LootItem(itemName = "Meat") ) ) } private fun makeCheese(): TibiaObject { return TibiaObject( actualname = "Cheese", name = "Cheese", objectclass = ObjectClass.PLANTS_ANIMAL_PRODUCTS_FOOD_AND_DRINK.description, droppedby = mutableListOf("Cave Rat", "Corym Charlatan", "Green Djinn", "Mutated Human", "Rat") ) } private fun makeHoneycomb(): TibiaObject { return TibiaObject( actualname = "Honeycomb", name = "Honeycomb", objectclass = ObjectClass.PLANTS_ANIMAL_PRODUCTS_FOOD_AND_DRINK.description, droppedby = mutableListOf( "<NAME>", "Shadowpelt", "Werebear", "Willi Wasp" ) // Bear and Wasp are purposely missing ) } private fun makeOldRag(): TibiaObject { return TibiaObject( actualname = "Old Rag", name = "Old Rag", objectclass = ObjectClass.OTHER_ITEMS.description, droppedby = mutableListOf( "Cyclops", "Troll", "Wolf", ) ) } private fun makeMeat(): TibiaObject { return TibiaObject( actualname = "Meat", name = "Meat", objectclass = ObjectClass.OTHER_ITEMS.description, droppedby = mutableListOf() ) } }
7
Kotlin
1
3
0f8f6990e7f979c42686383ade85be27501efe83
7,171
TibiaWikiBot
MIT License
glance_app_widget/src/main/java/dev/vengateshm/glance_app_widget/service/WidgetUpdate.kt
vengateshm
670,054,614
false
{"Kotlin": 2030949, "Java": 55066}
package dev.vengateshm.glance_app_widget.service import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Context import android.content.Intent import android.util.Log import androidx.datastore.preferences.core.edit import com.google.gson.Gson import dagger.hilt.EntryPoints import dev.vengateshm.appcore.PreferenceProviderEntryPoint import dev.vengateshm.glance_app_widget.network.COVIDApiService import dev.vengateshm.glance_app_widget.network.LiveScoreApiService import dev.vengateshm.glance_app_widget.receiver.COVID19WidgetReceiver import dev.vengateshm.glance_app_widget.receiver.LiveCricketScoreWidgetReceiver import dev.vengateshm.glance_app_widget.utils.LIVE_MATCHES_RESPONSE_KEY import dev.vengateshm.glance_app_widget.utils.SUMMARY_RESPONSE_KEY suspend fun updateLiveScoreWidget(context: Context) { val preferenceProvider = EntryPoints.get(context.applicationContext, PreferenceProviderEntryPoint::class.java) .preferenceProvider() val liveMatchesResponse = LiveScoreApiService.getLiveScoreApi().getLiveMatches() Log.d("LIVE_SCORE_RESPONSE", liveMatchesResponse.toString()) preferenceProvider.prefsDatastore().edit { store -> store[LIVE_MATCHES_RESPONSE_KEY] = Gson().toJson(liveMatchesResponse) } context.sendWidgetUpdateBroadcast<LiveCricketScoreWidgetReceiver>() } suspend fun updateCOVID19Widget(context: Context) { val preferenceProvider = EntryPoints.get(context.applicationContext, PreferenceProviderEntryPoint::class.java) .preferenceProvider() val summaryResponse = COVIDApiService.getCOVIDApi().getSummary() Log.d("SUMMARY_RESPONSE", summaryResponse.toString()) preferenceProvider.prefsDatastore().edit { store -> store[SUMMARY_RESPONSE_KEY] = Gson().toJson(summaryResponse) } context.sendWidgetUpdateBroadcast<COVID19WidgetReceiver>() } inline fun <reified T> Context.sendWidgetUpdateBroadcast() { val componentName = ComponentName(this, T::class.java) val appWidgetIds = AppWidgetManager.getInstance(this).getAppWidgetIds(componentName) Intent(this, T::class.java).apply { this.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE this.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds) }.also { this.sendBroadcast(it) } }
0
Kotlin
0
1
6fa0f1c3170c56264ba85db4ac081831d6623575
2,350
Android-Kotlin-Jetpack-Compose-Practice
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/ui/LargeCardWeather.kt
wilsoncastiblanco
348,888,496
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.ui import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.vectorResource import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.disabled import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.androiddevchallenge.R import com.example.androiddevchallenge.ui.model.ScheduledWeather import com.example.androiddevchallenge.ui.model.Weather @Composable fun LargeCardWeather( modifier: Modifier = Modifier, scheduledWeather: ScheduledWeather ) { Surface( modifier = modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { Card( modifier = modifier.padding(16.dp), elevation = 8.dp, backgroundColor = scheduledWeather.weather.color, shape = RoundedCornerShape(40.dp) ) { Wall(modifier) Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.semantics { disabled() } ) { WeatherVector(scheduledWeather, scheduledWeather.screen.title) WeatherData(scheduledWeather) } } } } @OptIn(ExperimentalAnimationApi::class) @Composable private fun WeatherData(scheduledWeather: ScheduledWeather) { val weather = scheduledWeather.weather WeatherTemperature(weather, scheduledWeather) Text( text = weather.weatherDescriptor.descriptor, style = MaterialTheme.typography.h1, color = Color.White, fontSize = 64.sp, textAlign = TextAlign.Center, modifier = Modifier.semantics { this.disabled() } ) WindVelocity(scheduledWeather) } @Composable private fun WeatherTemperature( weather: Weather, scheduledWeather: ScheduledWeather ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.semantics(mergeDescendants = true) {} ) { Text( text = weather.temperature.current, style = MaterialTheme.typography.h1, color = Color.White, fontSize = 164.sp, textAlign = TextAlign.Center, modifier = Modifier.semantics { contentDescription = "The temperature ${scheduledWeather.screen.title} is ${weather.temperature.current}." } ) Column { TemperatureLimit( temperature = weather.temperature.high, contentDescription = "High Temperature", vectorResource = R.drawable.ic_temp_high ) TemperatureLimit( temperature = weather.temperature.low, contentDescription = "Low Temperature", vectorResource = R.drawable.ic_temp_low ) } } } @Composable private fun WindVelocity(scheduledWeather: ScheduledWeather) { val weather = scheduledWeather.weather Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, modifier = Modifier.semantics(mergeDescendants = true) {} ) { Icon( imageVector = ImageVector.vectorResource(id = R.drawable.ic_wind), contentDescription = null, modifier = Modifier.size(54.dp), tint = Color.White ) Text( text = weather.wind, style = MaterialTheme.typography.caption, color = Color.White, fontSize = 34.sp, textAlign = TextAlign.Center, modifier = Modifier.semantics { this.contentDescription = "The Wind Speed ${scheduledWeather.screen.title} is ${weather.wind}" } ) } } @Composable private fun TemperatureLimit( temperature: String, contentDescription: String, vectorResource: Int ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.semantics(mergeDescendants = true) {} ) { Icon( imageVector = ImageVector.vectorResource(id = vectorResource), contentDescription = null, modifier = Modifier.size(54.dp), tint = Color.White ) Text( text = temperature, style = MaterialTheme.typography.caption, color = Color.White, fontSize = 54.sp, textAlign = TextAlign.Center, modifier = Modifier.semantics { this.contentDescription = "$contentDescription $temperature" } ) } }
0
Kotlin
0
0
fba7c4d2874b551f47b2bbe9e104c7df543edb5e
6,238
composed-weather
Apache License 2.0
src/main/kotlin/Day04.kt
attilaTorok
573,174,988
false
null
import kotlin.streams.toList fun main() { fun getFullyContainedPairsCount(fileName: String): Int { var sumOfFullyContainedPairs = 0 readInputWithStream(fileName).useLines { val iterator = it.iterator() while (iterator.hasNext()) { val assignmentPairs = iterator.next().split(",") val assignmentA = assignmentPairs[0].split("-").stream().mapToInt(String::toInt).toList() val assignmentB = assignmentPairs[1].split("-").stream().mapToInt(String::toInt).toList() if (assignmentA[0] <= assignmentB[0] && assignmentA[1] >= assignmentB[1] || assignmentB[0] <= assignmentA[0] && assignmentB[1] >= assignmentA[1]) { sumOfFullyContainedPairs++ } } } return sumOfFullyContainedPairs } fun getOverlappingPairCount(fileName: String): Int { var sumOfFullyContainedPairs = 0 readInputWithStream(fileName).useLines { val iterator = it.iterator() while (iterator.hasNext()) { val assignmentPairs = iterator.next().split(",") val assignmentA = assignmentPairs[0].split("-").stream().mapToInt(String::toInt).toList() val assignmentB = assignmentPairs[1].split("-").stream().mapToInt(String::toInt).toList() if (assignmentA[0] <= assignmentB[0] && assignmentA[1] >= assignmentB[0] || assignmentB[0] <= assignmentA[0] && assignmentB[1] >= assignmentA[0]) { sumOfFullyContainedPairs++ } } } return sumOfFullyContainedPairs } println("Test") println("Number of pairs where one range fully contain the other should be 2! Counted: ${getFullyContainedPairsCount("Day04_test")}") println("Number of pairs where's an overlap is 4! Counted: ${getOverlappingPairCount("Day04_test")}") println() println("Exercise") println("Number of pairs where one range fully contain the other should be 547! Counted: ${getFullyContainedPairsCount("Day04")}") println("Number of pairs where's an overlap is 843! Counted: ${getOverlappingPairCount("Day04")}") }
0
Kotlin
0
0
1799cf8c470d7f47f2fdd4b61a874adcc0de1e73
2,246
AOC2022
Apache License 2.0
platforms/core-configuration/kotlin-dsl-integ-tests/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/PrecompiledScriptPluginAccessorsIntegrationTest.kt
gradle
302,322
false
{"Groovy": 33309780, "Java": 30797028, "Kotlin": 3552953, "C++": 888505, "JavaScript": 76180, "HTML": 15779, "CSS": 13668, "Shell": 12214, "XSLT": 7121, "C": 5785, "Scala": 2817, "Gherkin": 192, "Python": 58, "Brainfuck": 54}
/* * Copyright 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.integration import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.fixtures.AbstractKotlinIntegrationTest import org.gradle.test.fixtures.file.LeaksFileHandles import org.hamcrest.CoreMatchers.containsString import org.hamcrest.MatcherAssert.assertThat import org.junit.Test @LeaksFileHandles("Kotlin Compiler Daemon working directory") class PrecompiledScriptPluginAccessorsIntegrationTest : AbstractKotlinIntegrationTest() { @Test fun `accessors are available after script body change`() { withKotlinBuildSrc() val myPluginScript = withFile( "buildSrc/src/main/kotlin/my-plugin.gradle.kts", """ plugins { base } base { archivesName.set("my") } println("base") """ ) withDefaultSettings() withBuildScript( """ plugins { `my-plugin` } """ ) build("help").apply { assertThat(output, containsString("base")) } myPluginScript.appendText( """ println("modified") """.trimIndent() ) build("help").apply { assertThat(output, containsString("base")) assertThat(output, containsString("modified")) } } @Test fun `accessors are available after re-running tasks`() { withKotlinBuildSrc() withFile( "buildSrc/src/main/kotlin/my-plugin.gradle.kts", """ plugins { base } base { archivesName.set("my") } """ ) withDefaultSettings() withBuildScript( """ plugins { `my-plugin` } """ ) build("clean") build("clean", "--rerun-tasks") } @Test fun `accessors are available after registering plugin`() { withSettings( """ $defaultSettingsScript include("consumer", "producer") """ ) withBuildScript( """ plugins { `java-library` } allprojects { $repositoriesBlock } dependencies { api(project(":consumer")) } """ ) withFolders { "consumer" { withFile( "build.gradle.kts", """ plugins { id("org.gradle.kotlin.kotlin-dsl") } // Forces dependencies to be visible as jars // so we get plugin spec accessors ${forceJarsOnCompileClasspath()} dependencies { implementation(project(":producer")) } """ ) withFile( "src/main/kotlin/consumer-plugin.gradle.kts", """ plugins { `producer-plugin` } """ ) } "producer" { withFile( "build.gradle", """ plugins { id("java-library") id("java-gradle-plugin") } """ ) withFile( "src/main/java/producer/ProducerPlugin.java", """ package producer; public class ProducerPlugin { // Using internal class to verify https://github.com/gradle/gradle/issues/17619 public static class Implementation implements ${nameOf<Plugin<*>>()}<${nameOf<Project>()}> { @Override public void apply(${nameOf<Project>()} target) {} } } """ ) } } buildAndFail("assemble").run { // Accessor is not available on the first run as the plugin hasn't been registered. assertTaskExecuted( ":consumer:generateExternalPluginSpecBuilders" ) } existing("producer/build.gradle").run { appendText( """ gradlePlugin { plugins { producer { id = 'producer-plugin' implementationClass = 'producer.ProducerPlugin${'$'}Implementation' } } } """ ) } // Accessor becomes available after registering the plugin. build("assemble").run { assertTaskExecuted( ":consumer:generateExternalPluginSpecBuilders" ) } } private inline fun <reified T> nameOf() = T::class.qualifiedName @Test fun `accessors are available after renaming precompiled script plugin from project dependency`() { withSettings( """ $defaultSettingsScript include("consumer", "producer") """ ) withBuildScript( """ plugins { `java-library` `kotlin-dsl` apply false } allprojects { $repositoriesBlock } dependencies { api(project(":consumer")) } """ ) withFolders { "consumer" { withFile( "build.gradle.kts", """ plugins { id("org.gradle.kotlin.kotlin-dsl") } // Forces dependencies to be visible as jars // to reproduce the failure that happens in forkingIntegTest. // Incidentally, this also allows us to write `stable-producer-plugin` // in the plugins block below instead of id("stable-producer-plugin"). ${forceJarsOnCompileClasspath()} dependencies { implementation(project(":producer")) } """ ) withFile( "src/main/kotlin/consumer-plugin.gradle.kts", """ plugins { `stable-producer-plugin` } """ ) } "producer" { withFile( "build.gradle.kts", """ plugins { id("org.gradle.kotlin.kotlin-dsl") } """ ) withFile("src/main/kotlin/changing-producer-plugin.gradle.kts") withFile( "src/main/kotlin/stable-producer-plugin.gradle.kts", """ println("*42*") """ ) } } build("assemble").run { assertTaskExecuted( ":consumer:generateExternalPluginSpecBuilders" ) } existing("producer/src/main/kotlin/changing-producer-plugin.gradle.kts").run { renameTo(resolveSibling("changed-producer-plugin.gradle.kts")) } build("assemble").run { assertTaskExecuted( ":consumer:generateExternalPluginSpecBuilders" ) } } private fun forceJarsOnCompileClasspath() = """ configurations { compileClasspath { attributes { attribute( LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.JAR) ) } } } """ }
2,663
Groovy
4552
15,640
3fde2e4dd65124d0f3b2ef42f7e93446ccd7cced
8,841
gradle
Apache License 2.0
src/main/kotlin/com/rockthejvm/oop/OOBasics.kt
rockthejvm
763,427,015
false
{"Kotlin": 87747}
package com.rockthejvm.oop // object-oriented programming class Person(val firstName: String, val lastName: String, age: Int) { // PRIMARY constructor init { // run arbitrary code when this class is being instantiated println("initializing a Person with the name $firstName $lastName") } // can run multiple init blocks, they run one after another in the order they're defined in the class init { println("some other arbitrary code") } // can define PROPERTIES (data = vals, vars) and METHODS (behavior = functions) val fullName = "$firstName $lastName" // <-- PROPERTY var favMovie: String = "Forrest Gump" get() = field set(value: String) { // run any code here println("Setting the value of favMovie to $value") field = value // set(value) } /* Properties with get() and/or set(value) may or may not have backing fields (= memory zones for them). Create a backing field simply by using `field` in the implementation of get() or set(). The compiler detects if you have a backing field or not. - if you have a backing field, you MUST initialize the property - if you don't have a backing field, you CANNOT initialize the property */ // initialization lateinit var favLanguage: String fun initializeFavLang() { if (!this::favLanguage.isInitialized) favLanguage = "Kotlin" } fun greet() = // METHOD "Hi everyone, my name is $firstName" // OVERLOADING = multiple methods with the same name and different signatures fun greet(firstName: String): String = "Hi $firstName, my name is ${this.firstName}, how do you do?" // secondary (overloaded) constructors // MUST always invoke another constructor constructor(firstName: String, lastName: String): this(firstName, lastName, 0) constructor(): this("Jane", "Doe") } // immutable = data cannot be changed, must create another instance // mutable = data CAN be changed without allocating another instance fun main() { val daniel = Person("Daniel", "Ciocîrlan", 130) // constructed/instantiated a Person // ^^^^^^ an INSTANCE of Person val danielsFullName = daniel.fullName println(danielsFullName) println(daniel.greet()) println(daniel.greet("Anna")) val simplePerson = Person() println(simplePerson.fullName) // get and set println("Getting and setting") println(daniel.favMovie) // calling the get() method on the favMovie property daniel.favMovie = "Mission Impossible" // calling the set("Mission Impossible") method on the favMovie property println(daniel.favMovie) }
0
Kotlin
3
5
5d39e17a14ba1760c2772876aefc8de86b4fee18
2,728
kotlin-essentials
MIT License
app/src/main/java/com/example/friendzone/viewmodel/story/StoryViewModel.kt
mohitdamke
839,901,877
false
{"Kotlin": 266468}
package com.example.friendzone.viewmodel.story import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.friendzone.data.model.StoryModel import com.example.friendzone.data.model.UserModel import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class StoryViewModel : ViewModel() { private val db = FirebaseDatabase.getInstance() val story = db.getReference("story") private var _storyAndUsers = MutableLiveData<List<Pair<StoryModel, UserModel>>>() val storyAndUsers: LiveData<List<Pair<StoryModel, UserModel>>> = _storyAndUsers init { fetchStoryAndUsers { _storyAndUsers.value = it } } private fun fetchStoryAndUsers(onResult: (List<Pair<StoryModel, UserModel>>) -> Unit) { story.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val result = mutableListOf<Pair<StoryModel, UserModel>>() for (storySnapshot in snapshot.children) { val story = storySnapshot.getValue(StoryModel::class.java) story.let { fetchUserFromStory(it!!) { user -> result.add(0, it to user) if (result.size == snapshot.childrenCount.toInt()) { onResult(result) } } } } } override fun onCancelled(error: DatabaseError) { TODO("Not yet implemented") } }) } private fun fetchUserFromStory(story: StoryModel, onResult: (UserModel) -> Unit) { db.getReference("users").child(story.userId) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val user = snapshot.getValue(UserModel::class.java) user?.let(onResult) } override fun onCancelled(error: DatabaseError) { TODO("Not yet implemented") } }) } }
0
Kotlin
0
2
8fc0cccbc4d56f7321a3a168b65c78af1684c196
2,405
Friend-Zone-App
MIT License
app/src/main/java/com/liyulive/timeer/logic/database/TimeErDatabase.kt
Liyulive
321,229,647
false
null
package com.liyulive.timeer.logic.database import com.liyulive.timeer.TimeErApplication import com.liyulive.timeer.logic.TimerDB import com.liyulive.timeer.logic.model.Timer object TimeErDatabase { private val timerDao = TimerDB.getDatabase(TimeErApplication.context).timerDao() fun insertTimer(timer: Timer) = timerDao.insertTimer(timer) fun updateTimer(newTimer: Timer) = timerDao.updateTimer(newTimer) fun loadAllTimer() = timerDao.loadAllTimer() fun loadTimerByDate(date: String) = timerDao.loadTimerByDate(date) }
0
Kotlin
0
0
701837fd229aa9c9a6319c1d169092fea226f43a
550
TimeEr
Apache License 2.0