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
src/main/kotlin/io/github/flaviolionelrita/lambdaorm/client/model/QueryResponse.kt
FlavioLionelRita
607,104,769
false
null
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package io.github.flaviolionelrita.lambdaorm.client.model import com.squareup.moshi.Json /** * * * @param result */ data class QueryResponse ( @Json(name = "result") val result: kotlin.Any? )
0
Kotlin
0
0
a09f50d7097ac3ee1d72397f4a5b7926d38e38ca
486
lambdaorm-client-kotlin
MIT License
app/src/main/java/br/com/manoloneto/vnavenda/data/dao/ShoppingItemDao.kt
manoloneto
741,086,329
false
{"Kotlin": 6781}
package br.com.manoloneto.vnavenda.data.dao import androidx.room.* import br.com.manoloneto.vnavenda.data.entities.ShoppingItem import kotlinx.coroutines.flow.Flow @Dao interface ShoppingItemDao { @Query("SELECT * FROM shopping_items") fun getAllItems(): Flow<List<ShoppingItem>> @Query("SELECT * FROM shopping_items WHERE id = :id") fun getItemById(id: Int): Flow<ShoppingItem> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertItem(item: ShoppingItem) @Update suspend fun updateItem(item: ShoppingItem) @Delete suspend fun deleteItem(item: ShoppingItem) }
0
Kotlin
0
0
318ab882b9799c578cfaa68e34cec2c59bc5f9b0
620
android-vnavenda
MIT License
app/src/main/java/br/com/manoloneto/vnavenda/data/dao/ShoppingItemDao.kt
manoloneto
741,086,329
false
{"Kotlin": 6781}
package br.com.manoloneto.vnavenda.data.dao import androidx.room.* import br.com.manoloneto.vnavenda.data.entities.ShoppingItem import kotlinx.coroutines.flow.Flow @Dao interface ShoppingItemDao { @Query("SELECT * FROM shopping_items") fun getAllItems(): Flow<List<ShoppingItem>> @Query("SELECT * FROM shopping_items WHERE id = :id") fun getItemById(id: Int): Flow<ShoppingItem> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertItem(item: ShoppingItem) @Update suspend fun updateItem(item: ShoppingItem) @Delete suspend fun deleteItem(item: ShoppingItem) }
0
Kotlin
0
0
318ab882b9799c578cfaa68e34cec2c59bc5f9b0
620
android-vnavenda
MIT License
core/src/pl/shockah/godwit/color/LCHColor.kt
Shockah
72,736,272
false
null
package pl.shockah.godwit.color import pl.shockah.godwit.color.XYZColor.Companion.xyz import pl.shockah.godwit.ease.ease import pl.shockah.godwit.geom.Angle import pl.shockah.godwit.geom.Radians import kotlin.math.atan2 import kotlin.math.pow import kotlin.math.sqrt data class LCHColor( val l: Float, val c: Float, val h: Angle, val reference: XYZColor.Reference = XYZColor.Reference.D65_2 ) : IGColor<LCHColor>() { companion object { fun from(lab: LabColor): LCHColor { return LCHColor( lab.l, sqrt(lab.a * lab.a + lab.b * lab.b), Radians.of(atan2(lab.b, lab.a)), lab.reference ) } } data class ReferenceRanges internal constructor( val reference: XYZColor.Reference, val l: ClosedRange<Float>, val c: ClosedRange<Float> ) { companion object { val D50_2: ReferenceRanges by lazy { ReferenceRanges(XYZColor.Reference.D50_2) } val D50_10: ReferenceRanges by lazy { ReferenceRanges(XYZColor.Reference.D50_10) } val D65_2: ReferenceRanges by lazy { ReferenceRanges(XYZColor.Reference.D65_2) } val D65_10: ReferenceRanges by lazy { ReferenceRanges(XYZColor.Reference.D65_10) } operator fun invoke(reference: XYZColor.Reference): ReferenceRanges { val steps = 16 var minL: Float? = null var minC: Float? = null var maxL: Float? = null var maxC: Float? = null for (bi in 0 until steps) { for (gi in 0 until steps) { for (ri in 0 until steps) { val lch = LabColor.from(RGBColor( 1f / (steps - 1) * ri, 1f / (steps - 1) * gi, 1f / (steps - 1) * bi ).xyz, reference).lch if (minL == null || lch.l < minL) minL = lch.l if (minC == null || lch.c < minC) minC = lch.c if (maxL == null || lch.l > maxL) maxL = lch.l if (maxC == null || lch.c > maxC) maxC = lch.c } } } return ReferenceRanges(reference, minL!!..maxL!!, minC!!..maxC!!) } } } override val rgb by lazy { lab.rgb } val exactRgb: RGBColor by lazy { lab.exactRgb } val lab: LabColor by lazy { LabColor( l, h.cos * c, h.sin * c, reference ) } val hsluv: HSLuvColor by lazy { HSLuvColor.from(this) } override fun getDistance(other: LCHColor): Float { val delta = h delta other.h return sqrt((delta.degrees.value / 180f).pow(2) + (l - other.l).pow(2) + (c - other.c).pow(2)) } override fun ease(other: LCHColor, f: Float): LCHColor { return LCHColor( f.ease(l, other.l), f.ease(c, other.c), h.ease(other.h, f), reference ) } fun with(l: Float = this.l, c: Float = this.c, h: Angle = this.h): LCHColor { return LCHColor(l, c, h) } }
0
Kotlin
0
0
e6290497e5f4780d2e2b337df8fb498a49c75087
2,670
Godwit
Apache License 2.0
domains/android/stub/src/testFixtures/kotlin/fake/FakeNotificationBuilder.kt
ouchadam
434,718,760
false
{"Kotlin": 461355, "JavaScript": 12445, "Shell": 1820}
package fake import android.app.Notification import io.mockk.every import io.mockk.mockk import test.delegateReturn class FakeNotificationBuilder { val instance = mockk<Notification.Builder>(relaxed = true) fun givenBuilds() = every { instance.build() }.delegateReturn() }
36
Kotlin
4
139
5a391676d0d482596fe5d270798c2b361dba67e7
283
small-talk
Apache License 2.0
src/main/kotlin/fr/phast/cql/services/providers/LibraryContentProviderImpl.kt
phast-fr
424,529,437
false
{"Kotlin": 69053}
/* * MIT License * * Copyright (c) 2021 PHAST * * 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 fr.phast.cql.services.providers import fr.phast.cql.services.content.LibraryContentType import org.cqframework.cql.cql2elm.FhirLibrarySourceProvider import org.hl7.elm.r1.VersionedIdentifier import org.slf4j.LoggerFactory import java.io.ByteArrayInputStream import java.io.InputStream class LibraryContentProviderImpl<LibraryType, AttachmentType>( private val provider: LibraryResolutionProvider<LibraryType>, private val getAttachments: (library: LibraryType) -> Iterable<AttachmentType>?, private val getContentType: (attachment: AttachmentType) -> String?, private val getContent: (attachment: AttachmentType) -> ByteArray? ): LibraryContentProvider { private val innerProvider = FhirLibrarySourceProvider() override fun getLibraryContent( versionedIdentifier: VersionedIdentifier, libraryContentType: LibraryContentType ): InputStream? { // TODO: Support loading ELM if (libraryContentType !== LibraryContentType.CQL) { return null } try { val library = this.provider.resolveLibraryByName( versionedIdentifier.id, versionedIdentifier.version ) library?.let<LibraryType, Iterable<AttachmentType>?> { this.getAttachments(it) }?.forEach { attachment -> if (this.getContentType(attachment) == "text/cql") { return ByteArrayInputStream(this.getContent(attachment)) } } } catch (e: Exception) { logger.warn( "Failed to parse Library source for VersionedIdentifier '$versionedIdentifier'!" + System.lineSeparator() + e.message, e ) } return innerProvider.getLibrarySource(versionedIdentifier) } companion object { private val logger = LoggerFactory.getLogger(LibraryContentProviderImpl::class.java) } }
0
Kotlin
0
0
b8e3da27d0b7e76eb85596ae8a217e597a074d35
3,109
cql-services
MIT License
core/src/main/java/id/rifqipadisiliwangi/core/domain/usecase/StoreUseCase.kt
Rifqips
767,860,717
false
{"Kotlin": 316033}
package id.rifqipadisiliwangi.core.domain.usecase import id.rifqipadisiliwangi.core.domain.model.detail.StoreDetailData import id.rifqipadisiliwangi.core.domain.model.fulfillment.FulfillmentRequest import id.rifqipadisiliwangi.core.domain.model.fulfillment.FulfillmentResponse import id.rifqipadisiliwangi.core.domain.model.history.DataHistory import id.rifqipadisiliwangi.core.domain.model.rating.RatingRequest import id.rifqipadisiliwangi.core.domain.model.rating.RatingResponse import id.rifqipadisiliwangi.core.domain.model.review.DataResponseReviewItemDataResponse import id.rifqipadisiliwangi.core.domain.model.search.SearchResponse import id.rifqipadisiliwangi.core.domain.model.store.ResponseStoreItem import id.rifqipadisiliwangi.core.domain.repository.StoreRepository import id.rifqipadisiliwangi.core.utils.ResultWrapper import kotlinx.coroutines.flow.Flow interface StoreUseCase { suspend fun productStore( searchItem:String? = null, brandItem:String? = null, lowestItem:Int? = null, highestItem:Int? = null, sortItem:String? = null, limitItem:Int? = null, pageItem:Int? = null, ): ResponseStoreItem suspend fun postFullFillment(body : FulfillmentRequest) : Flow<ResultWrapper<FulfillmentResponse>> suspend fun detailStore(productId : String) : Flow<ResultWrapper<StoreDetailData>> suspend fun searchSuggestion(query : String) : Flow<ResultWrapper<SearchResponse>> suspend fun reviewProduct(productId : String) : Flow<ResultWrapper<List<DataResponseReviewItemDataResponse>>> suspend fun getHistory() : Flow<ResultWrapper<List<DataHistory>>> suspend fun setAppCheckedPrefCart(isChecked: Boolean) fun getAppCheckedPrefCart() :Flow<Boolean> suspend fun saveCountNumberCart(countNumber: String) suspend fun getCountNumberCart() : String suspend fun removeAppChekcedData() suspend fun getKeySearch(): String suspend fun saveKeySearch(search: String) suspend fun removeKeySearch() fun getAppLayoutFlowStore(): Flow<Boolean> suspend fun setAppLayoutPrefStore(isGridLayout: Boolean) suspend fun userRating(userRating: RatingRequest): Flow<ResultWrapper<RatingResponse>> } class StoreInteractor(private val storeRepository : StoreRepository) : StoreUseCase{ override suspend fun productStore( searchItem: String?, brandItem: String?, lowestItem: Int?, highestItem: Int?, sortItem: String?, limitItem: Int?, pageItem: Int? ): ResponseStoreItem { return storeRepository.productStore(searchItem, brandItem, lowestItem, highestItem, sortItem,limitItem, pageItem) } override suspend fun postFullFillment(body: FulfillmentRequest): Flow<ResultWrapper<FulfillmentResponse>> { return storeRepository.postFullFillment(body) } override suspend fun detailStore(productId: String): Flow<ResultWrapper<StoreDetailData>> { return storeRepository.detailStore(productId) } override suspend fun searchSuggestion(query: String): Flow<ResultWrapper<SearchResponse>> { return storeRepository.searchSuggestion(query) } override suspend fun reviewProduct(productId: String): Flow<ResultWrapper<List<DataResponseReviewItemDataResponse>>> { return storeRepository.reviewProduct(productId) } override suspend fun getHistory(): Flow<ResultWrapper<List<DataHistory>>> { return storeRepository.getHistory() } override suspend fun setAppCheckedPrefCart(isChecked: Boolean) { return storeRepository.setAppCheckedPrefCart(isChecked) } override fun getAppCheckedPrefCart(): Flow<Boolean> { return storeRepository.getAppCheckedPrefCart() } override suspend fun saveCountNumberCart(countNumber: String) { return storeRepository.saveCountNumberCart(countNumber) } override suspend fun getCountNumberCart(): String { return storeRepository.getCountNumberCart() } override suspend fun removeAppChekcedData() { return storeRepository.removeAppChekcedData() } override suspend fun getKeySearch(): String { return storeRepository.getKeySearch() } override suspend fun saveKeySearch(search: String) { return storeRepository.saveKeySearch(search) } override suspend fun removeKeySearch() { return storeRepository.removeKeySearch() } override fun getAppLayoutFlowStore(): Flow<Boolean> { return storeRepository.getAppLayoutFlowStore() } override suspend fun setAppLayoutPrefStore(isGridLayout: Boolean) { return storeRepository.setAppLayoutPrefStore(isGridLayout) } override suspend fun userRating(userRating: RatingRequest): Flow<ResultWrapper<RatingResponse>> { return storeRepository.userRating(userRating) } }
0
Kotlin
0
0
d3dcbf01c5155a6b761a2919c214bda5de0374a9
4,856
TokoPaerbe
MIT License
AndroidApp/app/src/main/java/pl/todoit/industrialAndroidWebAppHost/model/extensions/SoundPool.kt
d-p-y
249,801,428
false
null
package pl.todoit.industrialAndroidWebAppHost.model.extensions import android.media.SoundPool import timber.log.Timber import java.io.Closeable fun SoundPool.asClosable() : Closeable = Closeable { this.release() } fun SoundPool.playOnce(sndId : Int) { val zeroIfFailed = this.play(sndId, 1f, 1f, 0, 0, 1f) if (zeroIfFailed == 0) { Timber.e("failed to play sound") } }
0
Kotlin
0
0
cf9a1312fdef17bb2aba98c6c1a39fe5502090b5
391
industrial-android-webapp-host
Apache License 2.0
Fragments/Configuration/SettingsRepository.kt
georeaper
852,383,858
false
{"Kotlin": 560550}
package com.gkprojects.cmmsandroidapp.Fragments.Configuration import android.content.Context import androidx.room.Insert import androidx.room.OnConflictStrategy import com.gkprojects.cmmsandroidapp.CMMSDatabase import com.gkprojects.cmmsandroidapp.Dao.SettingsDao import com.gkprojects.cmmsandroidapp.DataClasses.Settings import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale import com.gkprojects.cmmsandroidapp.DataClasses.Settings as AppSettings class SettingsRepository private constructor(context: Context) { private val settingsDao: SettingsDao = CMMSDatabase.getInstance(context)!!.SettingsDao() companion object { @Volatile private var instance: SettingsRepository? = null fun getInstance(context: Context): SettingsRepository { return instance ?: synchronized(this) { instance ?: SettingsRepository(context).also { instance = it } } } } // Example method to insert settings suspend fun insertSettings(settings: AppSettings): Long { val currentDateTime = Calendar.getInstance().time val dateFormat = SimpleDateFormat("dd/MM/yy HH:mm:ss", Locale.getDefault()) settings.DateCreated = dateFormat.format(currentDateTime) settings.LastModified=dateFormat.format(currentDateTime) return settingsDao.insertSettings(settings) } // Example method to retrieve settings by key suspend fun getSettingsByKey(key: String): List<AppSettings> { return settingsDao.getSettingsByKey(key) } suspend fun deleteSettings(settings: Settings):Int{ return settingsDao.deleteSettings(settings) } }
0
Kotlin
0
0
ead876d15542a773f84db60d89a2360dc940b268
1,690
CMMSmobile
MIT License
core/ui/src/main/java/com/devfalah/ui/screen/profile/composable/AlbumSection.kt
Salmon-family
569,890,321
false
{"Kotlin": 837143}
package com.devfalah.ui.screen.profile.composable import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.runtime.Composable 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.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.rememberAsyncImagePainter import com.devfalah.ui.R import com.devfalah.ui.composable.HeightSpacer8 import com.devfalah.ui.composable.WidthSpacer8 import com.devfalah.ui.theme.LightSecondaryBlackColor import com.devfalah.ui.theme.LightTernaryBlackColor import com.devfalah.ui.theme.PlusJakartaSans import com.devfalah.viewmodels.userProfile.AlbumUIState @Composable fun AlbumSection( albums: List<AlbumUIState>, modifier: Modifier = Modifier ) { Column( modifier .fillMaxWidth() .clip(RoundedCornerShape(16.dp)) .background(Color(0xFFF6F6F7)) .padding(16.dp) ) { Row( verticalAlignment = Alignment.CenterVertically ) { Text( modifier = Modifier.weight(1f), text = stringResource(id = R.string.albums), color = LightSecondaryBlackColor, fontFamily = PlusJakartaSans, fontSize = 14.sp ) Text( text = stringResource(id = R.string.see_all), color = LightTernaryBlackColor, fontFamily = PlusJakartaSans, fontSize = 12.sp ) WidthSpacer8() Image( painter = painterResource(id = R.drawable.ic_arrow_right), contentDescription = null, Modifier.size(24.dp) ) } HeightSpacer8() Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { albums.take(3).forEach { Image( painter = rememberAsyncImagePainter( model = it.albumCover, error = painterResource(id = R.drawable.test_image) ), contentDescription = null, contentScale = ContentScale.FillBounds, modifier = Modifier .fillMaxSize() .weight(1f) .aspectRatio(1f) .clip(RoundedCornerShape(20.dp)) ) } } } }
11
Kotlin
19
24
7589d73a400c78ecfa94b24d87189b4f5e01de9b
2,871
Clubs
Apache License 2.0
korge-core/test/korlibs/io/net/http/HttpTestExt.kt
korlibs
80,095,683
false
{"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41}
package korlibs.io.net.http import korlibs.io.lang.UTF8 import korlibs.io.lang.toString import korlibs.io.stream.readAll suspend fun HttpBodyContent.toDebugString(): String { return "$contentType\n${this.createAsyncStream().readAll().toString(UTF8)}" }
444
WebAssembly
121
2,207
dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a
259
korge
Apache License 2.0
ShowWmtProduct/app/src/main/java/com/example/showwmtproduct/ui/theme/Theme.kt
saga0086
594,338,181
false
{"Kotlin": 110752, "Java": 1348}
package com.example.showwmtproduct.ui.theme //import androidx.compose.foundation.isSystemInDarkTheme //import androidx.compose.material3.MaterialTheme //import androidx.compose.material3.darkColorScheme //import androidx.compose.material3.dynamicDarkColorScheme //import androidx.compose.material3.dynamicLightColorScheme //import androidx.compose.material3.lightColorScheme /* private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 */ /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), )*/ /* @Composable fun ShowWmtProductTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }*/
0
Kotlin
0
0
14358ca6e8c839d66bb502fd444720303ebf6758
1,904
android-small-project
Apache License 2.0
app/src/main/java/ci/projccb/mobile/activities/infospresenters/InspectionPreviewUpdateActivity.kt
SICADEVD
686,088,142
false
{"Kotlin": 1766967, "Java": 20374}
package ci.projccb.mobile.activities.infospresenters import android.graphics.Bitmap import android.graphics.BitmapFactory import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import ci.projccb.mobile.R import ci.projccb.mobile.activities.forms.FormationActivity import ci.projccb.mobile.activities.forms.InspectionActivity import ci.projccb.mobile.adapters.PreviewItemAdapter import ci.projccb.mobile.adapters.QuestionnairePreviewAdapter import ci.projccb.mobile.interfaces.SectionCallback import ci.projccb.mobile.itemviews.RecyclerItemDecoration import ci.projccb.mobile.models.InspectionDTO import ci.projccb.mobile.models.QuestionResponseModel import ci.projccb.mobile.repositories.databases.CcbRoomDatabase import ci.projccb.mobile.tools.Commons import ci.projccb.mobile.tools.MapEntry import com.blankj.utilcode.util.ActivityUtils import com.blankj.utilcode.util.GsonUtils import com.blankj.utilcode.util.LogUtils import com.google.firebase.crashlytics.FirebaseCrashlytics import com.google.gson.reflect.TypeToken import kotlinx.android.synthetic.main.activity_inspection_update_preview.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import java.io.File import java.lang.Exception class InspectionPreviewUpdateActivity : AppCompatActivity(), SectionCallback { private var cQuestionnairesMap: MutableList<HashMap<String, String>>? = mutableListOf() private var cQuestionnaires: MutableList<QuestionResponseModel>? = mutableListOf() lateinit var questionnaireAdapter: QuestionnairePreviewAdapter override fun isSectionHeader(position: Int): Boolean { return position == 0 || cQuestionnaires!![position].isTitle!! } override fun getSectionHeaderName(postion: Int): String { try { val mQuestionMapped = hashMapOf<String, String>() return mQuestionMapped["Title"] ?: "Size" } catch (ex: Exception) { LogUtils.e(ex.message) FirebaseCrashlytics.getInstance().recordException(ex) } return "" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_inspection_update_preview) clickCloseBtn.setOnClickListener { finish() } intent?.let { it -> try { val infoItemsListPrev: MutableList<Map<String, String>> = arrayListOf() val infoItemListData = it.getParcelableArrayListExtra<MapEntry>("previewitem") infoItemListData?.forEach { if(it.key.isNullOrEmpty()==false){ Commons.addItemsToList( if(it.key=="null") "Autre" else it.key, it.value.replace(", ", "\n"), infoItemsListPrev ) } } //LogUtils.json(infosProducteur) // LogUtils.d(producteurItemsListPrev) val rvPrevAdapter = PreviewItemAdapter(infoItemsListPrev) recyclerInfoPrev.adapter = rvPrevAdapter recyclerInfoPrev.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) val itemsDatas: InspectionDTO? = it.getParcelableExtra("preview") clickSaveFormationPreview.setOnClickListener { Commons.showMessage( "Etes-vous sur de vouloir faire cette mise à jour ?", this, showNo = true, callback = { CcbRoomDatabase.getDatabase(this)?.inspectionDao() ?.insert(itemsDatas!!) Commons.synchronisation(type = "inspection", this) Commons.showMessage( "Inspection mise à jour !", this, finished = true, callback = {}) }, finished = false ) ActivityUtils.finishActivity(InspectionActivity::class.java) } } catch (ex: Exception) { LogUtils.e(ex.message) FirebaseCrashlytics.getInstance().recordException(ex) } } clickCloseBtn.setOnClickListener { finish() } } }
0
Kotlin
0
2
9a8837d033e4cf50b023450540e7af4ff7e4780c
4,680
ccbm
Apache License 2.0
app/src/main/java/com/nextgen/mygithubuserapp/ui/setting/SettingViewModel.kt
beranju
564,798,705
false
null
package com.nextgen.mygithubuserapp.ui.setting import androidx.lifecycle.* import kotlinx.coroutines.launch class SettingViewModel(private val pref: SettingPreferences) : ViewModel() { fun getThemeSettings():LiveData<Boolean>{ return pref.getThemeSetting().asLiveData() } fun saveThemeSettings(isDarkModeActive: Boolean){ viewModelScope.launch { pref.saveThemeSetting(isDarkModeActive) } } }
0
Kotlin
0
0
4dcf8fb470a497bbeadf3e372ee5c03462033f13
448
User-Of-Github
Apache License 2.0
app/src/test/kotlin/com/ceh9/portfolio/features/calculator/domain/MathEngineImplTest.kt
CeH9
202,865,791
false
null
package com.ceh9.portfolio.features.calculator.domain import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Test /** * Created by CeH9 on 29.10.2019 */ class MathEngineImplTest { private val mathEngine: MathEngine = MathEngineImpl() @Test fun `multiply 2 by 3 to get 6`() { // GIVEN two numbers val first = 2 val second = 3 // WHEN multiply val result = mathEngine.multiply(first, second) // THEN result is 6 assertThat(result, `is`(6)) } }
0
Kotlin
0
0
d4efdcffbee64a02cdb82d73d4f707f322964c40
566
Portfolio
MIT License
identity/src/main/java/com/stripe/android/identity/viewmodel/FrontBackUploadViewModel.kt
vaibhavantil2
467,840,474
true
{"Kotlin": 5114452, "Java": 67363, "Shell": 14657, "Python": 1729, "Ruby": 1280}
package com.stripe.android.identity.viewmodel import android.content.Context import android.net.Uri import androidx.activity.result.ActivityResultCaller import androidx.activity.result.ActivityResultLauncher import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.stripe.android.core.model.InternalStripeFilePurpose import com.stripe.android.identity.IdentityVerificationSheetContract import com.stripe.android.identity.networking.IdentityRepository import com.stripe.android.identity.utils.ImageChooser import com.stripe.android.identity.utils.PhotoTaker import com.stripe.android.identity.utils.resizeUriAndCreateFileToUpload import kotlinx.coroutines.launch /** * ViewModel to upload front and back image of a document either through camera or from local * file storage. */ internal class FrontBackUploadViewModel( private val identityRepository: IdentityRepository, private val verificationArgs: IdentityVerificationSheetContract.Args ) : ViewModel() { /** * The ID front image has been uploaded */ private val _frontUploaded = MutableLiveData<Unit>() val frontUploaded: LiveData<Unit> = _frontUploaded /** * The ID back image has been uploaded */ private val _backUploaded = MutableLiveData<Unit>() val backUploaded: LiveData<Unit> = _backUploaded /** * Both front and back of ID are uploaded */ val uploadFinished = object : MediatorLiveData<Unit>() { private var frontUploaded = false private var backUploaded = false init { addSource(this@FrontBackUploadViewModel.frontUploaded) { frontUploaded = true postValueWhenBothUploaded() } addSource(this@FrontBackUploadViewModel.backUploaded) { backUploaded = true postValueWhenBothUploaded() } } private fun postValueWhenBothUploaded() { if (frontUploaded && backUploaded) { postValue(Unit) } } } private lateinit var frontPhotoTaker: PhotoTaker private lateinit var backPhotoTaker: PhotoTaker private lateinit var frontImageChooser: ImageChooser private lateinit var backImageChooser: ImageChooser /** * Registers for the [ActivityResultLauncher]s to take photo or pick image, should be called * during initialization of an Activity or Fragment. */ internal fun registerActivityResultCaller(activityResultCaller: ActivityResultCaller) { frontPhotoTaker = PhotoTaker(activityResultCaller) backPhotoTaker = PhotoTaker(activityResultCaller) frontImageChooser = ImageChooser(activityResultCaller) backImageChooser = ImageChooser(activityResultCaller) } /** * Takes a photo for front. */ fun takePhotoFront( context: Context, onPhotoTaken: (Uri) -> Unit ) { frontPhotoTaker.takePhoto(context, onPhotoTaken) } /** * Takes a photo for back. */ fun takePhotoBack( context: Context, onPhotoTaken: (Uri) -> Unit ) { backPhotoTaker.takePhoto(context, onPhotoTaken) } /** * Choose an image for front. */ fun chooseImageFront( onImageChosen: (Uri) -> Unit ) { frontImageChooser.chooseImage(onImageChosen) } /** * Choose an image for back. */ fun chooseImageBack( onImageChosen: (Uri) -> Unit ) { backImageChooser.chooseImage(onImageChosen) } /** * Upload the chosen image for front, notifies its corresponding live data when * finished. */ fun uploadImageFront( uri: Uri, context: Context ) { viewModelScope.launch { identityRepository.uploadImage( verificationId = verificationArgs.verificationSessionId, ephemeralKey = verificationArgs.ephemeralKeySecret, imageFile = resizeUriAndCreateFileToUpload( context, uri, verificationArgs.verificationSessionId, // TODO(ccen) upload both full frame and non full frame true, FRONT ), // TODO(ccen) pass it over from VerificationPage response filePurpose = InternalStripeFilePurpose.IdentityPrivate ) _frontUploaded.postValue(Unit) } } /** * Upload the chosen image for back, notifies its corresponding live data when * finished. */ fun uploadImageBack( uri: Uri, context: Context ) { viewModelScope.launch { identityRepository.uploadImage( verificationId = verificationArgs.verificationSessionId, ephemeralKey = verificationArgs.ephemeralKeySecret, imageFile = resizeUriAndCreateFileToUpload( context, uri, verificationArgs.verificationSessionId, // TODO(ccen) upload both full frame and non full frame true, BACK ), // TODO(ccen) pass it over from VerificationPage response filePurpose = InternalStripeFilePurpose.IdentityPrivate ) _backUploaded.postValue(Unit) } } internal class FrontBackUploadViewModelFactory( private val identityRepository: IdentityRepository, private val verificationArgs: IdentityVerificationSheetContract.Args ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return FrontBackUploadViewModel(identityRepository, verificationArgs) as T } } private companion object { const val FRONT = "front" const val BACK = "back" } }
0
Kotlin
0
0
52a37829e06439fa55d837423922f57265a9816f
6,179
stripe-android
MIT License
app/src/main/java/it/bosler/remotealarm/MainActivity.kt
maribox
736,473,741
false
{"Kotlin": 25495}
package it.bosler.remotealarm import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.room.Room import it.bosler.remotealarm.model.Alarms.Alarm import it.bosler.remotealarm.model.Alarms.AlarmDatabase import it.bosler.remotealarm.viewmodel.AlarmViewModel class MainActivity : ComponentActivity() { private val db by lazy { Room.databaseBuilder( applicationContext, AlarmDatabase::class.java, "alarms.db" ).build() } private val viewModel by viewModels<AlarmViewModel> { object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(AlarmViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return AlarmViewModel(db.dao) as T } throw IllegalArgumentException("Unknown ViewModel class") } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { RemoteAlarmApp(alarmViewModel = viewModel) } } }
0
Kotlin
0
0
cc4da14861653d1e4b8cd8c24cb30e9bdb70682e
1,407
RemoteAlarm
MIT License
app/src/main/java/com/powelllaboratoriesfsm/features/NewQuotation/interfaces/TaxOnclick.kt
DebashisINT
558,285,083
false
null
package com.powelllaboratoriesfsm.features.NewQuotation.interfaces import com.powelllaboratoriesfsm.app.domain.NewOrderGenderEntity interface TaxOnclick { fun OnClick(obj:String) }
0
Kotlin
0
0
9ca14a68e2c8a2958dc6d7dd00f4b6471dd95c1f
186
PowellLaboratories
Apache License 2.0
sample/src/commonMain/kotlin/com/mmk/kmpnotifier/sample/AppInitializer.kt
mirzemehdi
717,626,777
false
{"Kotlin": 33042, "Ruby": 2108, "Swift": 1582}
package com.mmk.kmpnotifier.sample import com.mmk.kmpnotifier.notification.NotifierManager import com.mmk.kmpnotifier.notification.PayloadData object AppInitializer { fun onApplicationStart() { onApplicationStartPlatformSpecific() NotifierManager.addListener(object : NotifierManager.Listener { override fun onNewToken(token: String) { println("Push Notification onNewToken: $token") } override fun onPushNotification(title: String?, body: String?) { super.onPushNotification(title, body) println("Push Notification notification type message is received: Title: $title and Body: $body") } override fun onPayloadData(data: PayloadData) { super.onPayloadData(data) println("Push Notification payloadData: $data") } override fun onNotificationClicked(data: PayloadData) { super.onNotificationClicked(data) println("Notification clicked, Notification payloadData: $data") } }) } }
9
Kotlin
5
97
30146d54821565000b3b5354cf04f20ff80517b1
1,122
KMPNotifier
Apache License 2.0
android/scripts/src/test/kotlin/com/github/pgreze/versions/VersionsStripperTest.kt
pgreze
535,231,537
false
{"Kotlin": 33443}
package com.github.pgreze.versions import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Test class VersionsStripperTest { @Test fun `strip after XX versions`(): Unit = runBlocking { val lines = VERSIONS_LONG.split("\n") .stripVersionAvailableLines(maxVersions = 3, artifactFilter = null) .joinToString("\n").trim() assertThat(lines).isEqualTo(VERSIONS_SHORT_3.trim()) } @Test fun `filter only specific artifacts`(): Unit = runBlocking { val lines = VERSIONS_LONG.split("\n") .stripVersionsAvailableForProtoOnly(maxVersions = 3) .joinToString("\n").trim() assertThat(lines).isEqualTo(VERSIONS_ONLY_PROTO_3.trim()) } } private const val HEADERS = """ #### Dependencies and Plugin versions with their available updates. #### Generated by `./gradlew refreshVersions` version 0.10.0 #### #### Don't manually edit or split the comments that start with four hashtags (####), #### they will be overwritten by refreshVersions. #### #### suppress inspection "SpellCheckingInspection" for whole file #### suppress inspection "UnusedProperty" for whole file """ private const val VERSIONS_LONG = """ $HEADERS # When updating, update also app_groundup/lint-baseline.xml plugin.android=7.0.0-alpha15 ## # available=7.0.0-beta01 ## # available=7.1.0-alpha01 version.androidx.annotation=1.1.0 ## # available=1.2.0-alpha01 ## # available=1.2.0-beta01 ## # available=1.2.0-rc01 ## # available=1.2.0 ## # available=1.3.0-alpha01 version.androidx.appcompat=1.3.0-rc01 ## # available=1.3.0 ## # available=1.4.0-alpha01 version.androidx.constraintlayout-compose=1.0.0-alpha06 ## # available=1.0.0-alpha07 version.com.mercari.proto..common.gateway=0.200.0 ## # available=0.201.0-SNAPSHOT ## # available=0.201.0 ## # available=0.202.0 ## # available=0.203.0 ## # available=0.204.0 ## # available=0.205.0 ## # available=0.206.0 ## # available=0.207.0 version.com.google.code.findbugs..jsr305=3.0.2 """ private const val VERSIONS_SHORT_3 = """ $HEADERS # When updating, update also app_groundup/lint-baseline.xml plugin.android=7.0.0-alpha15 ## # available=7.0.0-beta01 ## # available=7.1.0-alpha01 version.androidx.annotation=1.1.0 ## # available=1.2.0-rc01 ## # available=1.2.0 ## # available=1.3.0-alpha01 version.androidx.appcompat=1.3.0-rc01 ## # available=1.3.0 ## # available=1.4.0-alpha01 version.androidx.constraintlayout-compose=1.0.0-alpha06 ## # available=1.0.0-alpha07 version.com.mercari.proto..common.gateway=0.200.0 ## # available=0.205.0 ## # available=0.206.0 ## # available=0.207.0 version.com.google.code.findbugs..jsr305=3.0.2 """ private const val VERSIONS_ONLY_PROTO_3 = """ $HEADERS # When updating, update also app_groundup/lint-baseline.xml plugin.android=7.0.0-alpha15 ## # available=7.0.0-beta01 ## # available=7.1.0-alpha01 version.androidx.annotation=1.1.0 ## # available=1.2.0-alpha01 ## # available=1.2.0-beta01 ## # available=1.2.0-rc01 ## # available=1.2.0 ## # available=1.3.0-alpha01 version.androidx.appcompat=1.3.0-rc01 ## # available=1.3.0 ## # available=1.4.0-alpha01 version.androidx.constraintlayout-compose=1.0.0-alpha06 ## # available=1.0.0-alpha07 version.com.mercari.proto..common.gateway=0.200.0 ## # available=0.205.0 ## # available=0.206.0 ## # available=0.207.0 version.com.google.code.findbugs..jsr305=3.0.2 """
0
Kotlin
2
4
ad83259e9632c65c6d021f730a7248712601f68a
4,126
kotlin-ci
Apache License 2.0
core/ui/src/main/kotlin/de/tum/informatics/www1/artemis/native_app/core/ui/LocalLinkOpener.kt
ls1intum
537,104,541
false
{"Kotlin": 1958386, "Dockerfile": 1306, "Shell": 1187}
package de.tum.informatics.www1.artemis.native_app.core.ui import androidx.compose.runtime.ProvidableCompositionLocal import androidx.compose.runtime.compositionLocalOf /** * Local provider to open links from the UI. Currently provided by [de.tum.informatics.www1.artemis.native_app.android.ui.MainActivity]. */ val LocalLinkOpener: ProvidableCompositionLocal<LinkOpener> = compositionLocalOf { EmptyLinkOpener } /** * Allows the ui to open links */ interface LinkOpener { fun openLink(url: String) } /** * Link opener provided as default, does nothing when the ui requests to open a link. */ private object EmptyLinkOpener : LinkOpener { override fun openLink(url: String) = Unit }
12
Kotlin
0
6
dd4b99ab6a143b669d3db20af45dbe533c650bd4
700
artemis-android
MIT License
save-backend/src/main/kotlin/org/cqfn/save/backend/controllers/DownloadFilesController.kt
cqfn
300,279,336
false
null
package org.cqfn.save.backend.controllers import org.cqfn.save.agent.TestExecutionDto import org.cqfn.save.backend.ByteArrayResponse import org.cqfn.save.backend.repository.AgentRepository import org.cqfn.save.backend.repository.TestDataFilesystemRepository import org.cqfn.save.backend.repository.TimestampBasedFileSystemRepository import org.cqfn.save.backend.service.OrganizationService import org.cqfn.save.backend.service.UserDetailsService import org.cqfn.save.domain.FileInfo import org.cqfn.save.domain.TestResultDebugInfo import org.cqfn.save.domain.TestResultLocation import org.cqfn.save.from import org.cqfn.save.utils.AvatarType import org.slf4j.LoggerFactory import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.http.codec.multipart.FilePart import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RequestPart import org.springframework.web.bind.annotation.RestController import org.springframework.web.server.ResponseStatusException import reactor.core.publisher.Mono import java.io.FileNotFoundException import kotlin.io.path.* /** * A Spring controller for file downloading */ @RestController class DownloadFilesController( private val additionalToolsFileSystemRepository: TimestampBasedFileSystemRepository, private val testDataFilesystemRepository: TestDataFilesystemRepository, private val agentRepository: AgentRepository, private val organizationService: OrganizationService, private val userDetailsService: UserDetailsService, ) { private val logger = LoggerFactory.getLogger(DownloadFilesController::class.java) /** * @return a list of files in [additionalToolsFileSystemRepository] */ @GetMapping("/api/files/list") fun list(): List<FileInfo> = additionalToolsFileSystemRepository.getFilesList().map { FileInfo( it.name, // assuming here, that we always store files in timestamp-based directories it.parent.name.toLong(), it.fileSize(), ) } /** * @param fileInfo a FileInfo based on which a file should be located * @return [Mono] with file contents */ @GetMapping(value = ["/api/files/download"], produces = [MediaType.APPLICATION_OCTET_STREAM_VALUE]) fun download(@RequestBody fileInfo: FileInfo): Mono<ByteArrayResponse> = Mono.fromCallable { logger.info("Sending file ${fileInfo.name} to a client") ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).body( additionalToolsFileSystemRepository.getFile(fileInfo).inputStream.readAllBytes() ) } .doOnError(FileNotFoundException::class.java) { logger.warn("File $fileInfo is not found", it) } .onErrorReturn( FileNotFoundException::class.java, ResponseEntity .status(HttpStatus.NOT_FOUND) .contentType(MediaType.APPLICATION_OCTET_STREAM) .build() ) /** * @param file a file to be uploaded * @return [Mono] with response */ @PostMapping(value = ["/api/files/upload"], consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) fun upload(@RequestPart("file") file: Mono<FilePart>) = additionalToolsFileSystemRepository.saveFile(file).map { fileInfo -> ResponseEntity.status( if (fileInfo.sizeBytes > 0) HttpStatus.OK else HttpStatus.INTERNAL_SERVER_ERROR ) .body(fileInfo) } .onErrorReturn( FileAlreadyExistsException::class.java, ResponseEntity.status(HttpStatus.CONFLICT).build() ) /** * @param file image to be uploaded * @param owner owner name * @param type type of avatar * @return [Mono] with response */ @Suppress("UnsafeCallOnNullableType") @PostMapping(value = ["/api/image/upload"], consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) fun uploadImage( @RequestPart("file") file: Mono<FilePart>, @RequestParam owner: String, @RequestParam(required = false) type: AvatarType = AvatarType.ORGANIZATION ) = additionalToolsFileSystemRepository.saveImage(file, owner, type).map { imageInfo -> imageInfo.path?.let { when (type) { AvatarType.ORGANIZATION -> organizationService.saveAvatar(owner, it) AvatarType.USER -> userDetailsService.saveAvatar(owner, it) } } ResponseEntity.status( imageInfo.path?.let { HttpStatus.OK } ?: HttpStatus.INTERNAL_SERVER_ERROR ) .body(imageInfo) } .onErrorReturn( FileAlreadyExistsException::class.java, ResponseEntity.status(HttpStatus.CONFLICT).build() ) /** * @param testExecutionDto * @return [Mono] with response * @throws ResponseStatusException if request is invalid or result cannot be returned */ @Suppress("ThrowsCount", "UnsafeCallOnNullableType") @PostMapping(value = ["/api/files/get-debug-info"]) fun getDebugInfo( @RequestBody testExecutionDto: TestExecutionDto, ): String { val agentContainerId = testExecutionDto.agentContainerId ?: throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Request body should contain agentContainerId") val execution = agentRepository.findByContainerId(agentContainerId)?.execution ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Execution for agent $agentContainerId not found") val executionId = execution.id!! val testResultLocation = TestResultLocation.from(testExecutionDto) val debugInfoFile = testDataFilesystemRepository.getLocation( executionId, testResultLocation ) return if (debugInfoFile.notExists()) { logger.warn("File $debugInfoFile not found") throw ResponseStatusException(HttpStatus.NOT_FOUND, "File not found") } else { debugInfoFile.readText() } } /** * @param agentContainerId agent that has executed the test * @param testResultDebugInfo additional info that should be stored * @return [Mono] with response */ @PostMapping(value = ["/internal/files/debug-info"]) @Suppress("UnsafeCallOnNullableType") fun uploadDebugInfo(@RequestParam("agentId") agentContainerId: String, @RequestBody testResultDebugInfo: TestResultDebugInfo, ) { val executionId = agentRepository.findByContainerId(agentContainerId)!!.execution.id!! testDataFilesystemRepository.save(executionId, testResultDebugInfo) } }
97
Kotlin
0
15
c381c6fd4d9c12178de79da4818220b724a15596
7,217
save-cloud
MIT License
2021/app/src/test/kotlin/net/sympower/aok2021/tonis/Day03Test.kt
tonisojandu
573,036,346
false
{"Rust": 113625, "Kotlin": 15806, "Shell": 1265}
package net.sympower.aok2021.tonis import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class Day03Test { @Test fun test01() { val consumption = day03Part01("/Day03Test.in") assertThat(consumption).isEqualTo(198) } @Test fun test02() { val lifeSupportRating = day03Part02("/Day03Test.in") assertThat(lifeSupportRating).isEqualTo(230) } }
0
Rust
0
0
4154c0fd74ef0c933491498a14548afcdd1df414
402
to-advent-of-code
MIT License
IPassPlusSdk/src/main/java/com/sdk/ipassplussdk/model/response/ceon/PostCeon/Google.kt
yazanalqasem
808,584,767
false
{"Kotlin": 308101, "Java": 4759}
package com.sdk.ipassplussdk.model.response.ceon.PostCeon data class Google( val photo: String, val registered: Boolean )
0
Kotlin
0
0
1fc3247607811f7f52e1d401c252b82e2c98c3a8
130
iPass2.0NativeAndroidSDK
Apple MIT License
src/main/kotlin/org/hoss/repositories/PayDatesRepository.kt
HOSSVILLE
310,470,615
false
null
package org.hoss.repositories import io.micronaut.data.jdbc.annotation.JdbcRepository import io.micronaut.data.model.query.builder.sql.Dialect import io.micronaut.data.repository.CrudRepository import org.hoss.models.PayDates import org.hoss.models.Payee import java.util.* @JdbcRepository(dialect = Dialect.POSTGRES) interface PayDatesRepository : CrudRepository<PayDates, Int> { override fun findAll(): List<PayDates> }
0
Kotlin
0
0
176584f2b7e3b76a466c82e67380bdaeecc16b8a
427
personal-bill-trakker-kotlin
Apache License 2.0
PagerAdapter.kt
AtifAbbAsi19
289,652,733
false
null
import androidx.annotation.NonNull import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT import androidx.fragment.app.FragmentStatePagerAdapter import androidx.viewpager2.adapter.FragmentStateAdapter import java.lang.ref.WeakReference class PagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) { private val FRAGMENTS_SIZE = 2 var currentFragmentWeakReference: WeakReference<Fragment>? = null override fun getItemCount(): Int { return this.FRAGMENTS_SIZE } override fun createFragment(position: Int): Fragment { when (position) { 0 -> { currentFragmentWeakReference = WeakReference(TestFragment()) return TestFragment() } 1 -> { currentFragmentWeakReference = WeakReference(TestFragment()) return TestFragment() } } return TestFragment() } }
0
Kotlin
0
1
801321ea4e2b22c86ed9b1d699463948497135bb
1,124
ViewPager2
Apache License 2.0
src/main/kotlin/com/redrield/units/conversions/MassConversions.kt
Redrield
195,331,813
false
null
package com.redrield.units.conversions import com.redrield.units.Kilogram import com.redrield.units.SIConstants import com.redrield.units.SIUnit val SIUnit<Kilogram>.yottagram get() = value / SIConstants.kYottaOffsetKilo val SIUnit<Kilogram>.zettagram get() = value / SIConstants.kZettaOffsetKilo val SIUnit<Kilogram>.exagram get() = value / SIConstants.kExaOffsetKilo val SIUnit<Kilogram>.petagram get() = value / SIConstants.kPetaOffsetKilo val SIUnit<Kilogram>.teragram get() = value / SIConstants.kTeraOffsetKilo val SIUnit<Kilogram>.gigagram get() = value / SIConstants.kGigaOffsetKilo val SIUnit<Kilogram>.megagram get() = value / SIConstants.kMegaOffsetKilo val SIUnit<Kilogram>.kilogram get() = value val SIUnit<Kilogram>.hectogram get() = value / SIConstants.kHectoOffsetKilo val SIUnit<Kilogram>.decagram get() = value / SIConstants.kDecaOffsetKilo val SIUnit<Kilogram>.gram get() = value / SIConstants.kBaseOffsetKilo val SIUnit<Kilogram>.decigram get() = value / SIConstants.kDeciOffsetKilo val SIUnit<Kilogram>.centigram get() = value / SIConstants.kCentiOffsetKilo val SIUnit<Kilogram>.milligram get() = value / SIConstants.kMilliOffsetKilo val SIUnit<Kilogram>.microgram get() = value / SIConstants.kMicroOffsetKilo val SIUnit<Kilogram>.nanogram get() = value / SIConstants.kNanoOffsetKilo val SIUnit<Kilogram>.picogram get() = value / SIConstants.kPicoOffsetKilo val SIUnit<Kilogram>.femtogram get() = value / SIConstants.kFemtoOffsetKilo val SIUnit<Kilogram>.attogram get() = value / SIConstants.kAttoOffsetKilo val SIUnit<Kilogram>.zeptogram get() = value / SIConstants.kZeptoOffsetKilo val SIUnit<Kilogram>.yoctogram get() = value / SIConstants.kYoctoOffsetKilo
0
Kotlin
0
1
c536fbaf781558bd20e6e0568d44f06940827b97
1,682
yaul
Apache License 2.0
app/src/main/java/eu/kanade/data/history/anime/AnimeHistoryRepositoryImpl.kt
AniFOSS
377,170,228
true
{"Kotlin": 4060627}
package eu.kanade.data.history.anime import eu.kanade.data.handlers.anime.AnimeDatabaseHandler import eu.kanade.domain.history.anime.model.AnimeHistoryUpdate import eu.kanade.domain.history.anime.model.AnimeHistoryWithRelations import eu.kanade.domain.history.anime.repository.AnimeHistoryRepository import eu.kanade.tachiyomi.util.system.logcat import kotlinx.coroutines.flow.Flow import logcat.LogPriority class AnimeHistoryRepositoryImpl( private val handler: AnimeDatabaseHandler, ) : AnimeHistoryRepository { override fun getAnimeHistory(query: String): Flow<List<AnimeHistoryWithRelations>> { return handler.subscribeToList { animehistoryViewQueries.animehistory(query, animeHistoryWithRelationsMapper) } } override suspend fun getLastAnimeHistory(): AnimeHistoryWithRelations? { return handler.awaitOneOrNull { animehistoryViewQueries.getLatestAnimeHistory(animeHistoryWithRelationsMapper) } } override suspend fun resetAnimeHistory(historyId: Long) { try { handler.await { animehistoryQueries.resetAnimeHistoryById(historyId) } } catch (e: Exception) { logcat(LogPriority.ERROR, throwable = e) } } override suspend fun resetHistoryByAnimeId(animeId: Long) { try { handler.await { animehistoryQueries.resetHistoryByAnimeId(animeId) } } catch (e: Exception) { logcat(LogPriority.ERROR, throwable = e) } } override suspend fun deleteAllAnimeHistory(): Boolean { return try { handler.await { animehistoryQueries.removeAllHistory() } true } catch (e: Exception) { logcat(LogPriority.ERROR, throwable = e) false } } override suspend fun upsertAnimeHistory(historyUpdate: AnimeHistoryUpdate) { try { handler.await { animehistoryQueries.upsert( historyUpdate.episodeId, historyUpdate.seenAt, ) } } catch (e: Exception) { logcat(LogPriority.ERROR, throwable = e) } } }
1
Kotlin
0
0
08787976b43da6e02207081e1ecccb7fcd89c307
2,184
aniyomi
Apache License 2.0
app/src/main/java/com/shahin/meistersearch/data/Repository.kt
shahin68
369,420,907
false
null
package com.shahin.meistersearch.data import androidx.paging.PagingData import com.shahin.meistersearch.data.local.models.relations.project_section.ProjectWithSections import com.shahin.meistersearch.data.local.models.relations.project_section.SectionWithProjects import com.shahin.meistersearch.data.local.models.relations.task_Section.TaskWithSections import com.shahin.meistersearch.data.remote.models.body.FilterBody import com.shahin.meistersearch.data.remote.models.response.search.SearchResponse import com.shahin.meistersearch.data.remote.models.response.search.items.TaskResult import com.shahin.meistersearch.network.NetworkResult import kotlinx.coroutines.flow.Flow interface Repository { fun getToken(): String suspend fun search(query: String): NetworkResult<SearchResponse> suspend fun searchPaging(query: String): Flow<PagingData<TaskResult>> suspend fun searchPagingWithDb(filterBody: FilterBody): Flow<PagingData<TaskWithSections>> suspend fun getProjectsWithSections(projectId: Int): List<ProjectWithSections> suspend fun getSectionsWithProjects(projectId: Int): List<SectionWithProjects> }
0
Kotlin
0
0
c04a20438794ed2feb4faf8b4bd38614a141c968
1,134
meister-challenge
MIT License
src/main/kotlin/me/zhiyao/hexo/Main.kt
WangZhiYao
328,140,572
false
null
package me.zhiyao.hexo import me.zhiyao.hexo.exts.logger import me.zhiyao.hexo.network.BingCrawler import me.zhiyao.hexo.post.PostMaker class Main { companion object { @JvmStatic fun main(args: Array<String>) { val logger = logger() val bingImage = BingCrawler.getImage() if (bingImage == null) { logger.error("failed to get bing image") return } val postFile = PostMaker.make(bingImage) if (postFile == null) { logger.error("failed to maker post") return } } } }
0
Kotlin
0
0
44725a5c451dd52060612ca5b82da30e20fb6dce
648
HexoBingPostMaker
MIT License
graph/graph-application/src/main/kotlin/eu/tib/orkg/prototype/statements/domain/model/ExtractionMethod.kt
TIBHannover
197,416,205
false
{"Kotlin": 2439902, "Cypher": 212135, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240}
package eu.tib.orkg.prototype.statements.domain.model enum class ExtractionMethod { AUTOMATIC, MANUAL, UNKNOWN }
0
Kotlin
2
5
8739ce33adc28e780a0c98771cd0c91b63dc922a
126
orkg-backend
MIT License
app/src/main/java/com/cdev/showtracker/category/CategoryContract.kt
gyorgygabor
87,455,684
false
null
package com.cdev.showtracker.category import com.cdev.showtracker.BasePresenter import com.cdev.showtracker.BaseView import com.cdev.showtracker.model.Category interface CategoryContract { interface Presenter : BasePresenter<View> { fun loadCategories() } interface View : BaseView { fun showProgressBar() fun hideProgressBar() fun showCategories(listOfCategories: List<Category>) fun showError(error: String?) fun showEmptyState() } }
0
Kotlin
0
0
08d66dcd78908266b97bf3096582eed813d2163f
504
ShowTrackerMVP
MIT License
bluetape4k/testcontainers/src/test/kotlin/io/bluetape4k/testcontainers/llm/OllamaServerTest.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.testcontainers.llm import io.bluetape4k.logging.KLogging import io.bluetape4k.logging.debug import io.restassured.RestAssured.given import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldContain import org.junit.jupiter.api.Test import org.testcontainers.utility.Base58 import org.testcontainers.utility.DockerImageName class OllamaServerTest { companion object: KLogging() @Test fun `launch ollama server`() { OllamaServer().use { ollama -> ollama.start() val version = getOllamaVersion(ollama.url) version shouldBeEqualTo OllamaServer.TAG } } @Test fun `download model and commit to image`() { val newImageName = "tc-ollama-allminilm-" + Base58.randomString(4).lowercase() OllamaServer().use { ollama -> ollama.start() // pull model ollama.execInContainer("ollama", "pull", "all-minilm") val modelName = getOllimaModels(ollama.url).first() modelName shouldContain "all-minilm" ollama.commitToImage(newImageName) } // substitute val imageName = DockerImageName.parse(newImageName).asCompatibleSubstituteFor(OllamaServer.IMAGE) OllamaServer(imageName).use { ollama -> ollama.start() val modelName = getOllimaModels(ollama.url).first() modelName shouldContain "all-minilm" } } private fun getOllamaVersion(endpoint: String): String { log.debug { "Get Ollama version from $endpoint" } return given() .baseUri(endpoint) .get("/api/version") .jsonPath() .getString("version") .also { version -> log.debug { "Ollama version: $version" } } } private fun getOllimaModels(endpoint: String): List<String> { return given() .baseUri(endpoint) .get("/api/tags") .jsonPath() .getList<String>("models.name") .also { models -> log.debug { "Ollama models: ${models.joinToString()}" } } } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
2,188
bluetape4k
MIT License
library/src/main/kotlin/eu/tib/orkg/prototype/statements/application/ObjectController.kt
TIBHannover
197,416,205
false
null
package eu.tib.orkg.prototype.statements.application import eu.tib.orkg.prototype.statements.api.ResourceRepresentation import eu.tib.orkg.prototype.statements.api.ResourceUseCases import eu.tib.orkg.prototype.community.domain.model.ObservatoryId import eu.tib.orkg.prototype.community.domain.model.OrganizationId import eu.tib.orkg.prototype.statements.domain.model.PredicateId import eu.tib.orkg.prototype.statements.domain.model.ResourceId import eu.tib.orkg.prototype.statements.services.ObjectService import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.PatchMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController import org.springframework.web.util.UriComponentsBuilder const val RESOURCE_EXISTING_KEY = "resource" const val LITERAL_EXISTING_KEY = "literal" const val PREDICATE_EXISTING_KEY = "predicate" const val CLASS_EXISTING_KEY = "class" @RestController @RequestMapping("/api/objects/") class ObjectController( private val resourceService: ResourceUseCases, private val service: ObjectService, ) : BaseController() { @PostMapping("/") @ResponseStatus(HttpStatus.CREATED) fun add( @RequestBody obj: CreateObjectRequest, uriComponentsBuilder: UriComponentsBuilder ): ResponseEntity<ResourceRepresentation> { val resource = service.createObject(obj, null, authenticatedUserId()) val location = uriComponentsBuilder .path("api/objects/") .buildAndExpand(resource.id) .toUri() return ResponseEntity.created(location).body(resource) } @PatchMapping("/{id}") @ResponseStatus(HttpStatus.CREATED) fun add( @PathVariable id: ResourceId, @RequestBody obj: CreateObjectRequest, uriComponentsBuilder: UriComponentsBuilder ): ResponseEntity<ResourceRepresentation> { resourceService .findById(id) .orElseThrow { ResourceNotFound(id) } val resource = service.createObject(obj, id, authenticatedUserId()) val location = uriComponentsBuilder .path("api/objects/") .buildAndExpand(resource.id) .toUri() return ResponseEntity.created(location).body(resource) } } // <editor-fold desc="Data Classes"> data class CreateObjectRequest( val predicates: List<HashMap<String, String>>?, val resource: NamedObject ) { /** * Check if the object has a set * of predicates to be processed */ fun hasTempPredicates() = this.predicates != null && this.predicates.isNotEmpty() } data class NamedObject( val name: String, val classes: List<String>?, val values: HashMap<String, List<ObjectStatement>>?, val extractionMethod: ExtractionMethod = ExtractionMethod.UNKNOWN, val observatoryId: ObservatoryId = ObservatoryId.createUnknownObservatory(), val organizationId: OrganizationId = OrganizationId.createUnknownOrganization() ) { /** * Check if the object has a set * of statements to be added recursively */ fun hasSubsequentStatements() = this.values != null && this.values.isNotEmpty() /** * Check if the resource is typed * i.e., it has classes */ fun isTyped() = this.classes != null && this.classes.isNotEmpty() } data class ObjectStatement( val `@id`: String?, val `@type`: String?, val classes: List<String>?, val `@temp`: String?, val text: String?, val datatype: String?, val label: String?, val values: HashMap<String, List<ObjectStatement>>? ) { /** * Indicate if the entity is an existing thing * i.e., the @id property is used in the json object */ fun isExisting() = this.`@id` != null /** * Check if an entity is existing and explicitly typed. * Allowed types are: [class, resource, predicate, literal] */ fun isTypedExisting() = this.isExisting() && this.`@type` != null /** * Check if the entity is existing as a resource * If it is typed with resource * o/w if the id starts with an R */ fun isExistingResource() = this.isExisting() && when (this.`@type`) { null -> this.`@id`!!.startsWith("R") RESOURCE_EXISTING_KEY -> true else -> false } /** * Check if the entity is existing as a literal * If it is typed with literal * o/w if the id starts with an L */ fun isExistingLiteral() = this.isExisting() && when (this.`@type`) { null -> this.`@id`!!.startsWith("L") LITERAL_EXISTING_KEY -> true else -> false } /** * Check if the entity is existing as a class * If it is typed with class */ fun isExistingClass() = this.isTypedExisting() && this.`@type` == CLASS_EXISTING_KEY /** * Check if the entity is existing as a predicate * If it is typed with predicate */ fun isExistingPredicate() = this.isTypedExisting() && this.`@type` == PREDICATE_EXISTING_KEY /** * Check if the resource is a temp resource * i.e., its id starts with an _ */ fun isTempResource() = this.`@id`!!.startsWith("_") /** * Check if the resource is typed * i.e., it has classes */ fun isTyped() = this.classes != null && this.classes.isNotEmpty() /** * Check if this is a new resource to be created * i.e., the label property in the json object is used */ fun isNewResource() = this.label != null /** * Check if this is a new literal to be created * i.e., the text property in the json object is used */ fun isNewLiteral() = this.text != null /** * Check if the object has a set * of statements to be added recursively */ fun hasSubsequentStatements() = this.values != null && this.values.isNotEmpty() } data class TempResource( val subject: ResourceId, val predicate: PredicateId, val `object`: String ) // </editor-fold>
0
Kotlin
1
4
84e17adb51e35e7123e1d853d49ae1d8ea95d400
6,465
orkg-backend
MIT License
compose-dot/src/main/kotlin/dev/arunkumar/compose/dot/Dot.kt
arunkumar9t2
364,978,130
false
null
package dev.arunkumar.compose.dot import androidx.compose.runtime.Composable import androidx.compose.runtime.Composition import androidx.compose.runtime.Recomposer import dev.arunkumar.dot.* import kotlinx.coroutines.Dispatchers @DslMarker annotation class DotDslScope @DotDslScope inline class DotGraphScope(val dotGraph: DotGraph) { inline operator fun String.invoke(nodeBuilder: DotNode.() -> Unit = {}): String { dotGraph.add(DotNode(this).apply(nodeBuilder)) return this } infix fun String.link(target: String): EdgeBuilder { val dotEdge = DirectedDotEdge(this, target).also(dotGraph::add) return EdgeBuilder(dotEdge) } inline fun graph(builder: DotStatement.() -> Unit) { dotGraph.add(DotStatement("graph").apply(builder)) } inline fun node(builder: DotStatement.() -> Unit) { dotGraph.add(DotStatement("node").apply(builder)) } } @DotDslScope class EdgeBuilder(private val dotEdge: DotEdge) { operator fun invoke(edgeBuilder: DotEdge.() -> Unit) { dotEdge.apply(edgeBuilder) } } fun DirectedGraph( name: String, parent: Recomposer = Recomposer(Dispatchers.Main), content: @Composable DotGraphScope.() -> Unit ): Pair<DotGraph, Composition> { val dotGraph = DotGraph("digraph ${name.quote}") val applier = DotStatementApplier(rootDotGraph = dotGraph) val composition = Composition(applier = applier, parent = parent) composition.setContent { content(DotGraphScope(dotGraph)) } return applier.root as DotGraph to composition }
0
Kotlin
0
31
40a5c9fc0e44c5bc98b90efd901a4c615af94074
1,512
compose-dot
Apache License 2.0
stripe-ui-core/src/main/java/com/stripe/android/uicore/elements/PhoneNumberElement.kt
stripe
6,926,049
false
{"Kotlin": 11893047, "Java": 70838, "Ruby": 22569, "Python": 21716, "Shell": 20293, "HTML": 7519}
package com.stripe.android.uicore.elements import androidx.annotation.RestrictTo @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) data class PhoneNumberElement( override val identifier: IdentifierSpec, override val controller: PhoneNumberController ) : SectionSingleFieldElement(identifier)
126
Kotlin
629
1,227
c351d4adda26782202e3844f9bbbe556e80bdd76
303
stripe-android
MIT License
app/src/main/java/com/example/mycocktailsexpert/domain/drinks/usecases/SearchDrinksUseCase.kt
alexaniko88
777,171,389
false
{"Kotlin": 38706}
package com.example.mycocktailsexpert.domain.drinks.usecases import com.example.mycocktailsexpert.domain.drinks.entities.MyDrinks interface SearchDrinksUseCase { suspend fun execute(searchText: String): MyDrinks }
0
Kotlin
0
1
f4bee0f9b32bce334a9704164b313ce86e4268d2
220
MyCocktailsExpert
MIT License
sparkrecyclerview/src/main/java/com/louisfn/sparkrecyclerview/SparkItem.kt
LouisFn
284,340,133
false
null
package com.louisfn.sparkrecyclerview internal data class SparkItem<E>( var element: E? = null, var isHeader: Boolean = false, var isFooter: Boolean = false ) { val isHeaderOrFooter get() = isHeader || isFooter }
0
Kotlin
0
0
96f8760e4075b43925ddcc423e2cc7c48d995b6b
239
SparkRecyclerView
Apache License 2.0
app/src/main/java/com/example/weatherapp/data/WeatherResponse.kt
Christinepeng
840,926,905
false
{"Kotlin": 21106}
package com.example.weatherapp.data import androidx.room.Entity import androidx.room.PrimaryKey data class WeatherResponse( val main: Main, val weather: List<Weather>, val name: String ) data class Main( val temp: Double, val humidity: Int ) data class Weather( val description: String, val icon: String ) @Entity(tableName = "weather_table") data class WeatherEntity( @PrimaryKey(autoGenerate = true) val id: Int = 0, val cityName: String, val temperature: Double, val description: String, val icon: String, val timestamp: Long = System.currentTimeMillis() )
0
Kotlin
0
0
0a84bca30319e1eaa0ea5e3024a5d80a2d05faec
617
WeatherApp
Apache License 2.0
samples/src/main/kotlin/samples/SpawnSingleProcess.kt
aarangop
618,418,716
false
null
/* * Copyright (c) 2023. <NAME> <<EMAIL>> * * You may use, distribute and modify this code under the terms of the MIT license. */ package samples import Environment import process.SimProcess fun main() { // Create environment val env = Environment() val simpleProcess = SimProcess(env, sequence { println("Starting process execution @${env.now}") yield(env.timeout(50.0)) println("First process step executed @${env.now}") yield(env.timeout(35.0)) println("Second process step executed @${env.now}") }) env.schedule(simpleProcess) env.run() }
5
Kotlin
0
0
0424d803419e52da6abd6df957c4134f37c78e03
616
k-DESim
MIT License
app/src/main/java/com/ddiehl/rgsc/utils/ViewGroupExtensions.kt
damien5314
18,043,613
false
null
package com.ddiehl.rgsc.utils import android.view.View import android.view.ViewGroup import java.util.* fun ViewGroup.getChildren(): Iterable<View> { var list = ArrayList<View>() for (i in 0..childCount-1) list.add(getChildAt(i)) return list }
0
Kotlin
0
0
02615b7a1b2ce333c213852d7897aea57694a01c
257
RhythmGameScoreCalculator
Apache License 2.0
app/src/main/java/tj/boronov/farhang/ui/phrasebook/category/CategoryViewModel.kt
intoxication
375,275,467
false
null
package tj.boronov.farhang.ui.phrasebook.category import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingSource import androidx.paging.cachedIn import tj.boronov.farhang.App import tj.boronov.farhang.data.model.Categories import tj.boronov.farhang.data.model.Phrases import tj.boronov.farhang.data.model.Subcategory class CategoryViewModel : ViewModel() { lateinit var category: Categories lateinit var subcategoryList: List<Subcategory> var query = MutableLiveData<String>("") private var pagingSource: PagingSource<Int, Phrases>? = null suspend fun init(_category: Categories) { category = _category subcategoryList = App.database.phrasebookDao().getSubcategories(category.id) } val flow = Pager( PagingConfig(pageSize = 30, enablePlaceholders = true) ) { App.database.phrasebookDao().getPhrases(category.id, query.value!!).also { pagingSource = it } }.flow.cachedIn(viewModelScope) fun searchPhrases(_phrase: String) { query.value = if (_phrase.isEmpty() || _phrase.isBlank()) "" else "%$_phrase%" pagingSource?.invalidate() } }
0
null
0
0
775048d37136e72ee23af6bcef6366d43521b9f1
1,310
farhang
MIT License
src/main/kotlin/validations/LengthValidation.kt
davidisla
523,437,654
false
null
package validations class LengthValidation(private val length: Int) : Validation { override fun invoke(pattern: String): Boolean = pattern.length < length }
0
Kotlin
0
0
8b89d1e5b41784b089278e1f0d5133a9d74bd2d1
169
kataPasswordValidation
Apache License 2.0
player/src/main/java/com/kafka/player/queue/PlayerQueue.kt
compose-forks
271,084,093
false
{"Kotlin": 266767, "Java": 11357}
package com.kafka.player.queue //package com.kafka.player.queue // //import com.kafka.player.model.PlaybackItem //import com.kafka.player.model.PlayerHead // //interface PlayerQueue { // // fun init(item: PlaybackItem, head: PlayerHead?) // // fun currentSong(): PlaybackItem? // // fun head(): PlayerHead? // // fun setHead(head: PlayerHead?) // // fun next() // // fun prev() // // fun enqueue(item: PlaybackItem) // // fun enqueue(item: PlaybackItem, song: PlaybackItem) // // fun enqueueSong(item: PlaybackItem) // // fun dequeue(item: PlaybackItem) // // fun size(): Int // // fun clear() // // fun upcomingSongs(): Pair<PlaybackItem, PlaybackItem>? // // fun currentPlaylist(): PlaybackItem? // // fun queueItems(): List<PlaybackItem>? // // fun hasNext(): Boolean // // fun hasPrev(): Boolean //}
0
null
0
0
a528ca24c799f7f896cab65d2b2a0f8c11a7d2fd
856
Kafka
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/iam/CfnAccessKeyPropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.iam import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.iam.CfnAccessKeyProps @Generated public fun buildCfnAccessKeyProps(initializer: @AwsCdkDsl CfnAccessKeyProps.Builder.() -> Unit): CfnAccessKeyProps = CfnAccessKeyProps.Builder().apply(initializer).build()
1
Kotlin
0
0
a1cf8fbfdfef9550b3936de2f864543edb76348b
395
aws-cdk-kt
Apache License 2.0
source-downloader-core/src/main/kotlin/xyz/shoaky/sourcedownloader/core/file/PersistentSourceContent.kt
shoaky009
607,575,763
false
null
package xyz.shoaky.sourcedownloader.core.file import xyz.shoaky.sourcedownloader.sdk.MapPatternVariables import xyz.shoaky.sourcedownloader.sdk.SourceContent import xyz.shoaky.sourcedownloader.sdk.SourceItem data class PersistentSourceContent( override val sourceItem: SourceItem, override val sourceFiles: List<CoreFileContent>, val sharedPatternVariables: MapPatternVariables ) : SourceContent
1
Kotlin
0
5
16c265c082112aad122bb8a59cad6308e35da098
409
source-downloader
Apache License 2.0
app/src/main/java/com/asb/presentation/auth/ProgramActivity.kt
rizkyhamdhany
243,784,183
false
null
package com.asb.presentation.auth import android.os.Bundle import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.liveData import androidx.lifecycle.switchMap import com.asb.android.R import com.asb.core.model.MedcekRespond import com.asb.core.model.ProgramPostData import com.asb.core.network.Resource import com.asb.core.network.Status import com.asb.core.repository.LoginRepository import com.asb.presentation.BaseActivity import kotlinx.android.synthetic.main.activity_program.cemilan import kotlinx.android.synthetic.main.activity_program.input_pasien_btn import kotlinx.android.synthetic.main.activity_program.jalan_kaki import kotlinx.android.synthetic.main.activity_program.makan_pagi import kotlinx.android.synthetic.main.activity_program.makan_siang import kotlinx.android.synthetic.main.activity_program.makan_sore import kotlinx.android.synthetic.main.activity_program.minum1 import kotlinx.android.synthetic.main.activity_program.minum2 import kotlinx.android.synthetic.main.activity_program.olahraga import kotlinx.android.synthetic.main.activity_program.puasa import kotlinx.android.synthetic.main.activity_program.sikap import kotlinx.android.synthetic.main.activity_program.tanggal import kotlinx.android.synthetic.main.activity_program.tidur_siang import kotlinx.android.synthetic.main.activity_program.toolbar import kotlinx.coroutines.Dispatchers import org.koin.android.ext.android.inject class ProgramActivity : BaseActivity() { var programId = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) programId = intent.getIntExtra("id", 0) setContentView(R.layout.activity_program) setToolbar(toolbar) setViewListener() process.observe(this, observer) } private val authRepo: LoginRepository by inject() private var postData = MutableLiveData<ProgramPostData>() private var process = postData.switchMap { data -> liveData(Dispatchers.IO) { emit(Resource.loading(null)) emit(authRepo.programLogSubmit(data)) } } private val observer = Observer<Resource<MedcekRespond>> { when (it.status) { Status.SUCCESS -> { finish() } Status.ERROR -> { showDialog(ERROR_MSG) } } } private fun setViewListener() { input_pasien_btn.setOnClickListener { postData.value = ProgramPostData( program_id = programId, cemilan = cemilan.text.toString(), fasting = puasa.text.toString(), jalan_kaki = jalan_kaki.text.toString(), makan_pagi = makan_pagi.text.toString(), makan_siang = makan_siang.text.toString(), makan_sore = makan_sore.text.toString(), minum1 = minum1.text.toString(), minum2 = minum2.text.toString(), olahraga = olahraga.text.toString(), sikap = sikap.text.toString(), tanggal = tanggal.text.toString(), tidur_siang = tidur_siang.text.toString() ) } } }
0
Kotlin
0
0
42a6ef0d5ae6bb2ba1fdc4a12b6aea932c60f92d
3,235
asb-android
Apache License 2.0
roboquant-jupyter/src/test/kotlin/org/roboquant/jupyter/PriceChartTest.kt
neurallayer
406,929,056
false
null
/* * Copyright 2020-2023 Neural Layer * * 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 org.roboquant.jupyter import org.junit.jupiter.api.Test import org.roboquant.feeds.RandomWalkFeed import kotlin.test.assertEquals import kotlin.test.assertNotEquals import kotlin.test.assertTrue internal class PriceChartTest { @Test fun test() { val feed = RandomWalkFeed.lastYears(1) val asset = feed.assets.first() Chart.counter = 0 val chart = PriceChart(feed, asset) val html = chart.asHTML() assertTrue(html.isNotBlank()) Chart.counter = 0 val chart2 = PriceChart(feed, asset.symbol) assertEquals(html, chart2.asHTML()) Chart.counter = 0 val chart3 = PriceChart(feed, asset.symbol, priceType = "OPEN") assertNotEquals(html, chart3.asHTML()) } }
17
Kotlin
29
217
2b8f0cfcb12718d6a615eea4397b7c8dd91c1bfc
1,374
roboquant
Apache License 2.0
src/main/kotlin/org/skellig/plugin/language/teststep/psi/impl/SkelligTestStepFunctionImpl.kt
skellig-framework
309,154,374
false
null
package org.skellig.plugin.language.teststep.psi.impl import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import org.skellig.plugin.language.teststep.psi.SkelligTestStepElementVisitor interface SkelligTestStepFunction : PsiElement { } class SkelligTestStepFunctionImpl(node: ASTNode) : SkelligTestStepPsiElementBase(node), SkelligTestStepFunction { override fun getPresentableText(): String { return "Test Step: $elementText" } override fun acceptTestStep(visitor: SkelligTestStepElementVisitor) { visitor.visit(this) } }
0
Kotlin
0
1
9eb8fef6f1054bcd0a3cbc4fcbefbebe64655397
576
skellig-intellij-plugin
Apache License 2.0
src/main/kotlin/io/openfuture/chain/rpc/validation/TransferTransactionValidator.kt
OpenFuturePlatform
135,143,034
false
{"Kotlin": 466643, "Dockerfile": 210, "Shell": 74}
package io.openfuture.chain.rpc.validation import io.openfuture.chain.rpc.domain.transaction.request.TransferTransactionRequest import io.openfuture.chain.rpc.validation.annotation.TransferTransaction import javax.validation.ConstraintValidator import javax.validation.ConstraintValidatorContext class TransferTransactionValidator : ConstraintValidator<TransferTransaction, TransferTransactionRequest> { override fun isValid(value: TransferTransactionRequest, context: ConstraintValidatorContext?): Boolean = null != value.recipientAddress || null != value.data }
2
Kotlin
16
64
f7e511b3ba17cc75d7f23618008dd89a7b83c4c0
579
open-chain
MIT License
FitLifeIn30Days/app/src/main/java/com/example/fitlifein30days/workout/WorkoutViewModel.kt
atakan-ozkan
732,440,741
false
{"Kotlin": 42044}
package com.example.fitlifein30days import android.content.Context import androidx.lifecycle.ViewModel import org.xmlpull.v1.XmlPullParser import java.io.IOException class WorkoutViewModel (context: Context) : ViewModel(){ private val workoutsForMale = listOf( WorkoutModel(R.drawable.benchpressman, "Bench Press"), WorkoutModel(R.drawable.bicepsman, "Biceps Workout"), WorkoutModel(R.drawable.deadliftman, "Deadlift"), WorkoutModel(R.drawable.declinedumbleman, "Decline Dumbbell Press"), WorkoutModel(R.drawable.dumbellbackrowman, "Dumbbell Back Row"), WorkoutModel(R.drawable.hanginglegraisesman, "Hanging Leg Raises"), WorkoutModel(R.drawable.legpullinsman, "Leg Pull-Ins"), WorkoutModel(R.drawable.lateralraiseman, "Lateral Raise"), WorkoutModel(R.drawable.pushupman, "Push Up"), WorkoutModel(R.drawable.skulltricepsman, "Skull Crusher Triceps"), WorkoutModel(R.drawable.squatman, "Squat"), WorkoutModel(R.drawable.standshoulderpressman, "Standing Shoulder Press"), WorkoutModel(R.drawable.stitwistman, "Seated Twist") ) private val workoutsForFemale = listOf( WorkoutModel(R.drawable.abdominalwoman, "Abdominal Workout"), WorkoutModel(R.drawable.cobralatpulldownwoman, "Cobra Lat Pulldown"), WorkoutModel(R.drawable.invertedplankwoman, "Inverted Plank"), WorkoutModel(R.drawable.legstretchwoman, "Leg Stretching"), WorkoutModel(R.drawable.lowerabswoman, "Lower Abs Workout"), WorkoutModel(R.drawable.pushupwoman, "Push Up"), WorkoutModel(R.drawable.sidelegraisewoman, "Side Leg Raise"), WorkoutModel(R.drawable.singlelegdeadliftwoman, "Single Leg Deadlift"), WorkoutModel(R.drawable.squatwoman, "Squat") ) private val thirtyDaySchedule: Map<String, List<WorkoutModel>> init { val weeklySchedule = parseWeeklyWorkoutSchedule(context) thirtyDaySchedule = createThirtyDaySchedule(weeklySchedule) } fun getWorkoutSchedule(day: Int, gender: String): List<WorkoutModel>?{ return thirtyDaySchedule["Day$day-$gender"] } private fun createThirtyDaySchedule(weeklySchedule: Map<String, List<WorkoutModel>>): Map<String, List<WorkoutModel>> { val thirtyDaySchedule = mutableMapOf<String, List<WorkoutModel>>() for (day in 1..30) { val weekDay = (day - 1) % 7 + 1 for (gender in listOf("Male", "Female")) { val weeklyKey = "Day$weekDay-$gender" val thirtyDayKey = "Day$day-$gender" weeklySchedule[weeklyKey]?.let { thirtyDaySchedule[thirtyDayKey] = it } } } return thirtyDaySchedule } private fun parseWeeklyWorkoutSchedule(context: Context): Map<String, List<WorkoutModel>> { val schedule = mutableMapOf<String, MutableList<WorkoutModel>>() try { val parser = context.resources.getXml(R.xml.weekly_workout_schedule) var eventType = parser.eventType var day = "" var gender = "" var tempWorkoutList = listOf<WorkoutModel>() while (eventType != XmlPullParser.END_DOCUMENT) { when (eventType) { XmlPullParser.START_TAG -> { when (parser.name) { "day" -> day = "Day${parser.getAttributeValue(null, "number")}" "gender" -> { gender = parser.getAttributeValue(null, "type") tempWorkoutList = if (gender.equals("Male", ignoreCase = true)){ workoutsForMale } else{ workoutsForFemale } } "workout" -> { val workoutName = parser.getAttributeValue(null, "name") tempWorkoutList.find { it.title.equals(workoutName, ignoreCase = true) }?.let { val key = "$day-$gender" schedule.computeIfAbsent(key) { mutableListOf() } .add(it) } } } } } eventType = parser.next() } } catch (e: IOException) { e.printStackTrace() } return schedule } }
0
Kotlin
0
0
ffc0fb645d26491a1495a9de4a7b6a53cb4a10ac
4,677
comp319a-2023f-assign3
MIT License
litho-core/src/main/java/com/facebook/litho/cancellation/FutureCancelledByPolicyException.kt
philIip
627,174,901
true
{"Java Properties": 57, "Markdown": 81, "Gradle": 81, "Shell": 17, "Text": 2, "Batchfile": 12, "Starlark": 174, "Ignore List": 7, "Java": 1639, "XML": 157, "Kotlin": 881, "YAML": 6, "C": 2, "C++": 41, "CMake": 3, "Proguard": 10, "JavaScript": 7, "JSON": 1, "SVG": 14, "HTML": 1211, "CSS": 1, "SCSS": 2, "MDX": 70, "INI": 1}
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.cancellation /** * This exception should only be thrown whenever there is an [InterruptedException] or * [CancellationException] thrown inside a [TreeFuture] while being marked with * [TreeFuture.isCancelled] */ internal class FutureCancelledByPolicyException() : RuntimeException()
0
null
0
0
c66f7760ef0ca91232b44955881139c333121438
935
litho
Apache License 2.0
backend/src/main/kotlin/com/project/nanuriserver/domain/post/exception/InvalidCategoryException.kt
hackersground-kr
847,204,786
false
{"Kotlin": 75137, "TypeScript": 69688, "Bicep": 5862, "HTML": 1652, "CSS": 1371, "Shell": 89}
package com.project.nanuriserver.domain.post.exception import com.project.nanuriserver.domain.post.exception.error.PostError import com.project.nanuriserver.global.exception.BusinessException object InvalidCategoryException : BusinessException(PostError.INVALID_CATEGORY) { private fun readResolve(): Any = InvalidCategoryException }
0
Kotlin
3
2
10faf92c3a3ea48bdf7ab991d532e405ad88d223
340
hg-Team-azure-love
MIT License
src/main/kotlin/org/cryptobiotic/eg/core/ecgroup/EcGroupContext.kt
JohnLCaron
760,153,500
false
{"Kotlin": 1064430, "C": 26235}
package org.cryptobiotic.eg.core.ecgroup import org.cryptobiotic.eg.core.* import java.math.BigInteger class EcGroupContext(val name: String, useNative: Boolean = true): GroupContext { val vecGroup: VecGroup = VecGroups.getEcGroup(name, useNative) val ONE = EcElementModP(this, vecGroup.ONE) override val GINV_MOD_P: ElementModP = EcElementModP(this, vecGroup.g.inv()) override val G_MOD_P: ElementModP = EcElementModP(this, vecGroup.g) override val G_SQUARED_MOD_P: ElementModP = EcElementModP(this, vecGroup.g.square()) override val NUM_P_BITS: Int = vecGroup.pbitLength override val MAX_BYTES_P: Int = vecGroup.pbyteLength + 1 // x plus sign of y override val ONE_MOD_P: ElementModP = this.ONE override val MAX_BYTES_Q: Int = vecGroup.qbyteLength override val ZERO_MOD_Q: ElementModQ = EcElementModQ(this, BigInteger.ZERO) override val ONE_MOD_Q: ElementModQ = EcElementModQ(this, BigInteger.ONE) override val TWO_MOD_Q: ElementModQ = EcElementModQ(this, BigInteger.TWO) val NUM_Q_BITS: Int = vecGroup.qbitLength override val constants = vecGroup.constants val dlogg = DLogarithm(G_MOD_P) // TODO diff of this and safe version? override fun binaryToElementModP(b: ByteArray): ElementModP? { val elem = vecGroup.elementFromByteArray(b) return if (elem != null) EcElementModP(this, elem) else null } override fun binaryToElementModPsafe(b: ByteArray, minimum: Int): ElementModP { return binaryToElementModP(b) ?: throw RuntimeException("invalid input") } override fun binaryToElementModQ(b: ByteArray): ElementModQ? { return EcElementModQ(this, BigInteger(1, b)) } override fun binaryToElementModQsafe(b: ByteArray, minimum: Int): ElementModQ { return EcElementModQ(this, BigInteger(1, b)) } override fun dLogG(p: ElementModP, maxResult: Int): Int? { require(p is EcElementModP) return dlogg.dLog(p, maxResult) } override fun gPowP(exp: ElementModQ): ElementModP { require(exp is EcElementModQ) return EcElementModP(this, vecGroup.g.exp(exp.element)) } override fun getAndClearOpCounts(): Map<String, Int> { return emptyMap() } override fun isCompatible(ctx: GroupContext): Boolean { return (ctx is EcGroupContext) && name == ctx.name } override fun isProductionStrength(): Boolean { return true } override fun uIntToElementModQ(i: UInt): ElementModQ { return EcElementModQ(this, BigInteger.valueOf(i.toLong())) } override fun uLongToElementModQ(i: ULong): ElementModQ { return EcElementModQ(this, BigInteger.valueOf(i.toLong())) } override fun Iterable<ElementModQ>.addQ(): ElementModQ { return addQQ(this) } override fun Iterable<ElementModP>.multP(): ElementModP { return this.reduce { a, b -> a * b } } override fun randomElementModP(minimum: Int) = EcElementModP(this, vecGroup.randomElement()) // TODO could these be done with just a mod at the end? fun addQQ(cues: Iterable<ElementModQ>): ElementModQ { val sum = cues.fold(BigInteger.ZERO) { a, b -> a.plus((b as EcElementModQ).element) } return EcElementModQ(this, sum.mod(vecGroup.order)) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as EcGroupContext return name == other.name } override fun hashCode(): Int { return name.hashCode() } override fun prodPowers(bases: List<ElementModP>, exps: List<ElementModQ>): ElementModP { require(exps.size == bases.size) if (bases.isEmpty()) { return ONE_MOD_P } // TODO seems a bit awkward.... val ec = vecGroup.prodPowers(bases, exps) return EcElementModP(this, ec) } }
0
Kotlin
0
0
2acaeac9d4b6db99dd3d98165606154ccbb563e4
3,935
egk-ec
MIT License
kstatemachine/src/main/kotlin/ru/nsk/kstatemachine/TransitionDirection.kt
Obighbyd
427,186,102
false
null
package ru.nsk.kstatemachine sealed class TransitionDirection { open val targetState: IState? = null } /** * [Transition] is triggered, but state is not changed */ internal object Stay : TransitionDirection() fun stay(): TransitionDirection = Stay /** * [Transition] should not be triggered */ internal object NoTransition : TransitionDirection() fun noTransition(): TransitionDirection = NoTransition /** * [Transition] is triggered with a [targetState] */ internal class TargetState(override val targetState: IState) : TransitionDirection() fun targetState(targetState: IState): TransitionDirection = TargetState(targetState)
0
Kotlin
0
0
49654e06121d1769049d3428600a12f90e194ffa
645
kstatemachine
Boost Software License 1.0
src/main/kotlin/cn/rtast/rob/entity/Message.kt
RTAkland
848,228,984
false
{"Kotlin": 108404}
/* * Copyright © 2024 RTAkland * Author: RTAkland * Date: 2024/8/26 */ package cn.rtast.rob.entity import cn.rtast.rob.ROneBotFactory import cn.rtast.rob.ROneBotFactory.actionCoroutineScope import cn.rtast.rob.actionable.MessageActionable import cn.rtast.rob.entity.lagrange.ForwardMessageId import cn.rtast.rob.util.ob.CQMessageChain import cn.rtast.rob.util.ob.MessageChain import cn.rtast.rob.util.ob.NodeMessageChain import cn.rtast.rob.util.ob.OneBotListener import com.google.gson.annotations.SerializedName import kotlinx.coroutines.delay import kotlinx.coroutines.launch data class GroupMessage( @SerializedName("sub_type") val subType: String, @SerializedName("message_id") val messageId: Long, @SerializedName("user_id") val userId: Long, @SerializedName("group_id") val groupId: Long, val message: List<ArrayMessage>, @SerializedName("raw_message") val rawMessage: String, var sender: Sender, val time: Long, val listener: OneBotListener ) : MessageActionable { override suspend fun revoke(delay: Int) { super.revoke(delay) if (delay != 0) actionCoroutineScope.launch { delay(delay * 1000L) ROneBotFactory.action.revokeMessage(messageId) } else ROneBotFactory.action.revokeMessage(messageId) } override suspend fun reply(content: MessageChain) { val msg = MessageChain.Builder() .addReply(messageId) .addRawArrayMessage(content.finalArrayMsgList) .build() ROneBotFactory.action.sendGroupMessage(groupId, msg) } override suspend fun reply(content: String) { val msg = MessageChain.Builder().addText(content).build() this.reply(msg) } override suspend fun reply(content: CQMessageChain) { this.reply(content.finalString) } override suspend fun reply(content: NodeMessageChain, async: Boolean): ForwardMessageId.Data? { if (async) { ROneBotFactory.action.sendGroupForwardMsgAsync(groupId, content) return null } else { return ROneBotFactory.action.sendGroupForwardMsg(groupId, content) } } } data class PrivateMessage( @SerializedName("sub_type") val subType: String, @SerializedName("message_id") val messageId: Long, @SerializedName("user_id") val userId: Long, val message: List<ArrayMessage>, @SerializedName("raw_message") val rawMessage: String, val sender: Sender, val time: Long, ) : MessageActionable { override suspend fun revoke(delay: Int) { super.revoke(delay) if (delay != 0) actionCoroutineScope.launch { delay(delay * 1000L) ROneBotFactory.action.revokeMessage(messageId) } else ROneBotFactory.action.revokeMessage(messageId) } override suspend fun reply(content: MessageChain) { val msg = MessageChain.Builder() .addReply(messageId) .addRawArrayMessage(content.finalArrayMsgList) .build() ROneBotFactory.action.sendPrivateMessage(userId, msg) } override suspend fun reply(content: String) { val msg = MessageChain.Builder().addText(content).build() this.reply(msg) } override suspend fun reply(content: CQMessageChain) { this.reply(content.finalString) } override suspend fun reply(content: NodeMessageChain, async: Boolean): ForwardMessageId.Data? { if (async) { ROneBotFactory.action.sendPrivateForwardMsgAsync(sender.userId, content) return null } else { return ROneBotFactory.action.sendPrivateForwardMsg(sender.userId, content) } } }
0
Kotlin
0
1
fd3c166d03f2f2f12b407821391c9f58837c81e0
3,728
ROneBot
Apache License 2.0
mvi-test-util/src/main/kotlin/dev/sunnyday/arch/mvi/test/ConstructorRule.kt
SunnyDayDev
613,837,799
false
null
package dev.sunnyday.arch.mvi.test import io.mockk.Matcher import io.mockk.MockKGateway import io.mockk.every import kotlin.reflect.KClass @Suppress("UnusedEquals") class ConstructorRule<T: Any>( private val marker: Any, private val matchers: Array<Matcher<*>>, private val klass: KClass<T>, ) { fun verifyConstructorCalled(obj: Any, transformMatchers: ((Array<Matcher<*>>) -> Unit)? = null) { val matchers = if (transformMatchers != null) { matchers.copyOf().also(transformMatchers) } else { matchers } obj == marker io.mockk.verify { MockKGateway.implementation().constructorMockFactory.mockPlaceholder( klass, args = matchers ) == marker } } companion object { inline fun <reified T : Any> create(vararg matchers: Matcher<*>): ConstructorRule<T> { val marker = Any() every { constructedWith<T>(*matchers) == marker } returns false @Suppress("UNCHECKED_CAST") return ConstructorRule(marker, matchers as Array<Matcher<*>>, T::class) } @Suppress("TestFunctionName") fun <T> Matcher(match: (T) -> Boolean): Matcher<T> = object : Matcher<T> { override fun match(arg: T?): Boolean = arg?.let(match) ?: false } } }
13
Kotlin
0
1
30d3e472138d9797d9eda0363c7aae052e89623c
1,375
arch-mvi
MIT License
viewmodel/src/commonMain/kotlin/tech/skot/libraries/map/MapLogger.kt
skot-framework
416,366,518
false
{"Kotlin": 156431}
package tech.skot.libraries.map import tech.skot.core.SKLogger object MapLogger : SKLogger("sk-map")
0
Kotlin
1
0
9fb2c59c672cb1fad467c968d70c8d7b5040dfd4
102
sk-map
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/cloud9/RepositoryPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.cloud9 import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.cloud9.CfnEnvironmentEC2 @Generated public fun buildRepositoryProperty(initializer: @AwsCdkDsl CfnEnvironmentEC2.RepositoryProperty.Builder.() -> Unit): CfnEnvironmentEC2.RepositoryProperty = CfnEnvironmentEC2.RepositoryProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
463
aws-cdk-kt
Apache License 2.0
feature-governance-api/src/main/java/io/novafoundation/nova/feature_governance_api/data/network/blockhain/model/PreImage.kt
novasamatech
415,834,480
false
{"Kotlin": 11112596, "Rust": 25308, "Java": 17664, "JavaScript": 425}
package io.novafoundation.nova.feature_governance_api.data.network.blockhain.model import io.novasama.substrate_sdk_android.runtime.definitions.types.generics.GenericCall class PreImage(val encodedCall: ByteArray, val call: GenericCall.Instance)
14
Kotlin
30
50
166755d1c3388a7afd9b592402489ea5ca26fdb8
248
nova-wallet-android
Apache License 2.0
feature-governance-api/src/main/java/io/novafoundation/nova/feature_governance_api/data/network/blockhain/model/PreImage.kt
novasamatech
415,834,480
false
{"Kotlin": 11112596, "Rust": 25308, "Java": 17664, "JavaScript": 425}
package io.novafoundation.nova.feature_governance_api.data.network.blockhain.model import io.novasama.substrate_sdk_android.runtime.definitions.types.generics.GenericCall class PreImage(val encodedCall: ByteArray, val call: GenericCall.Instance)
14
Kotlin
30
50
166755d1c3388a7afd9b592402489ea5ca26fdb8
248
nova-wallet-android
Apache License 2.0
skiko/src/commonMain/kotlin/org/jetbrains/skiko/SkikoView.kt
JetBrains
282,864,178
false
null
package org.jetbrains.skiko @Deprecated( message = "Replaced with SkikoRenderDelegate", replaceWith = ReplaceWith("SkikoRenderDelegate") ) typealias SkikoView = SkikoRenderDelegate @Deprecated( message = "Replaced with SkiaLayerRenderDelegate", replaceWith = ReplaceWith("SkiaLayerRenderDelegate") ) typealias GenericSkikoView = SkiaLayerRenderDelegate
23
null
118
1,821
bbfaf62256fcf0255ac2b5846223f27c43dbfb00
371
skiko
Apache License 2.0
vire-stdlib/src/main/kotlin/net/voxelpi/vire/stdlib/kernel/Adders.kt
VoxelPi
700,036,011
false
{"Kotlin": 424819}
package net.voxelpi.vire.stdlib.kernel import net.voxelpi.vire.engine.kernel.Kernel import net.voxelpi.vire.engine.kernel.KernelProvider import net.voxelpi.vire.engine.kernel.kernel import net.voxelpi.vire.engine.kernel.variable.InputScalar import net.voxelpi.vire.engine.kernel.variable.OutputScalar import net.voxelpi.vire.engine.kernel.variable.createInput import net.voxelpi.vire.engine.kernel.variable.createOutput public object HalfAdder : KernelProvider { public val inputA: InputScalar = createInput("input_a") public val inputB: InputScalar = createInput("input_b") public val sum: OutputScalar = createOutput("output") public val carryOut: OutputScalar = createOutput("carry_out") override val kernel: Kernel = kernel { declare(inputA) declare(inputB) declare(sum) declare(carryOut) onUpdate { context -> val a = context[inputA].booleanState() val b = context[inputB].booleanState() context[sum] = a xor b context[carryOut] = a and b } } } public object FullAdder : KernelProvider { public val inputA: InputScalar = createInput("input_a") public val inputB: InputScalar = createInput("input_b") public val carryIn: InputScalar = createInput("carry_in") public val sum: OutputScalar = createOutput("output") public val carryOut: OutputScalar = createOutput("carry_out") override val kernel: Kernel = kernel { declare(inputA) declare(inputB) declare(carryIn) declare(sum) declare(carryOut) onUpdate { context -> val a = context[inputA].booleanState() val b = context[inputB].booleanState() val c = context[carryIn].booleanState() context[sum] = a xor b xor c context[carryOut] = (a and b) or (a and c) or (b and c) } } }
1
Kotlin
0
0
5ecadbfc298061e5fc680c37c93784ff4184fef8
1,902
Vire
MIT License
common/src/main/java/com/jonnyzzz/teamcity/plugins/node/common/GruntBean.kt
jonnyzzz
7,573,978
false
null
/* * Copyright 2013-2015 <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.jonnyzzz.teamcity.plugins.node.common /** * Created by <NAME> (<EMAIL>) * Date: 27.04.13 9:58 */ class GruntBean { val gruntConfigurationParameter : String = "grunt" val runTypeName: String = "jonnyzzz.grunt" val file: String = "jonnyzzz.grunt.file" val targets: String = "jonnyzzz.grunt.tasks" val commandLineParameterKey : String = "jonnyzzz.commandLine" val gruntMode : String = "jonnyzzz.grunt.mode" val gruntModeDefault : GruntExecutionMode = GruntExecutionMode.NPM val gruntModes : List<GruntExecutionMode> get() = arrayListOf(*GruntExecutionMode.values()) fun parseMode(text : String?) : GruntExecutionMode? = gruntModes.firstOrNull { text == it.value } ?: gruntModeDefault fun parseCommands(text: String?): Collection<String> { if (text == null) return listOf() else return text .lines() .map { it.trim() } .filterNot { it.isEmpty() } } } enum class GruntExecutionMode(val title : String, val value : String) { NPM("NPM package from project", "npm"), GLOBAL("System-wide grunt", "global"), }
60
null
51
306
9ef42088b96dad0d1e721dafedf394d8f4bad124
1,758
TeamCity.Node
Apache License 2.0
ui/src/main/kotlin/com/mephistolie/compost/ui/textfields/TextField.kt
mephistolie
529,561,862
false
{"Kotlin": 69974, "Shell": 330}
package com.mephistolie.compost.ui.textfields import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.LocalTextStyle import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.material.TextFieldColors import androidx.compose.material.TextFieldDefaults import androidx.compose.material.Typography import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.VisualTransformation import com.mephistolie.compost.ui.UiDefaults.SINGLE_LINE /** * Analogue of standard TextField with more freedom. Instead of original it has modifiable paddings * and doesn't apply background, minimum size and indicator line modifiers. You can add them by pass * suitable modifier by default. Also singleLine argument reduced to maxLines. * * @param value the input text to be shown in the text field * @param onValueChange the callback that is triggered when the input service updates the text. An * updated text comes as a parameter of the callback * @param modifier a [Modifier] for this text field * @param enabled controls the enabled state of the [TextField]. When `false`, the text field will * be neither editable nor focusable, the input of the text field will not be selectable, * visually text field will appear in the disabled UI state * @param readOnly controls the editable state of the [TextField]. When `true`, the text * field can not be modified, however, a user can focus it and copy text from it. Read-only text * fields are usually used to display pre-filled forms that user can not edit * @param textStyle the style to be applied to the input text. The default [textStyle] uses the * [LocalTextStyle] defined by the theme * @param cursorBrush the brush to be applied to cursor * @param label the optional label to be displayed inside the text field container. The default * text style for internal [Text] is [Typography.caption] when the text field is in focus and * [Typography.subtitle1] when the text field is not in focus * @param placeholder the optional placeholder to be displayed when the text field is in focus and * the input text is empty. The default text style for internal [Text] is [Typography.subtitle1] * @param leadingIcon the optional leading icon to be displayed at the beginning of the text field * container * @param trailingIcon the optional trailing icon to be displayed at the end of the text field * container * @param isError indicates if the text field's current value is in error. If set to true, the * label, bottom indicator and trailing icon by default will be displayed in error color * @param visualTransformation transforms the visual representation of the input [value] * For example, you can use * [PasswordVisualTransformation][androidx.compose.ui.text.input.PasswordVisualTransformation] to * create a password text field. By default no visual transformation is applied * @param keyboardOptions software keyboard options that contains configuration such as * [KeyboardType] and [ImeAction]. * @param keyboardActions when the input service emits an IME action, the corresponding callback * is called. Note that this IME action may be different from what you specified in * [KeyboardOptions.imeAction]. * @param maxLines the maximum height in terms of maximum number of visible lines. Should be * equal or greater than 1. * @param interactionSource the [MutableInteractionSource] representing the stream of * [Interaction]s for this TextField. You can create and pass in your own remembered * [MutableInteractionSource] if you want to observe [Interaction]s and customize the * appearance / behavior of this TextField in different [Interaction]s. * @param colors [TextFieldColors] that will be used to resolve color of the text, content * (including label, placeholder, leading and trailing icons, indicator line) and background for * this text field in different states. See [TextFieldDefaults.textFieldColors] * @param contentPadding [PaddingValues] that will be applied to actual text area */ @OptIn(ExperimentalMaterialApi::class) @Composable fun TextField( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = LocalTextStyle.current, cursorBrush: Brush = SolidColor(Color.Black), label: @Composable (() -> Unit)? = null, placeholder: @Composable (() -> Unit)? = null, leadingIcon: @Composable (() -> Unit)? = null, trailingIcon: @Composable (() -> Unit)? = null, isError: Boolean = false, visualTransformation: VisualTransformation = VisualTransformation.None, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions(), maxLines: Int = Int.MAX_VALUE, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, colors: TextFieldColors = TextFieldDefaults.textFieldColors(), contentPadding: PaddingValues = if (label == null) { TextFieldDefaults.textFieldWithoutLabelPadding() } else { TextFieldDefaults.textFieldWithLabelPadding() }, ) { val textColor = textStyle.color.takeOrElse { colors.textColor(enabled).value } val mergedTextStyle = textStyle.merge(TextStyle(color = textColor)) BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier, enabled = enabled, readOnly = readOnly, textStyle = mergedTextStyle, cursorBrush = cursorBrush, visualTransformation = visualTransformation, keyboardOptions = keyboardOptions, keyboardActions = keyboardActions, interactionSource = interactionSource, singleLine = maxLines == 1, maxLines = maxLines, decorationBox = @Composable { innerTextField -> TextFieldDefaults.TextFieldDecorationBox( value = value, visualTransformation = visualTransformation, innerTextField = innerTextField, placeholder = placeholder, label = label, leadingIcon = leadingIcon, trailingIcon = trailingIcon, singleLine = maxLines == SINGLE_LINE, enabled = enabled, isError = isError, interactionSource = interactionSource, colors = colors, contentPadding = contentPadding ) } ) }
0
Kotlin
0
15
2c2becb815a4d108db271d15c5aa4bb65add639a
7,337
compost
MIT License
android/src/main/java/com/audienzzrn/RCTOriginalInterstitialView.kt
audienzz
756,759,703
false
{"Kotlin": 82981, "Objective-C": 74969, "TypeScript": 54280, "Ruby": 3820, "JavaScript": 2122, "Objective-C++": 817, "C": 103}
package com.audienzz /* Copyright 2024 Audienzz AG 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. */ import android.content.Context import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.ReactContext import com.facebook.react.bridge.WritableMap import com.facebook.react.uimanager.events.RCTEventEmitter import com.google.android.gms.ads.AdError import com.google.android.gms.ads.FullScreenContentCallback import com.google.android.gms.ads.LoadAdError import com.google.android.gms.ads.admanager.AdManagerInterstitialAd import com.google.android.gms.ads.admanager.AdManagerInterstitialAdLoadCallback import com.google.android.gms.ads.interstitial.InterstitialAd import org.audienzz.mobile.AudienzzInterstitialAdUnit import org.audienzz.mobile.original.AudienzzInterstitialAdHandler import org.audienzz.mobile.util.lazyLoadAd class RCTOriginalInterstitialView(context: Context) : RCTOriginalView(context) { private var minSizesPercentage: List<Int> = listOf() private var auInterstitialView: AudienzzInterstitialAdUnit? = null private var mInterstitialAd: InterstitialAd? = null fun handleAdLoaded() { (context as ReactContext).getJSModule(RCTEventEmitter::class.java) .receiveEvent(id, "onAdLoaded", null) } fun handleAdFailedToLoad(loadError: LoadAdError) { val error: WritableMap = Arguments.createMap() error.putInt("code", loadError.code) error.putString("message", loadError.message) (context as ReactContext).getJSModule(RCTEventEmitter::class.java) .receiveEvent(id, "onAdFailedToLoad", error) } fun handleAdClicked() { (context as ReactContext).getJSModule(RCTEventEmitter::class.java) .receiveEvent(id, "onAdClicked", null) } fun handleAdOpened() { (context as ReactContext).getJSModule(RCTEventEmitter::class.java) .receiveEvent(id, "onAdOpened", null) } fun handleAdClosed() { (context as ReactContext).getJSModule(RCTEventEmitter::class.java) .receiveEvent(id, "onAdClosed", null) } override fun createAd() { super.createAd() auInterstitialView = AudienzzInterstitialAdUnit( auConfigID, AudienzzConversionUtils.convertToAudienzzAdFormats(adFormats) ) val handler = AudienzzInterstitialAdHandler( auInterstitialView!!, adUnitID, ) var interstitial: AdManagerInterstitialAd? = null if (pbAdSlot != null) { auInterstitialView?.pbAdSlot = pbAdSlot } if (gpID != null) { auInterstitialView?.gpid = gpID } if (keyword != null) { auInterstitialView?.addExtKeyword(keyword!!) } if (keywords != null) { auInterstitialView?.addExtKeywords(keywords!!) } if (appContent != null) { auInterstitialView?.appContent = appContent } auInterstitialView?.bannerParameters = bannerParameters auInterstitialView?.videoParameters = videoParameters auInterstitialView?.setMinSizePercentage(minSizesPercentage[0], minSizesPercentage[1]) this.lazyLoadAd( adHandler = handler, listener = object : AdManagerInterstitialAdLoadCallback() { override fun onAdLoaded(interstitialAd: AdManagerInterstitialAd) { val activity = (context as? ReactContext)?.currentActivity interstitial = interstitialAd mInterstitialAd = interstitialAd mInterstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback() { override fun onAdClicked() { handleAdClicked() } override fun onAdDismissedFullScreenContent() { handleAdClosed() mInterstitialAd = null } override fun onAdFailedToShowFullScreenContent(p0: AdError) { mInterstitialAd = null } override fun onAdImpression() {} override fun onAdShowedFullScreenContent() { handleAdOpened() } } handleAdLoaded() if (activity != null) { interstitial!!.show(activity) } } override fun onAdFailedToLoad(loadAdError: LoadAdError) { handleAdFailedToLoad(loadAdError) } }, resultCallback = {} ) } fun updateMinSizesPercentage(value: List<Int>) { minSizesPercentage = value; } }
0
Kotlin
0
0
e47b568680b339c51b137bda901cb86fffbeef29
4,832
audienzz-rn-sdk
Apache License 2.0
src/Main.kt
cjfuller
442,845,718
false
{"Kotlin": 34397}
package kargo import kotlinx.cli.ArgParser import kotlinx.cli.ArgType import kotlinx.cli.ExperimentalCli import kotlinx.cli.Subcommand import kotlin.io.path.Path @ExperimentalCli fun main(args: Array<String>) { val parser = ArgParser("kargo") class Init : Subcommand("init", "Required first-time setup") { override fun execute() { kargo.commands.Init.run() } } class Lock : Subcommand("lock", "Lock dependencies") { override fun execute() { kargo.commands.Lock.run() } } class Build : Subcommand("build", "Build the project") { override fun execute() { kargo.commands.Build.run() } } class Deps : Subcommand("deps", "Fetch and vendor dependencies from lockfile") { override fun execute() { kargo.commands.Deps.run() } } class Fmt : Subcommand("fmt", "Format kotlin sources using ktlint") { override fun execute() { kargo.commands.Fmt.run() } } class Lint : Subcommand("lint", "Lint kotlin sources using ktlint") { override fun execute() { kargo.commands.Lint.run() } } class Assemble : Subcommand("assemble", "Assemble a fat jar with all deps included") { override fun execute() { kargo.commands.Assemble.run() } } class Run(val moreArgs: List<String>) : Subcommand("run", "Run the jar produced by `build` or the supplied script") { val script: String? by parser.option(ArgType.String, shortName = "s", description = "Script file to run") override fun execute() { kargo.commands.Run(script = script?.let { Path(it) }, runArgs = moreArgs).run() } } class Test : Subcommand("test", "Run tests using JUnit") { override fun execute() { kargo.commands.Test.run() } } val nativeImageDesc = ( "Build a native image using GraalVM for the current OS. You must already have " + "a working install of GraalVM, including the native-image tool, for this to work." ) class GraalNativeImage : Subcommand("native-image", nativeImageDesc) { override fun execute() { kargo.commands.GraalNativeImage.run() } } val argsForParser = args.takeWhile { it != "--" } val argsToPassOn = args.dropWhile { it != "--" }.dropWhile { it == "--" } parser.subcommands(Build(), Init(), Lock(), Deps(), Fmt(), Lint(), Assemble(), GraalNativeImage(), Run(argsToPassOn), Test()) parser.parse(argsForParser.toTypedArray()) }
1
Kotlin
0
1
d622c90c603b7eaa88cb5039cb5b70be6b9309dc
2,621
kargo
Apache License 2.0
kt-api/src/main/kotlin/com/firebase/wrapper/admin/firestore/QueryDocumentSnapshot.kt
xebia-france
150,782,121
false
null
package com.firebase.wrapper.admin.firestore import com.firebase.wrapper.admin.firestore.DocumentSnapshot external interface QueryDocumentSnapshot : DocumentSnapshot
0
Kotlin
0
2
7042e20f5f1bb75f3542a4433b195f5ba2a5b1f3
168
mdk-kotlinjs
Apache License 2.0
src/test/kotlin/FetchTransactionAddressTest.kt
rench
130,037,838
false
{"CSS": 859461, "HTML": 42906, "Kotlin": 26453, "JavaScript": 6782}
import com.alibaba.fastjson.JSON import com.github.rench.ddw.rpc.RpcApi.web3j import com.sun.xml.internal.ws.util.CompletedFuture import org.junit.Test import org.web3j.protocol.Web3j import org.web3j.protocol.core.DefaultBlockParameter import org.web3j.protocol.core.DefaultBlockParameterName import org.web3j.protocol.http.HttpService import org.web3j.utils.Convert import java.math.BigDecimal import java.math.BigInteger import java.util.concurrent.* class FetchTransactionAddressTest { val map: MutableMap<String, BigDecimal> = ConcurrentHashMap() val pool: ExecutorService = Executors.newFixedThreadPool(200) val web3j: Web3j = Web3j.build(HttpService("http://localhost:8200")) @Test fun testFetch() { var currentBlockNum: Long = web3j.ethBlockNumber().send().blockNumber.longValueExact() var fs = mutableListOf<CompletableFuture<Boolean>>() for (i in 1..currentBlockNum) { var txCount = web3j.ethGetBlockTransactionCountByNumber(DefaultBlockParameter.valueOf(BigInteger.valueOf(i))).send().transactionCount.longValueExact() if (txCount != 0L) { (0 until txCount).mapTo(fs) { CompletableFuture.supplyAsync { var tx = web3j.ethGetTransactionByBlockNumberAndIndex( DefaultBlockParameter.valueOf(BigInteger.valueOf(i)), BigInteger.valueOf(it) ).send().transaction println("from ${tx.get()?.from} to ${tx.get()?.to} value ${Convert.fromWei(tx.get().value.toString(), Convert.Unit.ETHER)} in block ${tx.get().blockNumber}") if (tx.get().from!=null && !map.containsKey(tx.get().from)) { map[tx.get()?.from] = BigDecimal.ZERO } if (tx.get().to != null && !map.containsKey(tx.get().to)) { map[tx.get().to] = BigDecimal.ZERO } else { println(JSON.toJSONString(tx.get())) } true } } } Thread.yield() } val allOf = CompletableFuture.allOf(*fs.toTypedArray()) allOf.join() val countDown = CountDownLatch(map.keys.size) for (k in map.keys) { pool.execute { map[k] = web3j.ethGetBalance(k, DefaultBlockParameterName.PENDING).send().balance.toBigDecimal() countDown.countDown() } } countDown.await() for ((k, v) in map) { println("address:$k balance:${Convert.fromWei(v, Convert.Unit.ETHER)}") } } }
0
CSS
0
4
4a5f4e6cb9a54cc13653394cb29dde06748690ec
2,765
phi-ddw
MIT License
src/main/kotlin/io/kanro/idea/plugin/protobuf/aip/reference/contributor/AipReferenceContributor.kt
yuxin-zhao
359,704,598
true
{"Kotlin": 311223, "Lex": 6288, "Java": 730}
package io.kanro.idea.plugin.protobuf.aip.reference.contributor import com.intellij.patterns.PlatformPatterns import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.PsiReferenceContributor import com.intellij.psi.PsiReferenceProvider import com.intellij.psi.PsiReferenceRegistrar import com.intellij.psi.util.parentOfType import com.intellij.util.ProcessingContext import io.kanro.idea.plugin.protobuf.aip.AipOptions import io.kanro.idea.plugin.protobuf.aip.reference.AipResourceReference import io.kanro.idea.plugin.protobuf.aip.reference.ProtobufRpcInputFieldReference import io.kanro.idea.plugin.protobuf.aip.reference.ProtobufRpcOutputFieldReference import io.kanro.idea.plugin.protobuf.aip.reference.ProtobufTypeNameInStringReference import io.kanro.idea.plugin.protobuf.lang.psi.ProtobufFieldDefinition import io.kanro.idea.plugin.protobuf.lang.psi.ProtobufOptionAssign import io.kanro.idea.plugin.protobuf.lang.psi.ProtobufRpcDefinition import io.kanro.idea.plugin.protobuf.lang.psi.ProtobufStringValue import io.kanro.idea.plugin.protobuf.lang.psi.primitive.stratify.ProtobufOptionHover import io.kanro.idea.plugin.protobuf.lang.psi.primitive.structure.ProtobufValueAssign import io.kanro.idea.plugin.protobuf.lang.psi.value import io.kanro.idea.plugin.protobuf.string.splitToRange import io.kanro.idea.plugin.protobuf.string.trim class AipReferenceContributor : PsiReferenceContributor() { override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) { registrar.registerReferenceProvider( PlatformPatterns.psiElement(ProtobufStringValue::class.java) .inside(ProtobufFieldDefinition::class.java) .inside(ProtobufOptionAssign::class.java), AipResourceReferenceProvider() ) registrar.registerReferenceProvider( PlatformPatterns.psiElement(ProtobufStringValue::class.java) .inside(ProtobufRpcDefinition::class.java) .inside(ProtobufOptionAssign::class.java), AipFieldReferenceProvider() ) registrar.registerReferenceProvider( PlatformPatterns.psiElement(ProtobufStringValue::class.java) .inside(ProtobufRpcDefinition::class.java) .inside(ProtobufOptionAssign::class.java), AipTypeNameReferenceProvider() ) } } class AipResourceReferenceProvider : PsiReferenceProvider() { override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> { val stringValue = element as? ProtobufStringValue ?: return arrayOf() val reference = getReference(stringValue) ?: return arrayOf() return arrayOf(reference) } private fun getReference(element: ProtobufStringValue): PsiReference? { val hover = element.parentOfType<ProtobufOptionHover>() ?: return null if (!hover.isOption(AipOptions.resourceReferenceOption)) return null if (hover.value(AipOptions.resourceTypeField)?.stringValue == element) return AipResourceReference(element) if (hover.value(AipOptions.resourceChildTypeField)?.stringValue == element) return AipResourceReference(element) return null } } class AipFieldReferenceProvider : PsiReferenceProvider() { override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> { val stringValue = element as? ProtobufStringValue ?: return arrayOf() val reference = getReference(stringValue) ?: return arrayOf() return arrayOf(reference) } private fun getReference(element: ProtobufStringValue): PsiReference? { if (element.textMatches("\"*\"")) return null val assign = element.parentOfType<ProtobufValueAssign>() ?: return null val targetField = assign.field()?.qualifiedName() if (targetField == AipOptions.httpRuleBodyName) return ProtobufRpcInputFieldReference(element) if (targetField == AipOptions.httpRuleResponseBodyName) return ProtobufRpcOutputFieldReference(element) return null } } class AipTypeNameReferenceProvider : PsiReferenceProvider() { override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> { if (element !is ProtobufStringValue) return arrayOf() val assign = element.parentOfType<ProtobufValueAssign>() ?: return arrayOf() val targetField = assign.field()?.qualifiedName() if (targetField == AipOptions.lroMetadataName) return getReference(element) if (targetField == AipOptions.lroResponseName) return getReference(element) return arrayOf() } private fun getReference(element: ProtobufStringValue): Array<PsiReference> { val text = element.text val ranges = text.splitToRange('.', true) var reference: ProtobufTypeNameInStringReference? = null return ranges.asReversed().map { ProtobufTypeNameInStringReference( element, it.trim(text, '"'), reference ).apply { reference = this } }.toTypedArray() } }
0
null
0
0
43fd148d80b7d11c17b12fb2be7df5b1fd68dba4
5,185
intellij-protobuf-plugin
Apache License 2.0
core/src/main/java/kekmech/ru/core/dto/NoteNative.kt
NuvaltsevAA
249,189,732
true
{"Kotlin": 355287, "Shell": 46}
package kekmech.ru.core.dto import androidx.room.* import com.google.gson.annotations.SerializedName import org.jetbrains.annotations.NotNull @Entity( tableName = "notes", indices = [Index( value = ["id"], unique = true )] ) data class NoteNative( @ColumnInfo(name = "couple_id") var scheduleId: Int, @ColumnInfo(name = "timestamp") var timestamp: String, @ColumnInfo(name = "data") var data: String, @ColumnInfo(name = "tag") var tag: String ) { @PrimaryKey(autoGenerate = true) @NotNull var id: Int = 0 data class Note( @SerializedName("t") var text: String = "", @SerializedName("w") var weekNum: Int = 0, @SerializedName("d") var dayNum: Int = 0, @SerializedName("c") var coupleNum: Int = 0 ) }
0
null
0
0
94bd394725e495a13f818e94f674a5353dd29bcb
849
mpeiapp
MIT License
app/src/main/kotlin/batect/config/ImageSource.kt
Tzrlk
281,249,203
true
{"Kotlin": 2896181, "Python": 25357, "Groovy": 22956, "Shell": 19774, "PowerShell": 6999, "Dockerfile": 5707, "Batchfile": 3162, "Java": 1310, "HTML": 500}
/* Copyright 2017-2020 Charles Korn. 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 batect.config import java.nio.file.Path import kotlinx.serialization.Serializable sealed class ImageSource data class BuildImage( val buildDirectory: Expression, val relativeTo: Path, val buildArgs: Map<String, Expression> = emptyMap(), val dockerfilePath: String = "Dockerfile" ) : ImageSource() @Serializable data class PullImage(val imageName: String) : ImageSource()
0
null
0
0
b1321a0acbd2ba896c3024801d509259d96bfa6d
995
batect
Apache License 2.0
app/src/androidTest/java/net/skyscanner/backpack/button/BpkButtonTest.kt
Skyscanner
117,813,847
false
null
/** * Backpack for Android - Skyscanner's Design System * * Copyright 2018 Skyscanner 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 net.skyscanner.backpack.button import android.view.View import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.IntSize import androidx.compose.ui.viewinterop.AndroidView import net.skyscanner.backpack.BpkSnapshotTest import net.skyscanner.backpack.BpkTestVariant import net.skyscanner.backpack.compose.tokens.BpkColor import net.skyscanner.backpack.compose.tokens.BpkSpacing import net.skyscanner.backpack.demo.R import org.junit.Assume.assumeTrue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class BpkButtonTest(flavour: Flavor) : BpkSnapshotTest() { private val type: BpkButton.Type = flavour.first private val size: BpkButton.Size = flavour.second private val icon get() = testContext.getDrawable( when (size) { BpkButton.Size.Standard -> R.drawable.bpk_long_arrow_right_sm BpkButton.Size.Large -> R.drawable.bpk_long_arrow_right } ) @Test fun text() { assumeVariant(BpkTestVariant.Default, BpkTestVariant.DarkMode, BpkTestVariant.Themed) // no need to test text on Rtl // we want to see colors of all types // different sizes have different text style capture(background = type.rowBackground()) { BpkButton(testContext, type, size).apply { text = "Button" } } } @Test fun disabled() { assumeVariant(BpkTestVariant.Default, BpkTestVariant.DarkMode) // we're testing just colors here – no rtl is needed // disabled/loading colors are not theme customisable assumeTrue(size == BpkButton.Size.Standard) // colors will be the same on large size capture(background = type.rowBackground()) { BpkButton(testContext, type, size).apply { text = "Button" isEnabled = false } } } @Test fun loading() { assumeVariant(BpkTestVariant.Default, BpkTestVariant.DarkMode) // we're testing just colors here – no rtl is needed // disabled/loading colors are not theme customisable // we need to run it on large size as well and the progress size will be different capture(background = type.rowBackground()) { BpkButton(testContext, type, size).apply { text = "Button" loading = true } } } @Test fun loadingWithIcon() { assumeVariant(BpkTestVariant.Default, BpkTestVariant.Rtl) // this just tests layout, so RTL is required assumeTrue(type == BpkButton.Type.Primary) // colors will be the same on all loading buttons // we need to run it on large size as well and the progress size will be different capture { BpkButton(testContext, type, size).apply { text = "Button" icon = this@BpkButtonTest.icon iconPosition = BpkButton.START loading = true } } } @Test fun loadingWithIconOnly() { assumeVariant(BpkTestVariant.Default, BpkTestVariant.Rtl) // this just tests layout, so RTL is required assumeTrue(type == BpkButton.Type.Primary) // colors will be the same on all loading buttons // we need to run it on large size as well and the progress size will be different capture { BpkButton(testContext, type, size).apply { icon = this@BpkButtonTest.icon iconPosition = BpkButton.ICON_ONLY loading = true } } } @Test fun iconAtStart() { assumeVariant(BpkTestVariant.Default, BpkTestVariant.Rtl) // this just tests layout, so RTL is required assumeTrue(type == BpkButton.Type.Primary) // the layout the same across different button types // icon is bigger on large size, so we need to test this capture { BpkButton(testContext, type, size).apply { text = "Button" icon = this@BpkButtonTest.icon iconPosition = BpkButton.START } } } @Test fun iconAtEnd() { assumeVariant(BpkTestVariant.Default, BpkTestVariant.Rtl) // this just tests layout, so RTL is required assumeTrue(type == BpkButton.Type.Primary) // the layout the same across different button types // icon is bigger on large size, so we need to test this capture { BpkButton(testContext, type, size).apply { text = "Button" icon = this@BpkButtonTest.icon iconPosition = BpkButton.END } } } @Test fun iconOnly() { assumeVariant(BpkTestVariant.Default) // since its only icon, RTL doesn't matter assumeTrue(type == BpkButton.Type.Primary) // the layout the same across different button types // icon is bigger on large size, so we need to test this capture { BpkButton(testContext, type, size).apply { icon = this@BpkButtonTest.icon iconPosition = BpkButton.ICON_ONLY } } } private fun capture(background: Color = Color.Unspecified, content: () -> View) { composed( size = IntSize(160, 64), tags = listOf(type, size), ) { Box( Modifier .fillMaxSize() .background(background) .padding(BpkSpacing.Md), contentAlignment = Alignment.TopStart ) { AndroidView(factory = { content() }) } } } companion object { @JvmStatic @Parameterized.Parameters(name = "{0} Screenshot") fun flavours(): List<Flavor> = BpkButton.Type.values().flatMap { type -> BpkButton.Size.values().map { size -> Flavor(type, size) } } } } private typealias Flavor = Pair<BpkButton.Type, BpkButton.Size> private fun BpkButton.Type.rowBackground() = when (this) { BpkButton.Type.SecondaryOnDark, BpkButton.Type.PrimaryOnDark, BpkButton.Type.LinkOnDark -> BpkColor.SkyGray BpkButton.Type.PrimaryOnLight -> Color.White else -> Color.Unspecified }
7
Kotlin
22
62
160a3d32ba223295498a09c86f38f5b2bc46aa89
6,642
backpack-android
Apache License 2.0
model-d-control-core/src/test/kotlin/nl/breun/model_d/core/ModelDTest.kt
breun
92,437,248
false
{"Kotlin": 32029, "Shell": 7272, "Batchfile": 5127}
package nl.breun.model_d.core import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import io.github.benas.randombeans.api.EnhancedRandom.random import nl.breun.model_d.core.parameter.* import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.assertj.core.description.TextDescription import org.junit.Before import org.junit.Test import javax.sound.midi.MidiDevice import javax.sound.midi.Receiver import javax.sound.midi.ShortMessage import javax.sound.midi.SysexMessage class ModelDTest { private val modelD: ModelD private var deviceId: DeviceId private var lastMessage: SysexMessage? = null init { val r: Receiver = mock { on { send(any(), any()) }.doAnswer { lastMessage = it.getArgument(0) Unit } } val midiOut: MidiDevice = mock { on { receiver }.doReturn(r) } deviceId = random(DeviceId::class.java) modelD = ModelD(midiOut, deviceId) } @Before fun setup() { lastMessage = null } @Test fun `Set device ID to 0`() { modelD.setDeviceId(DeviceId._0) assertGlobalParameterMessage(0, 0, 0) } @Test fun `Set device ID to 15`() { modelD.setDeviceId(DeviceId._15) assertGlobalParameterMessage(0, 0, 15) } @Test fun `Set device ID to ALL`() { modelD.setDeviceId(DeviceId.ALL) assertGlobalParameterMessage(0, 0, 127) } @Test fun `Set MIDI channel in to 1`() { modelD.setMidiChannelIn(MidiChannel._1) assertGlobalParameterMessage(1, 0, 0) } @Test fun `Set MIDI channel in to 16`() { modelD.setMidiChannelIn(MidiChannel._16) assertGlobalParameterMessage(1, 0, 15) } @Test fun `Set MIDI channel out to 1`() { modelD.setMidiChannelOut(MidiChannel._1) assertGlobalParameterMessage(2, 0, 0) } @Test fun `Set MIDI channel out to 16`() { modelD.setMidiChannelOut(MidiChannel._16) assertGlobalParameterMessage(2, 0, 15) } @Test fun `Set key priority to lowest key`() { modelD.setKeyPriority(KeyPriority.LOW) assertGlobalParameterMessage(3, 0, 0) } @Test fun `Set key priority to last key`() { modelD.setKeyPriority(KeyPriority.LAST) assertGlobalParameterMessage(3, 0, 1) } @Test fun `Set key priority to highest key`() { modelD.setKeyPriority(KeyPriority.HIGH) assertGlobalParameterMessage(3, 0, 2) } @Test fun `Disable multi-trigger`() { modelD.setMultiTrigger(Status.OFF) assertGlobalParameterMessage(4, 0, 0) } @Test fun `Enable multi-trigger`() { modelD.setMultiTrigger(Status.ON) assertGlobalParameterMessage(4, 0, 1) } @Test fun `Set bend to 0 semitones`() { modelD.setBendSemitones(9) assertGlobalParameterMessage(5, 0, 9) } @Test fun `Set bend to 12 semitones`() { modelD.setBendSemitones(12) assertGlobalParameterMessage(5, 0, 12) } @Test fun `Throw exception when trying to set ben semitones to -1`() { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { modelD.setBendSemitones(-1) } .withMessage("bend semitones: [0, 12]") } @Test fun `Throw exception when trying to set ben semitones to 13`() { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { modelD.setBendSemitones(13) } .withMessage("bend semitones: [0, 12]") } @Test fun `Disable output MIDI pitch bend`() { modelD.setOutputMidiPitchBend(Status.OFF) assertGlobalParameterMessage(8, 0, 0) } @Test fun `Enable output MIDI pitch bend`() { modelD.setOutputMidiPitchBend(Status.ON) assertGlobalParameterMessage(8, 0, 1) } @Test fun `Disable output MIDI pressure`() { modelD.setOutputMidiPressure(Status.OFF) assertGlobalParameterMessage(9, 0, 0) } @Test fun `Enable output MIDI pressure`() { modelD.setOutputMidiPressure(Status.ON) assertGlobalParameterMessage(9, 0, 1) } @Test fun `Set gate trigger sources to external only`() { modelD.setGateTriggerSources(GateTriggerSources.EXTERNAL) assertGlobalParameterMessage(10, 0, 0) } @Test fun `Set gate trigger sources to external and local only`() { modelD.setGateTriggerSources(GateTriggerSources.EXTERNAL_AND_LOCAL) assertGlobalParameterMessage(10, 0, 1) } @Test fun `Set gate trigger sources to external and MIDI only`() { modelD.setGateTriggerSources(GateTriggerSources.EXTERNAL_AND_MIDI) assertGlobalParameterMessage(10, 0, 2) } @Test fun `Set gate trigger sources to external, local and MIDI`() { modelD.setGateTriggerSources(GateTriggerSources.EXTERNAL_AND_LOCAL_AND_MIDI) assertGlobalParameterMessage(10, 0, 3) } @Test fun `Disable tuning error`() { modelD.setTuningError(Status.OFF) assertGlobalParameterMessage(11, 0, 0) } @Test fun `Enable tuning error`() { modelD.setTuningError(Status.ON) assertGlobalParameterMessage(11, 0, 1) } @Test fun `Set tuning variance to 0 cents`() { modelD.setTuningVariance(0.0) assertGlobalParameterMessage(12, 0, 0) } @Test fun `Set tuning variance to 50 cents`() { modelD.setTuningVariance(50.0) assertGlobalParameterMessage(12, 3, 116) } @Test fun `Throw exception when trying to set negative tuning variance`() { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { modelD.setTuningVariance(-0.1) } .withMessage("cents: [0.0, 50.0]") } @Test fun `Throw exception when trying to set tuning variance higher than 50 cents`() { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { modelD.setTuningVariance(50.1) } .withMessage("cents: [0.0, 50.0]") } @Test fun `Set tuning program to twelve tone equal temparament`() { modelD.setTuningProgram(TuningProgram.TWELVE_TONE_EQUAL_TEMPERAMENT) assertGlobalParameterMessage(13, 0, 0) } @Test fun `Set tuning program to custom MIDI 1`() { modelD.setTuningProgram(TuningProgram.CUSTOM_MIDI_1) assertGlobalParameterMessage(13, 0, 1) } @Test fun `Set tuning program to custom MIDI 2`() { modelD.setTuningProgram(TuningProgram.CUSTOM_MIDI_2) assertGlobalParameterMessage(13, 0, 2) } @Test fun `Set tuning program to custom MIDI 3`() { modelD.setTuningProgram(TuningProgram.CUSTOM_MIDI_3) assertGlobalParameterMessage(13, 0, 3) } @Test fun `Set velocity curve to soft`() { modelD.setVelocityCurve(VelocityCurve.SOFT) assertGlobalParameterMessage(14, 0, 0) } @Test fun `Set velocity curve to medium`() { modelD.setVelocityCurve(VelocityCurve.MEDIUM) assertGlobalParameterMessage(14, 0, 1) } @Test fun `Set velocity curve to hard`() { modelD.setVelocityCurve(VelocityCurve.HARD) assertGlobalParameterMessage(14, 0, 2) } @Test fun `Set MIDI in transpose to -12 semitones`() { modelD.setMidiInTranspose(-12) assertGlobalParameterMessage(15, 0, 0) } @Test fun `Set MIDI in transpose to 0 semitones`() { modelD.setMidiInTranspose(0) assertGlobalParameterMessage(15, 0, 12) } @Test fun `Set MIDI in transpose to +12 semitones`() { modelD.setMidiInTranspose(12) assertGlobalParameterMessage(15, 0, 24) } @Test fun `Throw exception when trying to set MIDI in transpose lower than -12 semitones`() { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { modelD.setMidiInTranspose(-13) } .withMessage("transpose semitones: [-12, 12]") } @Test fun `Throw exception when trying to set MIDI in transpose higher than +12 semitones`() { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { modelD.setMidiInTranspose(13) } .withMessage("transpose semitones: [-12, 12]") } @Test fun `Set MIDI out transpose to -12 semitones`() { modelD.setMidiOutTranspose(-12) assertGlobalParameterMessage(16, 0, 0) } @Test fun `Set MIDI out transpose to 0 semitones`() { modelD.setMidiOutTranspose(0) assertGlobalParameterMessage(16, 0, 12) } @Test fun `Set MIDI out transpose to +12 semitones`() { modelD.setMidiOutTranspose(12) assertGlobalParameterMessage(16, 0, 24) } @Test fun `Throw exception when trying to set MIDI out transpose lower than -12 semitones`() { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { modelD.setMidiOutTranspose(-13) } .withMessage("transpose semitones: [-12, 12]") } @Test fun `Throw exception when trying to set MIDI out transpose higher than +12 semitones`() { assertThatExceptionOfType(IllegalArgumentException::class.java) .isThrownBy { modelD.setMidiOutTranspose(13) } .withMessage("transpose semitones: [-12, 12]") } @Test fun `Set pressure CV range to +5 volts`() { modelD.setPressureCVRange(PressureCVRange.PLUS_FIVE_VOLTS) assertGlobalParameterMessage(17, 0, 0) } @Test fun `Set pressure CV range to +10 volts`() { modelD.setPressureCVRange(PressureCVRange.PLUS_TEN_VOLTS) assertGlobalParameterMessage(17, 0, 1) } @Test fun `Set MIDI note 0 volts to C0 (MIDI note 0)`() { modelD.setMidiNoteZeroVolts(MidiNote(0)) assertGlobalParameterMessage(18, 0, 0) } @Test fun `Set MIDI note 0 volts to G10 (MIDI note 127)`() { modelD.setMidiNoteZeroVolts(MidiNote(127)) assertGlobalParameterMessage(18, 0, 127) } @Test fun `Disable local control`() { modelD.setLocalControl(Status.OFF) assertGlobalParameterMessage(19, 0, 0) } @Test fun `Enable local control`() { modelD.setLocalControl(Status.ON) assertGlobalParameterMessage(19, 0, 1) } private fun assertGlobalParameterMessage( expectedGlobalParameterNumber: Int, expectedMSB: Int, expectedLSB: Int ) { assertThat(lastMessage).isNotNull() val bytes = lastMessage!!.message assertGlobalParameterMessageBytes(bytes) assertDeviceId(bytes) assertGlobalParameterNumber(expectedGlobalParameterNumber.toByte(), bytes) assertMSB(expectedMSB.toByte(), bytes) assertLSB(expectedLSB.toByte(), bytes) } private fun assertGlobalParameterMessageBytes(bytes: ByteArray) { assertThat(bytes[0]) .describedAs(TextDescription("First byte (status byte, constant)")) .isEqualTo(SysexMessage.SYSTEM_EXCLUSIVE.toByte()) assertThat(bytes[1]) .describedAs(TextDescription("Second byte (constant)")) .isEqualTo(0x04.toByte()) assertThat(bytes[2]) .describedAs(TextDescription("Third byte (constant)")) .isEqualTo(0x15.toByte()) assertThat(bytes[4]) .describedAs(TextDescription("Fifth byte (constant)")) .isEqualTo(0x14.toByte()) assertThat(bytes[8]) .describedAs(TextDescription("Ninth byte (end byte, constant)")) .isEqualTo(ShortMessage.END_OF_EXCLUSIVE.toByte()) } private fun assertDeviceId(bytes: ByteArray) { assertThat(bytes[3]) .describedAs(TextDescription("Device ID (fourth byte)")) .isEqualTo(deviceId.value.toByte()) } private fun assertGlobalParameterNumber(expectedGlobalParameterNumber: Byte, bytes: ByteArray) { assertThat(bytes[5]) .describedAs(TextDescription("Global parameter number (sixth byte)")) .isEqualTo(expectedGlobalParameterNumber) } private fun assertMSB(expectedMSB: Byte, bytes: ByteArray) { assertThat(bytes[6]) .describedAs(TextDescription("MSB (seventh byte)")) .isEqualTo(expectedMSB) } private fun assertLSB(expected: Byte, bytes: ByteArray) { assertThat(bytes[7]) .describedAs(TextDescription("LSB (eighth byte)")) .isEqualTo(expected) } }
0
Kotlin
0
0
e820e12b22bc2fbc5d8cfd9bae30ab1cea879bf1
13,054
model-d-control
Apache License 2.0
03/MasterDetail/app/src/main/java/com/lfg/masterdetail/fragments/ContainerFragment.kt
leonelgomez1990
402,218,277
false
null
package com.lfg.masterdetail.fragments import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayoutMediator import com.lfg.masterdetail.R import com.lfg.masterdetail.adapters.ViewPagerAdapter import com.lfg.masterdetail.viewmodels.ContainerViewModel class ContainerFragment : Fragment() { companion object { fun newInstance() = ContainerFragment() } private lateinit var viewModel: ContainerViewModel lateinit var v : View lateinit var viewPager: ViewPager2 lateinit var tabLayout: TabLayout override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { v = inflater.inflate(R.layout.container_fragment, container, false) viewPager = v.findViewById(R.id.view_pager) tabLayout = v.findViewById(R.id.tabLayout) return v } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this).get(ContainerViewModel::class.java) // TODO: Use the ViewModel } override fun onStart() { super.onStart() viewPager.setAdapter(ViewPagerAdapter(requireActivity())) // viewPager.isUserInputEnabled = false TabLayoutMediator(tabLayout, viewPager, TabLayoutMediator.TabConfigurationStrategy { tab, position -> when (position) { 0 -> tab.text = "Tab1" 1 -> tab.text = "Tab2" else -> tab.text = "undefined" } }).attach() } }
0
Kotlin
0
0
ce39f62befef83d53a3809411dbf60c2dcd410cc
1,868
kotlin1
MIT License
shared/src/commonMain/kotlin/dev/vengateshm/kmpudemycourseapp/articles/di/ArticlesModule.kt
vengateshm
767,983,517
false
{"Kotlin": 36800, "Swift": 6537}
package dev.vengateshm.kmpudemycourseapp.articles.di import dev.vengateshm.kmpudemycourseapp.articles.data.ArticleRepository import dev.vengateshm.kmpudemycourseapp.articles.data.ArticlesDataSource import dev.vengateshm.kmpudemycourseapp.articles.data.ArticlesService import dev.vengateshm.kmpudemycourseapp.articles.domain.ArticlesUseCase import dev.vengateshm.kmpudemycourseapp.articles.presentation.ArticlesViewModel import org.koin.dsl.module val articlesModule = module { single<ArticlesService> { ArticlesService(get()) } single<ArticlesUseCase> { ArticlesUseCase(get()) } single<ArticlesViewModel> { ArticlesViewModel(get(), get()) } single<ArticlesDataSource> { ArticlesDataSource(get()) } single<ArticleRepository> { ArticleRepository(get(), get()) } }
0
Kotlin
0
1
a6c1224efc9db820c8d99c3444e6e5cc35167497
783
KMP-Udemy-Course-Practice
Apache License 2.0
app/src/main/java/JandD/zinify/MainActivity.kt
KST-JD
422,671,215
false
null
package JandD.zinify import JandD.zinify.gallery.GalleryActivity import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.util.Log import android.view.MotionEvent import android.view.ScaleGestureDetector import android.widget.ImageButton import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.* import androidx.camera.lifecycle.ProcessCameraProvider import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import kotlinx.android.synthetic.main.activity_main.* import java.io.File import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class MainActivity : AppCompatActivity() { private var imageCapture: ImageCapture? = null private var photoTaken = false private lateinit var outputDirectory: File private lateinit var cameraExecutor: ExecutorService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Request camera permissions if (allPermissionsGranted()) { startCamera() } else { ActivityCompat.requestPermissions( this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS) } // gallery button listener findViewById<ImageButton>(R.id.gallery_button).setOnClickListener { val intent = Intent(this@MainActivity, GalleryActivity::class.java) startActivity(intent) } // upload button listener findViewById<ImageButton>(R.id.upload_button).setOnClickListener { pickExternalImg() } // take photo button listener val takePhoto = findViewById<ImageButton>(R.id.zinify_floating_btn) takePhoto.setOnClickListener { if (!photoTaken) { photoTaken = true takePhoto() } } outputDirectory = getOutputDirectory() cameraExecutor = Executors.newSingleThreadExecutor() } // Functions private fun takePhoto() { // Get a stable reference of the modifiable image capture use case val imageCapture = imageCapture ?: return // Create time-stamped output file to hold the image val photoFile = File( outputDirectory, "captured_temp.jpg") // Create output options object which contains file + metadata val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build() // Set up image capture listener, which is triggered after photo has been taken imageCapture.takePicture( outputOptions, ContextCompat.getMainExecutor(this), object : ImageCapture.OnImageSavedCallback { override fun onError(exc: ImageCaptureException) { Log.e(TAG, "Photo capture failed: ${exc.message}", exc) } override fun onImageSaved(output: ImageCapture.OutputFileResults) { val savedUri = Uri.fromFile(photoFile) // Go to img preview goToImagePreview(savedUri, 1) } }) } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener(Runnable { // Used to bind the lifecycle of cameras to the lifecycle owner val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get() // Preview val preview = Preview.Builder() .build() .also { it.setSurfaceProvider(camera_view.surfaceProvider) } imageCapture = ImageCapture.Builder() .build() // Select back camera as a default val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try { cameraProvider.unbindAll() cameraProvider.bindToLifecycle( this, cameraSelector, preview, imageCapture ) } catch (exc: Exception) { Log.e(TAG, "Use case binding failed", exc) } }, ContextCompat.getMainExecutor(this)) } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission( baseContext, it) == PackageManager.PERMISSION_GRANTED } private fun getOutputDirectory(): File { val mediaDir = externalMediaDirs.firstOrNull()?.let { File(it, resources.getString(R.string.app_name)).apply { mkdirs() } } return if (mediaDir != null && mediaDir.exists()) mediaDir else filesDir } private fun pickExternalImg() { val intentGallery = Intent(Intent.ACTION_PICK) intentGallery.type = "image/*" startActivityForResult(intentGallery, IMAGE_REQUEST_CODE)// NOTTODO za cholere nie moge tego zrobic bez tej funkcji } fun goToImagePreview(imageUri:Uri?, callerId: Int) { val intent = Intent(this, EditImageActivity::class.java) intent.data = imageUri // parse img uri to intent intent.putExtra("callerID",callerId) startActivity(intent) } override fun onResume() { super.onResume() photoTaken = false } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data)// TODO depricated function if(requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK) { intent.data = data?.data // parse img uri to intent goToImagePreview(intent.data, 3) } } override fun onDestroy() { super.onDestroy() cameraExecutor.shutdown() } companion object { private const val TAG = "CameraXBasic" private const val REQUEST_CODE_PERMISSIONS = 10 private const val IMAGE_REQUEST_CODE = 50 private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_CODE_PERMISSIONS) { if (allPermissionsGranted()) { startCamera() } else { Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show() finish() } } } }
0
Kotlin
0
0
5bacee7a04e781caa677f75f9079d2bf4d4fb082
7,112
Zinify
MIT License
library/src/main/java/com/etrusted/android/trustbadge/library/ui/badge/TrustbadgeViewModel.kt
trustedshops-public
560,817,987
false
null
/* * Created by <NAME> on 30.1.2023. * Copyright (c) 2023 Trusted Shops GmbH * * MIT License * * 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.etrusted.android.trustbadge.library.ui.badge import android.util.Log import androidx.lifecycle.ViewModel import com.etrusted.android.trustbadge.library.model.TrustbadgeData import com.etrusted.android.trustbadge.library.data.repository.TrustbadgeRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.withContext private const val TAG = "TrustbadgeVM" internal class TrustbadgeViewModel: ViewModel() { private val trustbadgeRepo = TrustbadgeRepository() private val _trustbadgeData = MutableStateFlow<TrustbadgeData?>(null) internal val trustbadgeData: StateFlow<TrustbadgeData?> get() = _trustbadgeData internal suspend fun fetchTrustbadgeData( tsId: String, channelId: String, ) { withContext(Dispatchers.IO) { try { val resp = trustbadgeRepo.fetchTrustbadgeData(tsid = tsId, channelId = channelId) if (resp.isSuccess) { withContext(Dispatchers.Main) { _trustbadgeData.value = resp.getOrNull() } } else { Log.e(TAG, "error: ${resp.exceptionOrNull()?.message}") } } catch (e: Exception) { Log.e(TAG, "error: ${e.message}") } } } }
2
Kotlin
1
0
299495b5913a8a8e541ea9fd8db8fc1477fd927d
2,599
etrusted-android-trustbadge-library
MIT License
src/main/kotlin/me/melijn/melijnbot/enums/SpamType.kt
ToxicMushroom
107,187,088
false
null
package me.melijn.melijnbot.enums enum class SpamType { FAST_MESSAGE, MANY_CAPS, MANY_MENTIONS }
5
Kotlin
22
80
01107bbaad0e343d770b1e4124a5a9873b1bb5bd
109
Melijn
MIT License
src/main/kotlin/dev/dexsr/gmod/palworld/toolbox/savegame/composeui/libint/ExternalDragAwtExtensions.kt
flammky
758,310,188
false
null
package dev.dexsr.gmod.palworld.toolbox.savegame.composeui.libint import androidx.compose.ui.ExperimentalComposeUiApi /* * Copyright 2023 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 * * 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. */ import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.toPainter import java.awt.Image import java.awt.datatransfer.DataFlavor import java.awt.datatransfer.DataFlavor.selectBestTextFlavor import java.awt.datatransfer.Transferable import java.awt.image.BufferedImage import java.io.File @OptIn(ExperimentalComposeUiApi::class) internal fun Transferable.dragData(): DragData { val bestTextFlavor = selectBestTextFlavor(transferDataFlavors) return when { isDataFlavorSupported(DataFlavor.javaFileListFlavor) -> DragDataFilesListImpl(this) isDataFlavorSupported(DataFlavor.imageFlavor) -> DragDataImageImpl(this) bestTextFlavor != null -> DragDataTextImpl(bestTextFlavor, this) else -> UnknownDragData } } @OptIn(ExperimentalComposeUiApi::class) private object UnknownDragData : DragData @OptIn(ExperimentalComposeUiApi::class) private class DragDataFilesListImpl( private val transferable: Transferable ) : DragData.FilesList { override fun readFiles(): List<String> { val files = transferable.getTransferData(DataFlavor.javaFileListFlavor) as List<*> return files.filterIsInstance<File>().map { it.toURI().toString() } } } @OptIn(ExperimentalComposeUiApi::class) private class DragDataImageImpl( private val transferable: Transferable ) : DragData.Image { override fun readImage(): Painter { return (transferable.getTransferData(DataFlavor.imageFlavor) as Image).painter() } private fun Image.painter(): Painter { if (this is BufferedImage) { return this.toPainter() } val bufferedImage = BufferedImage(getWidth(null), getHeight(null), BufferedImage.TYPE_INT_ARGB) val g2 = bufferedImage.createGraphics() try { g2.drawImage(this, 0, 0, null) } finally { g2.dispose() } return bufferedImage.toPainter() } } @OptIn(ExperimentalComposeUiApi::class) private class DragDataTextImpl( private val bestTextFlavor: DataFlavor, private val transferable: Transferable ) : DragData.Text { override val bestMimeType: String = bestTextFlavor.mimeType override fun readText(): String { val reader = bestTextFlavor.getReaderForText(transferable) return reader.readText() } }
0
null
0
4
cd07163868b5ee8d3f46d106d467d211b8f3c5d8
3,099
PalToolbox
Apache License 2.0
android/di_common/src/main/java/com/phicdy/totoanticipation/di_common/Scopes.kt
phicdy
69,365,985
false
{"Kotlin": 241309, "HTML": 1307, "Shell": 1139}
package com.phicdy.totoanticipation.di_common import javax.inject.Scope @Scope @Retention(AnnotationRetention.RUNTIME) annotation class ActivityScope @Scope @Retention(AnnotationRetention.RUNTIME) annotation class FragmentScope
20
Kotlin
0
1
5ccc5c781f5569b5da12d75a3d83bc0622daede4
232
toto-anticipation
Apache License 2.0
Stipop/src/main/java/io/stipop/extend/StipopEditText.kt
hojunjeong90
400,364,714
true
{"Kotlin": 165406, "Java": 70029}
package io.stipop.extend import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import androidx.appcompat.widget.AppCompatEditText import androidx.appcompat.widget.AppCompatTextView import io.stipop.Config import java.lang.Exception class StipopEditText : AppCompatEditText { constructor(context: Context) : super(context) { setFont() } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { setFont() } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { setFont() } private fun setFont() { if (Config.fontFace != null) { this.typeface = Config.fontFace } // letterSpacing this.letterSpacing = Config.fontCharacter } }
1
Kotlin
0
0
be1f878c1cf79cf5be1900ebb1a68d936b04dba9
849
stipop-android-sdk
MIT License
app/src/main/java/com/winterprojects/tvmazeapp/business/shows/UpdateShowFavoriteStatusUseCase.kt
CristianoWinter10
427,190,987
false
{"Kotlin": 100578}
package com.winterprojects.tvmazeapp.business.shows import com.winterprojects.tvmazeapp.domain.helpers.ResultState import com.winterprojects.tvmazeapp.domain.shows.models.ShowModel interface UpdateShowFavoriteStatusUseCase { suspend operator fun invoke(showModel: ShowModel): ResultState<Boolean> }
0
Kotlin
0
1
172516b151689332e0671449105b501cbd665ac8
304
tvmaze-app-android
MIT License
src/main/kotlin/dev/bogwalk/batch0/Problem10.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch0 /** * Problem 10: Summation of Primes * * https://projecteuler.net/problem=10 * * Goal: Find the sum of all prime numbers <= N. * * Constraints: 1 <= N <= 1e6 * * e.g. N = 5 * primes = {2, 3, 5} * sum = 10 */ class SummationOfPrimes { /** * Stores the cumulative sum of prime numbers to allow quick access to the answers for * multiple N <= [n]. * * Solution mimics original Sieve of Eratosthenes algorithm that iterates over only odd * numbers & their multiples, but uses boolean mask to alter a list of cumulative sums * instead of returning a list of prime numbers. * * SPEED (WORSE) 51.48ms for N = 1e6 * * @return array of the cumulative sums of prime numbers <= index. */ fun sumOfPrimesQuickDraw(n: Int): LongArray { require(n % 2 == 0) { "Limit must be even otherwise loop check needed" } val primesBool = BooleanArray(n + 1) { it == 2 || it > 2 && it % 2 != 0 } val sums = LongArray(n + 1) { 0L }.apply { this[2] = 2L } for (i in 3..n step 2) { if (primesBool[i]) { // change current odd number sums[i] = sums[i - 1] + i // mark all multiples of this prime if (1L * i * i < n.toLong()) { for (j in (i * i)..n step 2 * i) { primesBool[j] = false } } } else { // odd is not prime so keep most recent total sums[i] = sums[i - 1] } // change next even number sums[i + 1] = sums[i] } return sums } /** * Similar to the above solution in that it stores the cumulative sum of prime numbers to * allow future quick access; however, it replaces the typical boolean mask from the Sieve of * Eratosthenes algorithm with this cumulative cache. * * An unaltered element == 0 indicates a prime, with future multiples of that prime * marked with a -1, before the former, and its even successor, are replaced by the total so * far. * * SPEED (BETTER) 31.90ms for N = 1e6 * * @return array of the cumulative sums of prime numbers <= index. */ fun sumOfPrimesQuickDrawOptimised(n: Int): LongArray { require(n % 2 == 0) { "Limit must be even otherwise loop check needed" } val sums = LongArray(n + 1) { 0L }.apply { this[2] = 2L } var total = 2L for (i in 3..n step 2) { if (sums[i] == 0L) { total += i // mark all multiples of this prime if (1L * i * i < n.toLong()) { for (j in (i * i)..n step 2 * i) { sums[j] = -1L } } } // change current odd & next even number sums[i] = total sums[i + 1] = total } return sums } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,040
project-euler-kotlin
MIT License
presentation/src/main/java/com/innosync/hook/feature/jopoffer/info/hackathon/support/JobOfferInfoHackathonSupportViewModel.kt
2023-DGSW-FLY
685,568,000
false
{"Kotlin": 362041}
package com.innosync.hook.feature.jopoffer.info.hackathon.support import com.innosync.domain.usecase.jobopening.JobOpeningSupportHackathonUseCase import com.innosync.hook.base.BaseViewModel import com.innosync.hook.util.launchIO import com.innosync.hook.util.launchMain import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import javax.inject.Inject @HiltViewModel class JobOfferInfoHackathonSupportViewModel @Inject constructor( private val supportHackathonUseCase: JobOpeningSupportHackathonUseCase ): BaseViewModel() { private val _touchState = MutableStateFlow(false) val touchState = _touchState.asStateFlow() fun createHackathon( id: Int, name: String, contact: String, introduction: String, portfolioLink: String? ) = launchIO { supportHackathonUseCase.invoke( id = id, name = name, contact = contact, introduction = introduction, portfolioLink = portfolioLink ).onSuccess { notTouch() launchMain { viewEvent(ON_SUCCESS) } }.onFailures { launchMain { notTouch() if (it.message == "Fail") { viewEvent(ON_FAILED_OVERLAPPING) return@launchMain } viewEvent(ON_FAILED) } } } fun touch() { _touchState.value = true } fun notTouch() { _touchState.value = false } fun onClickComplete() { if (!touchState.value) { touch() viewEvent(ON_CLICK_COMPLETE) } } fun onClickBack() { viewEvent(ON_CLICK_BACK) } companion object { const val ON_CLICK_COMPLETE = 0 const val ON_CLICK_BACK = 1 const val ON_SUCCESS = 100 const val ON_FAILED = 101 const val ON_FAILED_OVERLAPPING = 102 } }
3
Kotlin
0
0
64011af8c3425a46481efe26c92da4a2758e06d6
2,055
Android_Hook
MIT License
inference/src/test/kotlin/io/kinference/operators/operations/UnsqueezeTest.kt
cybernetics
324,970,047
true
{"Kotlin": 461291, "PureBasic": 24490}
package io.kinference.operators.operations import io.kinference.runners.TestRunner import org.junit.jupiter.api.Test class UnsqueezeTest { private fun getTargetPath(dirName: String) = "/unsqueeze/$dirName/" @Test fun `test unsqueeze axis 0`() { TestRunner.runFromResources(getTargetPath("test_unsqueeze_axis_0")) } @Test fun `test unsqueeze axis 1`() { TestRunner.runFromResources(getTargetPath("test_unsqueeze_axis_1")) } @Test fun `test unsqueeze axis 2`() { TestRunner.runFromResources(getTargetPath("test_unsqueeze_axis_2")) } @Test fun `test unsqueeze axis 3`() { TestRunner.runFromResources(getTargetPath("test_unsqueeze_axis_3")) } @Test fun `test unsqueeze with negative axes`() { TestRunner.runFromResources(getTargetPath("test_unsqueeze_negative_axes")) } @Test fun `test unsqueeze three axes`() { TestRunner.runFromResources(getTargetPath("test_unsqueeze_three_axes")) } @Test fun `test unsqueeze two axes`() { TestRunner.runFromResources(getTargetPath("test_unsqueeze_two_axes")) } @Test fun `test unsqueeze unsorted axes`() { TestRunner.runFromResources(getTargetPath("test_unsqueeze_unsorted_axes")) } }
0
null
0
0
8aa3295f112353949562750b83991b7ea8b83cf2
1,292
kinference
Apache License 2.0
plugin/src/main/kotlin/xyz/jpenilla/resourcefactory/bungeecord/BungeeCordConvention.kt
jpenilla
775,651,436
false
{"Kotlin": 70506}
package xyz.jpenilla.resourcefactory.bungeecord import xyz.jpenilla.resourcefactory.ResourceFactoryConventionPlugin abstract class BungeeCordConvention : ResourceFactoryConventionPlugin.Provider<BungeeCordPluginYaml>( "bungeePluginYaml", { project -> project.bungeePluginYaml() } )
2
Kotlin
1
5
b2fbbae88f4981758d143fbeebf24512a8082e11
292
resource-factory
Apache License 2.0
FirstLineCodeForAndroid/Chapter5/FragmentTest/app/src/main/java/com/rxf113/fragmenttest/LeftFragment.kt
rxf113
397,638,698
false
null
package com.example.fragmenttest import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.rxf113.fragmenttest.R class LeftFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.left_fragment, container, false) } }
0
Kotlin
0
1
5bac57a9979901c7e249083148f62ec5c172899a
455
FirstLineCodeForAndroid
Apache License 2.0
app/src/main/java/ai/andromeda/nordstarter/base/ui/BaseFragment.kt
atick-faisal
374,208,645
false
null
package ai.andromeda.nordstarter.base.ui import ai.andromeda.nordstarter.extensions.observeEvent import ai.andromeda.nordstarter.extensions.showToast import android.content.Context import android.net.ConnectivityManager import android.os.Bundle import androidx.annotation.LayoutRes import androidx.fragment.app.Fragment abstract class BaseFragment( @LayoutRes layoutRes: Int ) : Fragment(layoutRes) { abstract val baseViewModel: BaseViewModel protected open fun observeLiveData() { observeEvent(baseViewModel.toastMessage) { message -> context?.showToast(message) } } protected fun isInternetAvailable(): Boolean { val cm = requireContext() .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return cm.activeNetwork != null } }
0
Kotlin
0
1
0956e330e6a6eced2506f1afd775a0f0d8b05404
832
Nord-Starter-Android
MIT License
app/src/main/java/akme/akme.kt
javipacheco
109,856,824
false
null
package akme import kategory.* import kotlinx.coroutines.experimental.channels.ActorJob import kotlinx.coroutines.experimental.runBlocking typealias Service<A> = Either<AkmeException, A> sealed class AkmeException: Throwable() { data class UiException(val msg: String) : AkmeException() data class ApiException(val msg: String) : AkmeException() data class CallException(val msg: String) : AkmeException() } fun <A> ServiceRight(op: () -> A): Either<AkmeException, A> = Either.Right(op()) fun <A> ServiceLeft(ex: AkmeException): Either<AkmeException, A> = Either.Left(ex) fun ServiceMonad() = Either.monad<AkmeException>() fun <A> A.catchOnly(ex: AkmeException): Service<A> = catchOnly(ex) { this } fun <A> A.catchUi(): Service<A> = this.catchOnly(AkmeException.UiException("")) fun <A> catchUi(default: () -> A): Service<A> = default().catchOnly(AkmeException.UiException("")) fun <A> catchOnly(ex: AkmeException, default: () -> A): Service<A> = try { ServiceRight({ default() }) } catch (e: Throwable) { ServiceLeft<A>(ex) } fun <A> ActorJob<A>.sendBlocking(element: A): Unit = runBlocking<Unit> { channel.send(element) }
1
Kotlin
1
23
a4b530d47adbe83691d5ec1b6f07eaba1b8c5451
1,163
rekkit
Apache License 2.0
src/main/kotlin/at/rechnerherz/example/config/Profiles.kt
rechnerherz
292,055,822
false
null
package at.rechnerherz.example.config // Constants for our Spring application profiles const val DEVELOPMENT: String = "development" const val TESTING: String = "testing" const val STAGING: String = "staging" const val PRODUCTION: String = "production"
0
Kotlin
0
3
475b6ec7f1b0d4df9c9894f8731d73d06bfef990
255
spring-boot-kotlin-rest-api-template
Apache License 2.0
core/network/src/main/java/com/roquebuarque/smartstocks/network/ScarletModule.kt
RBJUR
385,636,037
false
null
package com.roquebuarque.smartstocks.network import android.app.Application import com.tinder.scarlet.Lifecycle import com.tinder.scarlet.Scarlet import com.tinder.scarlet.lifecycle.android.AndroidLifecycle import com.tinder.scarlet.messageadapter.gson.GsonMessageAdapter import com.tinder.scarlet.streamadapter.rxjava2.RxJava2StreamAdapterFactory import com.tinder.scarlet.websocket.okhttp.newWebSocketFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class ScarletModule { @Provides @Singleton fun provideOkHttpClient(): OkHttpClient = OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)) .build() @Provides fun provideLifecycle(application: Application): Lifecycle { return AndroidLifecycle.ofApplicationForeground(application) } @Provides @Singleton fun provideScarlet(client: OkHttpClient, lifecycle: Lifecycle): Scarlet { return Scarlet.Builder() .webSocketFactory(client.newWebSocketFactory(BuildConfig.BASE_URL)) .addMessageAdapterFactory(GsonMessageAdapter.Factory()) .addStreamAdapterFactory(RxJava2StreamAdapterFactory()) .lifecycle(lifecycle) .build() } @Provides @Singleton fun provideSocketService(scarlet: Scarlet): SocketService { return scarlet.create(service = SocketService::class.java) } }
0
Kotlin
0
3
09861c8858cd456227be862880c08fa66c6ba6a3
1,660
SmartStocks
The Unlicense
src/commonTest/kotlin/superlogin/RestoreKeyTest.kt
sergeych
564,533,845
false
null
package superlogin import kotlinx.coroutines.test.runTest import net.sergeych.superlogin.InitSuperlogin import net.sergeych.superlogin.RestoreKey import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFails internal class RestoreKeyTest { @Test fun checkRestoreKey() = runTest { InitSuperlogin() val rk = RestoreKey.generate() val (id, k) = RestoreKey.parse(rk.secret) assertContentEquals(rk.restoreId, id) assertEquals(rk.key.id, k.id) assertContentEquals(rk.key.keyBytes, k.keyBytes) val x = StringBuilder(rk.secret) x[0] = (x[0].code xor 0x75).toChar() assertFails { RestoreKey.parse(x.toString()) } } }
0
Kotlin
0
0
6c0825f512e1fce0b91b74279c2f0039543d6c91
781
superlogin
MIT License
app/src/main/java/com/example/androiddevchallenge/ui/input/FloatingInput.kt
MarioNoll
349,129,357
false
{"Kotlin": 112565}
/* * 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.input import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.tween import androidx.compose.animation.core.updateTransition import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.androiddevchallenge.WeatherViewState import com.example.androiddevchallenge.ui.input.search.CitySearchInput import com.example.androiddevchallenge.ui.input.search.SearchInputListener import com.example.androiddevchallenge.ui.theme.MyTheme import dev.chrisbanes.accompanist.insets.LocalWindowInsets import dev.chrisbanes.accompanist.insets.ProvideWindowInsets @Composable fun FloatingInput( listener: SearchInputListener, viewState: WeatherViewState ) { val inputMarginTop = LocalDensity.current.run { LocalWindowInsets.current.statusBars.top.toDp() + 16.dp } val offsetFactor by updateFloatingInputOffsetFactor(viewState) BoxWithConstraints { val maxHeight = maxHeight Column( modifier = Modifier.fillMaxSize() ) { CitySearchInput( listener = listener, viewState = viewState.inputViewState, modifier = Modifier .padding(horizontal = 64.dp) .layout { measurable, constraints -> val placeable = measurable.measure(constraints) layout(placeable.width, placeable.height) { val center = (maxHeight - placeable.height.toDp()) / 2 val offsetRange = (center - inputMarginTop) val y = (offsetRange * offsetFactor) .plus(inputMarginTop) .roundToPx() placeable.place(x = 0, y = y) } } ) } } } @Composable private fun updateFloatingInputOffsetFactor(viewState: WeatherViewState): State<Float> { val transition = updateTransition(viewState) val offsetFactor = transition.animateFloat( transitionSpec = { tween(durationMillis = 1000) } ) { when (viewState) { is WeatherViewState.Result -> 0F is WeatherViewState.Search -> 1F } } return remember(transition) { offsetFactor } } @Preview(widthDp = 360, heightDp = 100) @Composable fun FloatingInputPreview() { MyTheme { ProvideWindowInsets { FloatingInput( listener = SearchInputListener.NONE, viewState = WeatherViewState.DEFAULT ) } } }
0
Kotlin
0
1
1a9b93677e258398c4c92fad1d700c924a0a4a21
3,850
android-dev-challenge-compose-week4
Apache License 2.0
manager-commons/src/main/kotlin/com/github/lee/core/Constants.kt
291700351
142,010,755
false
{"Java": 55328, "Kotlin": 19403, "Dockerfile": 1295, "Shell": 154, "Batchfile": 140}
package com.github.lee.core class Constants { companion object { /**SpringBoot启动类上添加包扫描*/ const val SCAN_BASE_PACKAGES = "com.github.lee" /**数据库操作的Mapper扫描地*/ const val SCAN_BASE_MAPPER ="com.github.lee.dao.mapper" } }
1
null
1
1
d7f65afb5ef880b22249ddd2df002e9268582c2b
259
CloudManager
MIT License
src/test/kotlin/io/github/srtigers98/birthdaydiscordbot/application/command/BirthdaySelectCommandTest.kt
SRTigers98
461,204,182
false
{"Kotlin": 71103, "Dockerfile": 446}
package io.github.srtigers98.birthdaydiscordbot.application.command import dev.kord.common.entity.InteractionResponseType import dev.kord.common.entity.Permission import dev.kord.common.entity.Permissions import dev.kord.common.entity.Snowflake import dev.kord.common.entity.optional.OptionalSnowflake import dev.kord.core.cache.data.InteractionData import dev.kord.core.entity.Member import dev.kord.core.entity.User import dev.kord.core.entity.interaction.ChatInputCommandInteraction import io.github.srtigers98.birthdaydiscordbot.application.service.GuildConfigService import kotlinx.coroutines.runBlocking import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @ExtendWith(MockitoExtension::class) internal class BirthdaySelectCommandTest { @InjectMocks private lateinit var tested: BirthdaySelectCommand @Mock private lateinit var guildConfigService: GuildConfigService @Test fun handleCommandTest() = runBlocking<Unit> { val interaction: ChatInputCommandInteraction = mock() val interactionUser: User = mock() val interactionData: InteractionData = mock() val guildId = "111" val channelId = "555" val member: Member = mock() val memberPermissions: Permissions = mock() whenever(interaction.data) .thenReturn(interactionData) whenever(interactionData.guildId) .thenReturn(OptionalSnowflake.Value(Snowflake(guildId))) whenever(interaction.channelId) .thenReturn(Snowflake(channelId)) whenever(interaction.user) .thenReturn(interactionUser) whenever(interactionUser.asMember(Snowflake(guildId))) .thenReturn(member) whenever(member.getPermissions()) .thenReturn(memberPermissions) whenever(memberPermissions.contains(Permission.ManageGuild)) .thenReturn(true) whenever(guildConfigService.selectGuildChannel(guildId, channelId)) .thenReturn(mock()) val result = tested.handleCommand(interaction) assertThat(result, `is`(notNullValue())) assertThat(result.type, `is`(InteractionResponseType.ChannelMessageWithSource)) assertThat(result.data.value, `is`(notNullValue())) assertThat(result.data.value?.content?.value, `is`(notNullValue())) verify(guildConfigService, times(1)) .selectGuildChannel(guildId, channelId) } @Test fun handleCommandNoPermissionTest() = runBlocking<Unit> { val interaction: ChatInputCommandInteraction = mock() val interactionUser: User = mock() val interactionData: InteractionData = mock() val guildId = "111" val channelId = "555" val member: Member = mock() val memberPermissions: Permissions = mock() whenever(interaction.data) .thenReturn(interactionData) whenever(interactionData.guildId) .thenReturn(OptionalSnowflake.Value(Snowflake(guildId))) whenever(interaction.channelId) .thenReturn(Snowflake(channelId)) whenever(interaction.user) .thenReturn(interactionUser) whenever(interactionUser.asMember(Snowflake(guildId))) .thenReturn(member) whenever(member.getPermissions()) .thenReturn(memberPermissions) whenever(memberPermissions.contains(Permission.ManageGuild)) .thenReturn(false) val result = tested.handleCommand(interaction) assertThat(result, `is`(notNullValue())) assertThat(result.type, `is`(InteractionResponseType.ChannelMessageWithSource)) assertThat(result.data.value, `is`(notNullValue())) assertThat(result.data.value?.content?.value, `is`(notNullValue())) verify(guildConfigService, times(0)) .selectGuildChannel(guildId, channelId) } }
6
Kotlin
0
4
e5363762d7522d88ae583bfcd86f67dd2bb6295a
3,989
ye-ol-birthday-reminder
MIT License
app/src/main/java/com/tcc/alif/view/ui/administrator/configuration/OptionConfigurationAdapter.kt
Limatucano
343,949,865
false
null
package com.tcc.alif.view.ui.administrator.configuration import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.tcc.alif.data.model.local.ConfigurationOptions import com.tcc.alif.databinding.ConfigurationOptionsItemBinding class OptionConfigurationAdapter( private val context: Context, val action: (intent: ConfigurationIntent) -> Unit ) : RecyclerView.Adapter<OptionConfigurationAdapter.ViewHolder>() { var options: List<ConfigurationOptions> = listOf() set(value){ field = value notifyDataSetChanged() } inner class ViewHolder( private val binding: ConfigurationOptionsItemBinding ) : RecyclerView.ViewHolder(binding.root){ fun bind(option: ConfigurationOptions) = binding.run { optionIcon.setImageResource(option.icon) optionTitle.text = context.getText(option.title) root.setOnClickListener { action.invoke(option.intent) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = ConfigurationOptionsItemBinding.inflate( LayoutInflater.from(context), parent, false ) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(options[position]) } override fun getItemCount(): Int = options.size }
0
Kotlin
0
4
cb64297f16b239bd07ce109e286d379e4fbf9908
1,534
alif
MIT License
legacy/src/main/kotlin/com/hadilq/mastan/timeline/ui/Share.kt
hadilq
715,823,678
false
{"Kotlin": 689784, "Nix": 4671}
/** * Copyright 2023 Hadi Lashkari Ghouchani * * 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.hadilq.mastan.timeline.ui import android.content.Context import android.content.Intent import com.hadilq.mastan.timeline.ui.model.UI fun Context.shareStatus( status: UI, ) { status.contentEmojiText?.text?.let { share( title ="Status", text = "${it.substring(30)}\n${status.sharingUri}", ) } } fun Context.share( title: String? = null, text: String, ) { val sendIntent: Intent = Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, text) type = "text/plain" } startActivity(Intent.createChooser(sendIntent, title)) }
0
Kotlin
0
3
f17caa73c487d927d651e788215aa30b8b9cf842
1,251
Mastan
Apache License 2.0
adaptive-lib/adaptive-browser/src/jsMain/kotlin/hu/simplexion/adaptive/html/launchButton.kt
spxbhuhb
788,711,010
false
{"Kotlin": 1058159, "CSS": 47382, "Java": 18012, "HTML": 2759, "JavaScript": 896}
/* * Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package hu.simplexion.adaptive.html import hu.simplexion.adaptive.base.* import hu.simplexion.adaptive.dom.AdaptiveDOMNodeFragment import kotlinx.browser.document import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.w3c.dom.HTMLButtonElement import org.w3c.dom.Node fun Adaptive.launchButton(title: String, onClick: suspend () -> Unit) { manualImplementation(AdaptiveButton::class, title, onClick) } class AdaptiveLaunchButton( adapter: AdaptiveAdapter<Node>, parent: AdaptiveFragment<Node>, index: Int ) : AdaptiveDOMNodeFragment(adapter, parent, index, 2, true) { private val label: String get() = state[0] as String private val onClick: AdaptiveSupportFunction get() = state[1] as AdaptiveSupportFunction override val receiver = document.createElement("button") as HTMLButtonElement override fun genPatchInternal() { val closureMask = getThisClosureDirtyMask() if (haveToPatch(closureMask, 1)) { receiver.innerText = label } if (haveToPatch(closureMask, 2)) { receiver.onclick = { CoroutineScope(Dispatchers.Default).launch { onClick.invokeSuspend() } onClick.declaringFragment.patch() } } } }
1
Kotlin
0
0
75ec9b0c6a9f89359a08ce992affab493475ca4c
1,489
adaptive
Apache License 2.0
solar/src/main/java/com/chiksmedina/solar/outline/videoaudiosound/Pip2.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.outline.videoaudiosound import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.outline.VideoAudioSoundGroup val VideoAudioSoundGroup.Pip2: ImageVector get() { if (_pip2 != null) { return _pip2!! } _pip2 = Builder( name = "Pip2", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd ) { moveTo(10.9548f, 2.25f) horizontalLineTo(13.0452f) curveTo(14.8818f, 2.25f, 16.3214f, 2.25f, 17.4635f, 2.3737f) curveTo(18.6291f, 2.5f, 19.5734f, 2.7623f, 20.3798f, 3.3482f) curveTo(20.8679f, 3.7028f, 21.2972f, 4.1321f, 21.6518f, 4.6202f) curveTo(22.2377f, 5.4266f, 22.5f, 6.3709f, 22.6263f, 7.5365f) curveTo(22.75f, 8.6786f, 22.75f, 10.1182f, 22.75f, 11.9547f) verticalLineTo(12.0453f) curveTo(22.75f, 13.8818f, 22.75f, 15.3214f, 22.6263f, 16.4635f) curveTo(22.5f, 17.6291f, 22.2377f, 18.5734f, 21.6518f, 19.3798f) curveTo(21.2972f, 19.8679f, 20.8679f, 20.2972f, 20.3798f, 20.6518f) curveTo(19.5734f, 21.2377f, 18.6291f, 21.5f, 17.4635f, 21.6263f) curveTo(16.3214f, 21.75f, 14.8818f, 21.75f, 13.0453f, 21.75f) horizontalLineTo(10.9547f) curveTo(9.1182f, 21.75f, 7.6786f, 21.75f, 6.5365f, 21.6263f) curveTo(5.3709f, 21.5f, 4.4266f, 21.2377f, 3.6202f, 20.6518f) curveTo(3.1321f, 20.2972f, 2.7028f, 19.8679f, 2.3482f, 19.3798f) curveTo(1.7623f, 18.5734f, 1.5f, 17.6291f, 1.3737f, 16.4635f) curveTo(1.25f, 15.3214f, 1.25f, 13.8818f, 1.25f, 12.0452f) verticalLineTo(11.9548f) curveTo(1.25f, 10.1182f, 1.25f, 8.6786f, 1.3737f, 7.5365f) curveTo(1.5f, 6.3709f, 1.7623f, 5.4266f, 2.3482f, 4.6202f) curveTo(2.7028f, 4.1321f, 3.1321f, 3.7028f, 3.6202f, 3.3482f) curveTo(4.4266f, 2.7623f, 5.3709f, 2.5f, 6.5365f, 2.3737f) curveTo(7.6786f, 2.25f, 9.1182f, 2.25f, 10.9548f, 2.25f) close() moveTo(6.6981f, 3.865f) curveTo(5.6601f, 3.9774f, 5.0099f, 4.1926f, 4.5019f, 4.5617f) curveTo(4.1411f, 4.8238f, 3.8238f, 5.1411f, 3.5617f, 5.5019f) curveTo(3.1926f, 6.0099f, 2.9774f, 6.6601f, 2.865f, 7.6981f) curveTo(2.751f, 8.75f, 2.75f, 10.1084f, 2.75f, 12.0f) curveTo(2.75f, 13.8916f, 2.751f, 15.25f, 2.865f, 16.302f) curveTo(2.9774f, 17.3399f, 3.1926f, 17.9901f, 3.5617f, 18.4981f) curveTo(3.8238f, 18.8589f, 4.1411f, 19.1762f, 4.5019f, 19.4383f) curveTo(5.0099f, 19.8074f, 5.6601f, 20.0225f, 6.6981f, 20.135f) curveTo(7.75f, 20.249f, 9.1084f, 20.25f, 11.0f, 20.25f) horizontalLineTo(13.0f) curveTo(14.8916f, 20.25f, 16.25f, 20.249f, 17.302f, 20.135f) curveTo(18.3399f, 20.0225f, 18.9901f, 19.8074f, 19.4981f, 19.4383f) curveTo(19.8589f, 19.1762f, 20.1762f, 18.8589f, 20.4383f, 18.4981f) curveTo(20.8074f, 17.9901f, 21.0225f, 17.3399f, 21.135f, 16.302f) curveTo(21.249f, 15.25f, 21.25f, 13.8916f, 21.25f, 12.0f) curveTo(21.25f, 10.1084f, 21.249f, 8.75f, 21.135f, 7.6981f) curveTo(21.0225f, 6.6601f, 20.8074f, 6.0099f, 20.4383f, 5.5019f) curveTo(20.1762f, 5.1411f, 19.8589f, 4.8238f, 19.4981f, 4.5617f) curveTo(18.9901f, 4.1926f, 18.3399f, 3.9774f, 17.302f, 3.865f) curveTo(16.25f, 3.751f, 14.8916f, 3.75f, 13.0f, 3.75f) horizontalLineTo(11.0f) curveTo(9.1084f, 3.75f, 7.75f, 3.751f, 6.6981f, 3.865f) close() moveTo(13.9747f, 10.25f) horizontalLineTo(15.0253f) curveTo(15.4697f, 10.25f, 15.8408f, 10.25f, 16.1454f, 10.2708f) curveTo(16.4625f, 10.2924f, 16.762f, 10.339f, 17.0524f, 10.4593f) curveTo(17.7262f, 10.7384f, 18.2616f, 11.2738f, 18.5407f, 11.9476f) curveTo(18.661f, 12.238f, 18.7076f, 12.5375f, 18.7292f, 12.8546f) curveTo(18.75f, 13.1592f, 18.75f, 13.5303f, 18.75f, 13.9747f) verticalLineTo(14.0253f) curveTo(18.75f, 14.4697f, 18.75f, 14.8408f, 18.7292f, 15.1454f) curveTo(18.7076f, 15.4625f, 18.661f, 15.762f, 18.5407f, 16.0524f) curveTo(18.2616f, 16.7262f, 17.7262f, 17.2616f, 17.0524f, 17.5407f) curveTo(16.762f, 17.661f, 16.4625f, 17.7076f, 16.1454f, 17.7292f) curveTo(15.8408f, 17.75f, 15.4697f, 17.75f, 15.0253f, 17.75f) horizontalLineTo(13.9747f) curveTo(13.5303f, 17.75f, 13.1592f, 17.75f, 12.8546f, 17.7292f) curveTo(12.5375f, 17.7076f, 12.238f, 17.661f, 11.9476f, 17.5407f) curveTo(11.2738f, 17.2616f, 10.7384f, 16.7262f, 10.4593f, 16.0524f) curveTo(10.339f, 15.762f, 10.2924f, 15.4625f, 10.2708f, 15.1454f) curveTo(10.25f, 14.8408f, 10.25f, 14.4697f, 10.25f, 14.0253f) verticalLineTo(13.9747f) curveTo(10.25f, 13.5303f, 10.25f, 13.1592f, 10.2708f, 12.8546f) curveTo(10.2924f, 12.5375f, 10.339f, 12.238f, 10.4593f, 11.9476f) curveTo(10.7384f, 11.2738f, 11.2738f, 10.7384f, 11.9476f, 10.4593f) curveTo(12.238f, 10.339f, 12.5375f, 10.2924f, 12.8546f, 10.2708f) curveTo(13.1592f, 10.25f, 13.5303f, 10.25f, 13.9747f, 10.25f) close() moveTo(12.9567f, 11.7673f) curveTo(12.716f, 11.7837f, 12.5988f, 11.8132f, 12.5216f, 11.8451f) curveTo(12.2154f, 11.972f, 11.972f, 12.2154f, 11.8451f, 12.5216f) curveTo(11.8132f, 12.5988f, 11.7837f, 12.716f, 11.7673f, 12.9567f) curveTo(11.7504f, 13.2042f, 11.75f, 13.5238f, 11.75f, 14.0f) curveTo(11.75f, 14.4762f, 11.7504f, 14.7958f, 11.7673f, 15.0433f) curveTo(11.7837f, 15.284f, 11.8132f, 15.4012f, 11.8451f, 15.4784f) curveTo(11.972f, 15.7846f, 12.2154f, 16.028f, 12.5216f, 16.1549f) curveTo(12.5988f, 16.1868f, 12.716f, 16.2163f, 12.9567f, 16.2327f) curveTo(13.2042f, 16.2496f, 13.5238f, 16.25f, 14.0f, 16.25f) horizontalLineTo(15.0f) curveTo(15.4762f, 16.25f, 15.7958f, 16.2496f, 16.0433f, 16.2327f) curveTo(16.284f, 16.2163f, 16.4012f, 16.1868f, 16.4784f, 16.1549f) curveTo(16.7846f, 16.028f, 17.028f, 15.7846f, 17.1549f, 15.4784f) curveTo(17.1868f, 15.4012f, 17.2163f, 15.284f, 17.2327f, 15.0433f) curveTo(17.2496f, 14.7958f, 17.25f, 14.4762f, 17.25f, 14.0f) curveTo(17.25f, 13.5238f, 17.2496f, 13.2042f, 17.2327f, 12.9567f) curveTo(17.2163f, 12.716f, 17.1868f, 12.5988f, 17.1549f, 12.5216f) curveTo(17.028f, 12.2154f, 16.7846f, 11.972f, 16.4784f, 11.8451f) curveTo(16.4012f, 11.8132f, 16.284f, 11.7837f, 16.0433f, 11.7673f) curveTo(15.7958f, 11.7504f, 15.4762f, 11.75f, 15.0f, 11.75f) horizontalLineTo(14.0f) curveTo(13.5238f, 11.75f, 13.2042f, 11.7504f, 12.9567f, 11.7673f) close() } } .build() return _pip2!! } private var _pip2: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
8,379
SolarIconSetAndroid
MIT License