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/model/AuthenticationToken.kt
mehdizebhi
769,983,829
false
{"Kotlin": 13306}
package model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class AuthenticationToken( @SerialName("access_token") val accessToken: String, @SerialName("expires_in") val expiresIn: Int, @SerialName("refresh_token") val refreshToken: String, @SerialName("scope") val scope: List<String>, @SerialName("token_type") val tokenType: String )
0
Kotlin
0
0
ea1bc30f0e8516d9f7505ac737a33a7ea398ed72
433
2each
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/Dry.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/Dry") @file:JsNonModule package mui.icons.material @JsName("default") external val Dry: SvgIconComponent
12
Kotlin
145
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
188
kotlin-wrappers
Apache License 2.0
common/src/commonMain/kotlin/com/artemchep/keyguard/common/usecase/GetProducts.kt
AChep
669,697,660
false
{"Kotlin": 5516822, "HTML": 45876}
package com.artemchep.keyguard.common.usecase import com.artemchep.keyguard.common.model.Product import kotlinx.coroutines.flow.Flow interface GetProducts : () -> Flow<List<Product>?>
66
Kotlin
31
995
557bf42372ebb19007e3a8871e3f7cb8a7e50739
186
keyguard-app
Linux Kernel Variant of OpenIB.org license
news/src/main/java/com/antarikshc/news/models/Author.kt
antarikshc
129,514,672
false
null
package com.antarikshc.news.models import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName @Entity(tableName = "authors_table") data class Author( @PrimaryKey(autoGenerate = false) var id: String = "", @ColumnInfo(name = "news_id") val newsId: String = "", @SerializedName("webTitle") val title: String, val bio: String? )
2
Kotlin
2
4
2f160f561cd74b4fa1f3380f1d086828851d6e80
442
Bluffpost
Apache License 2.0
app/src/main/java/com/ocakmali/brewway/equipments/coffees/CoffeesViewModel.kt
ocakmali
155,255,987
false
null
package com.ocakmali.brewway.equipments.coffees import androidx.lifecycle.MutableLiveData import androidx.paging.toLiveData import com.crashlytics.android.Crashlytics import com.ocakmali.brewway.base.BaseViewModel import com.ocakmali.brewway.datamodel.CoffeeView import com.ocakmali.brewway.datamodel.toCoffee import com.ocakmali.brewway.datamodel.toView import com.ocakmali.brewway.exceptions.EmptyItem import com.ocakmali.common.Result import com.ocakmali.domain.interactor.CoffeeInterActor import kotlinx.coroutines.launch class CoffeesViewModel(private val interActor: CoffeeInterActor) : BaseViewModel() { val coffees = interActor.loadCoffees() .map { it.toView() } .toLiveData(20) val coffeeInserted = MutableLiveData<Unit>() fun addCoffee(coffeeView: CoffeeView) = launch { if (coffeeView.name.isEmpty()) { postFailure(EmptyItem) } else { interActor.addCoffee(coffeeView.toCoffee()).also { it.result(::coffeeInsertionFailed, ::coffeeInsertionSucceed) } } } private fun coffeeInsertionFailed(e: Exception) { Crashlytics.logException(e) postFailure(e) } private fun coffeeInsertionSucceed(u: Unit) { coffeeInserted.value = u } fun deleteCoffee(coffeeView: CoffeeView) = launch { interActor.deleteCoffee(coffeeView.toCoffee()).also {result -> if (result is Result.Error) { Crashlytics.logException(result.error) postFailure(result.error) } } } }
0
Kotlin
0
1
cde32648afdab7c6f2dbc65ba8be7a2458ea8c1a
1,592
BrewWay
MIT License
app/src/main/java/com/temtem/interactive/map/temzone/domain/repository/temzone/model/marker/spawn/temtem/Type.kt
Temtem-Interactive-Map
568,136,913
false
null
package com.temtem.interactive.map.temzone.domain.repository.temzone.model.marker.spawn.temtem data class Type( val name: String, val imageUrl: String, )
0
Kotlin
0
1
338c95ef870b6ead4a58daec914c99583f1dc294
163
Temzone-Android
MIT License
src/main/day07/Filesystem.kt
ollehagner
572,141,655
false
{"Kotlin": 80353}
package day07 import java.util.* class Filesystem { val TOTAL_DISK_SPACE = 70000000 private val dirStack: Deque<Directory> = LinkedList() private fun root(): Directory { return dirStack.last } fun availableDiskspace(): Int { return TOTAL_DISK_SPACE - root().value() } fun allDirectories(): List<Directory> { var toProcess = mutableListOf<Directory>() var result = mutableListOf<Directory>() toProcess.addAll(root().subDirs()) result.add(root()) do { val inProgressDir = toProcess.removeFirst() result.add(inProgressDir) toProcess.addAll(inProgressDir.subDirs()) } while(toProcess.isNotEmpty()) return result } fun createFromCommandData(command: String, output: List<String>) { when { command == "$ cd .." -> { if(dirStack.size > 1) { dirStack.pop() } } command.matches("\\$ cd .*".toRegex()) -> { val newDir = Directory(command.substringAfter("cd ")) dirStack.peek()?.addChild(newDir) dirStack.push(newDir) } command.startsWith("$ ls") -> { val currentDir = dirStack.peek()!! output .filter { !it.startsWith("dir") } .forEach { fileInfo -> fileInfo.split(" ").let { parts -> currentDir.addChild(File(parts[1], parts[0].toInt())) } } } } } fun print() { dirStack.last().print(0) } }
0
Kotlin
0
0
6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1
1,712
aoc2022
Apache License 2.0
keel-scheduler/src/main/kotlin/com/netflix/spinnaker/keel/scheduler/SchedulerAgent.kt
jeyrschabu
126,823,024
true
{"Kotlin": 358363, "Shell": 2094}
/* * Copyright 2017 Netflix, Inc. * * 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.netflix.spinnaker.keel.scheduler import com.netflix.spinnaker.q.Queue import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.time.Duration import javax.annotation.PostConstruct /** * Starts the convergence schedule, and ensures that it stays scheduled through failures. */ @Component @ConditionalOnExpression("\${scheduler.enabled:true}") class SchedulerAgent( private val queue: Queue, @Value("\${scheduler.retry.onStart.ms:30000}") private val ensureSchedulerFrequency: Long ) { private val log = LoggerFactory.getLogger(javaClass) @PostConstruct fun ensureSchedule() { log.info("Ensuring scheduler convergence task exists") queue.ensure(ScheduleConvergence(), Duration.ofMillis(ensureSchedulerFrequency)) } @Scheduled(fixedDelayString = "\${scheduler.retry.frequency.ms:30000}") fun run() { queue.ensure(ScheduleConvergence(), Duration.ofSeconds(30)) } }
0
Kotlin
0
0
db755ed4b692a38dcb53d3e5290a36c702ea0ef0
1,734
keel
Apache License 2.0
src/main/kotlin/no/nav/klage/document/util/TokenUtil.kt
navikt
417,132,176
false
{"Kotlin": 42449, "PLpgSQL": 823, "Dockerfile": 133}
package no.nav.klage.document.util import no.nav.klage.document.config.SecurityConfiguration.Companion.ISSUER_AAD import no.nav.security.token.support.core.context.TokenValidationContextHolder import org.springframework.stereotype.Service @Service class TokenUtil( private val tokenValidationContextHolder: TokenValidationContextHolder, ) { companion object { @Suppress("JAVA_CLASS_ON_COMPANION") private val logger = getLogger(javaClass.enclosingClass) private val securelogger = getSecureLogger() } fun getIdent(): String = getIdentNullable() ?: throw RuntimeException("NAVident not found in token") fun getIdentNullable(): String? = tokenValidationContextHolder.tokenValidationContext.getJwtToken(ISSUER_AAD) .jwtTokenClaims?.get("NAVident")?.toString() }
1
Kotlin
0
0
e139b54db614e90a8e8c8c8f0aadb91818680dcc
837
kabal-smart-editor-api
MIT License
app/src/main/java/com/example/mc_project/network/nearestStops.kt
AbhishekIIITD
805,312,421
false
{"Kotlin": 45931}
package com.example.mc_project.network import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Text import androidx.compose.foundation.layout.* import androidx.compose.material3.IconButton import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.google.maps.android.compose.GoogleMap import com.google.maps.android.compose.rememberCameraPositionState import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import com.example.mc_project.viewModels.ApiViewModel import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat import androidx.navigation.NavHostController import com.example.mc_project.R import com.example.mc_project.StopsDetails import com.example.mc_project.viewModels.StopsUiState import com.example.mc_project.viewModels.buesyouarein import com.google.android.gms.maps.model.BitmapDescriptor import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import com.google.maps.android.compose.Marker import com.google.maps.android.compose.rememberMarkerState import android.graphics.BitmapFactory import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material3.Icon import com.google.android.gms.maps.model.BitmapDescriptorFactory @OptIn(ExperimentalMaterial3Api::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun NearestStopsScreen( navController: NavHostController, viewModel: ApiViewModel, lat: Double, lon: Double, context: Context ) { val modifier = Modifier Scaffold( topBar = { CenterAlignedTopAppBar( actions = { IconButton(onClick = { }) {} Icon(Icons.Default.MoreVert, contentDescription = "", tint = Color.Black) }, navigationIcon = { IconButton(onClick = { navController.popBackStack() }) { Icon(Icons.Default.ArrowBack, contentDescription = "", tint = Color.Black) } }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primary, ), title = { Text("MERI BUS", color = MaterialTheme.colorScheme.background) } ) } ) { paddingValues -> val stopsUiState = viewModel.stopsUiState val busState = viewModel.bus viewModel.getNearbyStops(lat, lon) Column(modifier.padding(paddingValues)) { when (stopsUiState) { is StopsUiState.Loading -> LoadingScreen(modifier = modifier.fillMaxSize()) is StopsUiState.Success -> { when (busState) { is buesyouarein.Loading -> { LoadingScreen(modifier = modifier.fillMaxSize()) } is buesyouarein.Success -> { val busList = busState.buesyouarein ?: emptyList() val closestBus = busList.minByOrNull { it.distace_frome_me } closestBus?.let { closestBus -> Card( modifier = Modifier .fillMaxWidth() .padding(5.dp) ) { Column(modifier = Modifier.padding(16.dp)) { Text( text = "Bus ID: ${closestBus.id}", style = TextStyle( color = MaterialTheme.colorScheme.primary, fontSize = 18.sp ) ) Text( text = "Start Date: ${closestBus.startDate}", style = TextStyle( color = MaterialTheme.colorScheme.onSurface, fontSize = 16.sp ) ) Text( text = "Start Time: ${closestBus.startTime}", style = TextStyle( color = MaterialTheme.colorScheme.onSurface, fontSize = 16.sp ) ) } } Box( modifier = Modifier .clip(RoundedCornerShape(10.dp)) .padding(15.dp) .requiredHeight(500.dp) ) { MapWithMarkers( closestBus, stopsUiState.stopDetails ?: emptyList(), context ) } } ?: run { Card( modifier = Modifier .fillMaxWidth() .padding(5.dp) ) { Column(modifier = Modifier.padding(16.dp)) { Text( text = "No Bus Around You In 500m Radius", style = TextStyle( color = MaterialTheme.colorScheme.primary, fontSize = 18.sp ) ) } } Box( modifier = Modifier .clip(RoundedCornerShape(10.dp)) .padding(15.dp) .requiredHeight(500.dp) ) { MapWithMarkers( closestBus, stopsUiState.stopDetails ?: emptyList(), context ) } } } else -> ErrorScreen("error") } val stopsDetails = stopsUiState.stopDetails if (stopsDetails.isNullOrEmpty()) { ErrorScreen("Error in result") } else { val sortedStops = stopsDetails.sortedBy { it.distance } // Sort stops by distance LazyRow() { items(sortedStops) { stop -> Card(Modifier.padding(4.dp)) { StopItem(stop = stop) } } } } } else -> { Text(text = "Stop error") } } } } } @Composable fun MapWithMarkers( busData: VehicleData?, stops: List<StopsDetails>, context: Context ) { // Calculate the average latitude and longitude of all stops val averageLatitude = stops.map { it.stop_lat }.average() val averageLongitude = stops.map { it.stop_lon }.average() val markerPosition = LatLng(averageLatitude, averageLongitude) // Remember the camera position state val cameraPositionState = rememberCameraPositionState { position = CameraPosition.fromLatLngZoom(markerPosition, 16f) } // Show GoogleMap GoogleMap( modifier = Modifier.fillMaxSize(), cameraPositionState = cameraPositionState ) { // Add markers for each bus val busLatitude = busData?.latitude val busLongitude = busData?.longitude val busMarkerState = rememberMarkerState("Bus marker") if (busLatitude != null) { if (busLongitude != null) { busMarkerState.position = LatLng(busLatitude.toDouble(), busLongitude.toDouble()) } } Marker( state = busMarkerState, icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE), anchor = Offset(0.5f, 0.5f) ) // Add markers for each stop stops.forEach { stop -> val stopMarkerState = rememberMarkerState("Stop marker") stopMarkerState.position = LatLng(stop.stop_lat.toDouble(), stop.stop_lon.toDouble()) Marker( state = stopMarkerState, icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED), anchor = Offset(0.5f, 0.5f) ) } } } @Composable fun StopItem(stop: StopsDetails) { Column( modifier = Modifier .padding(8.dp) .clip(RoundedCornerShape(12.dp)) // .background(Color.Black.copy(alpha = 0.7f)) // 70% transparency ) { Column( modifier = Modifier .padding(16.dp) ) { Text( text = stop.stop_name, style = TextStyle(color = MaterialTheme.colorScheme.primary, fontSize = 18.sp) ) Text( text = "lat: ${stop.stop_lat} m", style = TextStyle(color = MaterialTheme.colorScheme.onSurface, fontSize = 14.sp) ) Text( text = "lon: ${stop.stop_lon} m", style = TextStyle(color = MaterialTheme.colorScheme.onSurface, fontSize = 14.sp) ) } } }
0
Kotlin
0
0
a50b5817d281d493988dc714849a591cb3727168
12,088
Meri_BUS
MIT License
app/src/main/java/com/technicalassigments/moviewapp/ui/detailmovie/adapter/ReviewsLoadStateAdapter.kt
anang2602
380,973,246
false
null
package com.technicalassigments.moviewapp.ui.detailmovie.adapter import android.view.ViewGroup import androidx.paging.LoadState import androidx.paging.LoadStateAdapter import com.technicalassigments.moviewapp.ui.detailmovie.view.ReviewsLoadStateViewHolder import com.technicalassigments.moviewapp.ui.main.view.MovieLoadStateViewHolder class ReviewsLoadStateAdapter(private val retry: () -> Unit) : LoadStateAdapter<ReviewsLoadStateViewHolder>() { override fun onBindViewHolder(holder: ReviewsLoadStateViewHolder, loadState: LoadState) { holder.bind(loadState) } override fun onCreateViewHolder( parent: ViewGroup, loadState: LoadState ): ReviewsLoadStateViewHolder { return ReviewsLoadStateViewHolder.create(parent, retry) } }
0
Kotlin
0
0
2d746afeb8ca41c4ef78b78e0ba2e0af8c3c3163
786
movie-app
Apache License 2.0
twitter-core/src/main/java/com/twitter/sdk/android/core/identity/OAuthWebViewClient.kt
takke
195,917,891
true
{"Java": 273963, "Kotlin": 73666}
/* * Copyright (C) 2015 Twitter, Inc. * * 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.twitter.sdk.android.core.identity import android.net.http.SslError import android.os.Bundle import android.webkit.SslErrorHandler import android.webkit.WebView import android.webkit.WebViewClient import com.twitter.sdk.android.core.internal.network.UrlUtils import java.net.URI internal class OAuthWebViewClient( private val completeUrl: String, private val listener: Listener ) : WebViewClient() { internal interface Listener { fun onPageFinished(webView: WebView, url: String) fun onSuccess(bundle: Bundle) fun onError(exception: WebViewException) } override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) listener.onPageFinished(view, url) } override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { if (url.startsWith(completeUrl)) { val params = UrlUtils.getQueryParams(URI.create(url), false) val bundle = Bundle(params.size) for ((key, value) in params) { bundle.putString(key, value) } listener.onSuccess(bundle) return true } @Suppress("DEPRECATION") return super.shouldOverrideUrlLoading(view, url) } override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { @Suppress("DEPRECATION") super.onReceivedError(view, errorCode, description, failingUrl) listener.onError(WebViewException(errorCode, description, failingUrl)) } override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) { super.onReceivedSslError(view, handler, error) listener.onError(WebViewException(error.primaryError, null, null)) } }
1
Java
1
1
33c16785b9adeb3e54299dff85280bdfafce4873
2,453
simple-twitter-auth-android
Apache License 2.0
app/src/main/java/com/doctoror/particleswallpaper/presentation/di/modules/ServicesContributes.kt
NTRsolutions
149,505,676
true
{"Kotlin": 365313, "Java": 1291, "IDL": 1233, "Prolog": 763}
/* * Copyright (C) 2018 <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.doctoror.particleswallpaper.presentation.di.modules import com.doctoror.particleswallpaper.data.engine.WallpaperServiceImpl import dagger.Module import dagger.android.ContributesAndroidInjector @Module interface ServicesContributes { @ContributesAndroidInjector fun wallpaperService(): WallpaperServiceImpl }
0
Kotlin
0
0
860235f776e6af339241bbd3a3ba6927d26699ef
927
ParticleConstellationsLiveWallpaper
Apache License 2.0
app/src/main/java/com/github/boybeak/v8x/app/model/Location.kt
boybeak
616,090,715
false
null
package com.github.boybeak.v8x.app.model import com.eclipsesource.v8.V8Object import com.github.boybeak.v8x.binding.V8BindingAdapter class Location : V8BindingAdapter { override fun getBindingId(): String { return hashCode().toString() } override fun onDoubleBindingChanged( target: V8Object, fieldName: String, newValue: Double, oldValue: Double ) { super.onDoubleBindingChanged(target, fieldName, newValue, oldValue) } }
0
Kotlin
0
1
51b79c523ab50ba10112f0ec10d77b89a1ed9c35
493
v8x
MIT License
WearSpeakerSample/wear/src/main/java/com/example/android/wearable/speaker/SpeakerApp.kt
android
192,007,253
false
{"Kotlin": 376081, "Shell": 1164}
/* * 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.android.wearable.speaker import android.Manifest import android.app.Activity import android.content.Context import android.content.ContextWrapper import androidx.activity.compose.ManagedActivityResultLauncher import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts.RequestPermission import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.stringResource import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.viewmodel.compose.viewModel import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.Text import androidx.wear.compose.material.dialog.Confirmation import androidx.wear.compose.navigation.SwipeDismissableNavHost import androidx.wear.compose.navigation.composable import androidx.wear.compose.navigation.rememberSwipeDismissableNavController import com.google.android.horologist.annotations.ExperimentalHorologistApi import com.google.android.horologist.audio.ui.VolumeScreen import com.google.android.horologist.audio.ui.VolumeViewModel import com.google.android.horologist.compose.layout.AppScaffold import com.google.android.horologist.compose.layout.ScreenScaffold import com.google.android.horologist.compose.material.AlertContent import kotlinx.coroutines.launch /** * The logic for the speaker sample. * * The stateful logic is kept by a [MainState]. */ @OptIn(ExperimentalHorologistApi::class) @Composable fun SpeakerApp() { MaterialTheme { lateinit var requestPermissionLauncher: ManagedActivityResultLauncher<String, Boolean> val context = LocalContext.current val activity = context.findActivity() val scope = rememberCoroutineScope() val volumeViewModel: VolumeViewModel = viewModel(factory = VolumeViewModel.Factory) val navController = rememberSwipeDismissableNavController() val mainState = remember(activity) { MainState( activity = activity, requestPermission = { requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO) } ) } requestPermissionLauncher = rememberLauncherForActivityResult(RequestPermission()) { // We ignore the direct result here, since we're going to check anyway. scope.launch { mainState.permissionResultReturned() } } val lifecycleOwner = LocalLifecycleOwner.current AppScaffold { // Notify the state holder whenever we become stopped to reset the state DisposableEffect(mainState, scope, lifecycleOwner) { val lifecycleObserver = object : DefaultLifecycleObserver { override fun onStop(owner: LifecycleOwner) { super.onStop(owner) scope.launch { mainState.onStopped() } } } lifecycleOwner.lifecycle.addObserver(lifecycleObserver) onDispose { lifecycleOwner.lifecycle.removeObserver(lifecycleObserver) } } SwipeDismissableNavHost(navController = navController, startDestination = "speaker") { composable("speaker") { SpeakerRecordingScreen( playbackState = mainState.playbackState, isPermissionDenied = mainState.isPermissionDenied, recordingProgress = mainState.recordingProgress, onMicClicked = { scope.launch { mainState.onMicClicked() } }, onPlayClicked = { navController.navigate("player") } ) if (mainState.showPermissionRationale) { AlertContent( onOk = { requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO) mainState.showPermissionRationale = false }, onCancel = { mainState.showPermissionRationale = false }, title = stringResource( id = R.string.rationale_for_microphone_permission ) ) } if (mainState.showSpeakerNotSupported) { Confirmation( onTimeout = { mainState.showSpeakerNotSupported = false } ) { Text(text = stringResource(id = R.string.no_speaker_supported)) } } } composable("player") { SpeakerPlayerScreen( volumeViewModel = volumeViewModel, onVolumeClick = { navController.navigate("volume") } ) } composable("volume") { ScreenScaffold(timeText = {}) { VolumeScreen(volumeViewModel = volumeViewModel) } } } } } } /** * Find the closest Activity in a given Context. */ tailrec fun Context.findActivity(): Activity = when (this) { is Activity -> this is ContextWrapper -> baseContext.findActivity() else -> throw IllegalStateException( "findActivity should be called in the context of an Activity" ) }
22
Kotlin
573
1,122
473b9ffe4866fe592d6944c419eaf498ed9efccc
6,770
wear-os-samples
Apache License 2.0
clients/android/app/src/main/java/com/example/android/ui/notifications/NotificationsViewModel.kt
ierror
255,703,103
false
null
package com.example.android.ui.notifications import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class NotificationsViewModel : ViewModel() { private val _text = MutableLiveData<String>().apply { value = "This is notifications Fragment\n" + "change tab to fire page view event" } val text: LiveData<String> = _text }
1
Python
0
2
52eecbbe46569809b4fa4ee5738c5210815ca818
416
stream-steam
MIT License
pdfViewer/src/main/java/com/rajat/pdfviewer/util/Enums.kt
afreakyelf
278,914,823
false
{"Kotlin": 104686, "Python": 723}
package com.rajat.pdfviewer.util sealed class DownloadStatus { object Started : DownloadStatus() object Success : DownloadStatus() object Failure : DownloadStatus() data class Progress(val progress: Int) : DownloadStatus() } enum class saveTo { DOWNLOADS, ASK_EVERYTIME }
20
Kotlin
155
717
a2f11aa01fbfa4bdfaee5c7789c6504acb6c519f
298
Pdf-Viewer
MIT License
kotlintest-tests/kotlintest-tests-core/src/test/kotlin/com/sksamuel/kotlintest/matchers/bigdecimal/BigDecimalMatchersTest.kt
mindhaq
199,806,492
true
{"Gradle": 28, "YAML": 2, "Markdown": 12, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 1, "Batchfile": 2, "EditorConfig": 1, "Java": 4, "INI": 4, "Kotlin": 490, "XML": 8, "JSON": 1, "Maven POM": 1}
package com.sksamuel.kotlintest.matchers.bigdecimal import io.kotlintest.matchers.bigdecimal.* import io.kotlintest.specs.StringSpec import java.math.BigDecimal class BigDecimalMatchersTest : StringSpec() { init { "shouldBeZero" { BigDecimal.ZERO.shouldBeZero() BigDecimal(0).shouldBeZero() 0.toBigDecimal().shouldBeZero() } "shouldHavePrecision" { BigDecimal(10).setScale(3) shouldHavePrecision 5 BigDecimal(10.1) shouldHavePrecision 51 10.1.toBigDecimal() shouldHavePrecision 3 BigDecimal.ZERO shouldHavePrecision 1 } "shouldHaveScale" { BigDecimal(10).setScale(3) shouldHaveScale 3 BigDecimal(10.1) shouldHaveScale 49 10.444.toBigDecimal() shouldHaveScale 3 0.toBigDecimal() shouldHaveScale 0 BigDecimal.ZERO shouldHaveScale 0 } "shouldBePositive" { BigDecimal(10).shouldBePositive() BigDecimal.ZERO.shouldBePositive() BigDecimal(0.1).shouldBePositive() 0.1.toBigDecimal().shouldBePositive() } "shouldBeNegative" { BigDecimal(-1).shouldBeNegative() (-1).toBigDecimal().shouldBeNegative() BigDecimal(-0.1).shouldBeNegative() BigDecimal(1).minus(BigDecimal(2)).shouldBeNegative() } } }
0
Kotlin
0
0
f07c8b62e83f214589b1e9ef15295a34b695570e
1,418
kotlintest
Apache License 2.0
posts/src/main/java/com/addhen/checkin/posts/view/PostsBuilder.kt
zularizal
151,024,171
false
null
/* * Copyright (c) 2015 - 2018 Henry Addo * * 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.addhen.checkin.posts.view import androidx.lifecycle.ViewModel import com.addhen.checkin.base.di.module.ViewModelKey import dagger.Binds import dagger.Module import dagger.android.ContributesAndroidInjector import dagger.multibindings.IntoMap @Module abstract class PostsBuilder { @ContributesAndroidInjector abstract fun postsFragment(): PostsFragment @Binds @IntoMap @ViewModelKey(PostsViewModel::class) abstract fun postsViewModel(viewModel: PostsViewModel): ViewModel }
0
Kotlin
1
0
e95e26679ee045456814155b286ae20931f12ff2
1,109
checkin
MIT License
app/src/main/java/org/mp/recipes/data/di/feature/home/HomeActionProcessorHolder.kt
mprasad2510
193,449,283
false
null
package org.mp.recipes.data.di.feature.home import android.util.Log import io.reactivex.Observable import io.reactivex.ObservableTransformer import org.mp.doctorsearchapp.utils.schedulers.BaseSchedulerProvider import org.mp.recipes.data.Repository import org.mp.recipes.data.di.mvibase.MviActionProcessorHolder import javax.inject.Inject class HomeActionProcessorHolder @Inject constructor(private val repository: Repository, private val schedulerProvider: BaseSchedulerProvider ) : MviActionProcessorHolder<HomeAction, HomeResult> { override fun transformFromAction(): ObservableTransformer<HomeAction, HomeResult> { return ObservableTransformer { action -> action.publish { shared -> Observable.merge( shared.ofType(HomeAction.LoadHomeAction::class.java).compose(loadHome()), shared.ofType(HomeAction.ClickAction::class.java).compose(shareArticle()) ) } } } private fun shareArticle(): ObservableTransformer<HomeAction.ClickAction, HomeResult.ClickResult> { return ObservableTransformer { action -> action.flatMap { Observable.just(HomeResult.ClickResult(it.article)) } } } private fun loadHome(): ObservableTransformer<HomeAction.LoadHomeAction, HomeResult.LoadHomeResult> { return ObservableTransformer { action -> action.flatMap { repository.loadList() .toObservable() .map { response -> HomeResult.LoadHomeResult.Success(response.items) } .cast(HomeResult.LoadHomeResult::class.java) .onErrorReturn { t -> HomeResult.LoadHomeResult.Failure(401) } .subscribeOn(schedulerProvider.io()) .observeOn(schedulerProvider.ui()) .startWith(HomeResult.LoadHomeResult.InFlight) } } } }
0
Kotlin
0
0
7e2ddb3ad50ae4308c50e187bcea96d2757c964a
2,187
Recipes
MIT License
integrasjonstest/src/test/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/integrasjonstest/NotifikasjonTrengerInntektMeldingIT.kt
navikt
495,713,363
false
null
package no.nav.helsearbeidsgiver.inntektsmelding.integrasjonstest import com.fasterxml.jackson.module.kotlin.contains import io.mockk.coEvery import no.nav.helsearbeidsgiver.felles.BehovType import no.nav.helsearbeidsgiver.felles.DataFelt import no.nav.helsearbeidsgiver.felles.EventName import no.nav.helsearbeidsgiver.felles.Key import no.nav.helsearbeidsgiver.felles.PersonDato import no.nav.helsearbeidsgiver.felles.json.customObjectMapper import no.nav.helsearbeidsgiver.inntektsmelding.integrasjonstest.utils.EndToEndTest import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.util.UUID class NotifikasjonTrengerInntektMeldingIT : EndToEndTest() { private val FNR = "fnr-123" private val ORGNR = "orgnr-456" private val FORESPOERSEL = UUID.randomUUID().toString() private val SAK_ID = "sak_id_123" private val OPPGAVE_ID = "oppgave_id_456" @BeforeEach fun beforeEach() { resetMessages() } @Test fun `Oppretter og lagrer sak etter at forespørselen er mottatt`() { coEvery { arbeidsgiverNotifikasjonKlient.opprettNySak(any(), any(), any(), any(), any(), any(), any()) } answers { SAK_ID } publish( mapOf( Key.EVENT_NAME.str to EventName.FORESPØRSEL_LAGRET.name, Key.IDENTITETSNUMMER.str to FNR, // Key.UUID.str to TRANSAKSJONS_ID, DataFelt.ORGNRUNDERENHET.str to ORGNR, Key.FORESPOERSEL_ID.str to FORESPOERSEL ) ) Thread.sleep(10000) with(filter(EventName.FORESPØRSEL_LAGRET, BehovType.FULLT_NAVN).first()) { assertEquals(FNR, this[Key.IDENTITETSNUMMER.str].asText()) assertEquals(FORESPOERSEL, this[Key.FORESPOERSEL_ID.str].asText()) } with(filter(EventName.FORESPØRSEL_LAGRET, datafelt = DataFelt.ARBEIDSTAKER_INFORMASJON).first()) { assertNotNull(customObjectMapper().treeToValue(this[DataFelt.ARBEIDSTAKER_INFORMASJON.str], PersonDato::class.java)) } with(filter(EventName.FORESPØRSEL_LAGRET, BehovType.OPPRETT_SAK).first()) { assertEquals(FORESPOERSEL, this[Key.FORESPOERSEL_ID.str].asText()) } with(filter(EventName.FORESPØRSEL_LAGRET, datafelt = DataFelt.SAK_ID).first()) { assertEquals(SAK_ID, this[DataFelt.SAK_ID.str].asText()) assertEquals(FORESPOERSEL, this[Key.FORESPOERSEL_ID.str].asText()) } with(filter(EventName.SAK_OPPRETTET).first()) { assertEquals(SAK_ID, this[DataFelt.SAK_ID.str].asText()) } } @Test fun `Oppretter og lagrer oppgave etter at forespørselen er mottatt`() { coEvery { arbeidsgiverNotifikasjonKlient.opprettNyOppgave(any(), any(), any(), any(), any(), any(), any(), any(), any()) } answers { OPPGAVE_ID } publish( mapOf( Key.EVENT_NAME.str to EventName.FORESPØRSEL_LAGRET.name, DataFelt.ORGNRUNDERENHET.str to ORGNR, Key.FORESPOERSEL_ID.str to FORESPOERSEL ) ) Thread.sleep(8000) var transaksjonsId: String with(filter(EventName.FORESPØRSEL_LAGRET, BehovType.OPPRETT_OPPGAVE).first()) { assertNotNull(this[Key.UUID.str].asText().also { transaksjonsId = this[Key.UUID.str].asText() }) assertEquals(ORGNR, this[DataFelt.ORGNRUNDERENHET.str].asText()) assertEquals(FORESPOERSEL, this[Key.FORESPOERSEL_ID.str].asText()) } with(filter(EventName.FORESPØRSEL_LAGRET, BehovType.PERSISTER_OPPGAVE_ID).first()) { assertEquals(OPPGAVE_ID, this[DataFelt.OPPGAVE_ID.str].asText()) assertEquals(FORESPOERSEL, this[Key.FORESPOERSEL_ID.str].asText()) assertEquals(transaksjonsId, this[Key.UUID.str].asText()) } with(filter(EventName.OPPGAVE_LAGRET).first()) { assertEquals(OPPGAVE_ID, this[DataFelt.OPPGAVE_ID.str].asText()) assertFalse(this.contains(Key.UUID.str)) } } }
7
Kotlin
0
2
8cea9f4e81efbf79d1e0d064a3d23c8f5d2cae14
4,302
helsearbeidsgiver-inntektsmelding
MIT License
plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/anyInReturn.kt
JetBrains
2,489,216
false
null
// "Change return type of enclosing function 'foo' to 'Any'" "true" fun foo() { class A return <caret>A() } // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.ChangeCallableReturnTypeFix$ForEnclosing // FUS_K2_QUICKFIX_NAME: org.jetbrains.kotlin.idea.k2.codeinsight.fixes.ChangeTypeQuickFixFactories$UpdateTypeQuickFix
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
333
intellij-community
Apache License 2.0
app/src/main/java/com/example/b_my_friend/ui/LogoutDialogFragment.kt
maximFenyuk
304,598,098
false
null
package com.example.b_my_friend.ui import android.app.AlertDialog import android.app.Dialog import android.content.Intent import android.os.Bundle import android.util.Log import androidx.fragment.app.DialogFragment import androidx.room.Room import com.example.b_my_friend.R import com.example.b_my_friend.data.SessionManager import com.example.b_my_friend.db.AccountDataBase import com.example.b_my_friend.db.UserDataBase import com.example.b_my_friend.networking.Message import com.example.b_my_friend.networking.NetworkService import com.example.b_my_friend.ui.login.LoginActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import retrofit2.Call import retrofit2.Callback import retrofit2.Response class LogoutDialogFragment : DialogFragment() { private val accountDB: AccountDataBase by lazy { Room.databaseBuilder(requireContext(), AccountDataBase::class.java, "account.db").build() } private val userDB: UserDataBase by lazy { Room.databaseBuilder(requireContext(), UserDataBase::class.java, "user.db").build() } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val sessionManager = SessionManager(requireActivity()) val intent = Intent(requireContext(), LoginActivity::class.java) val builder = AlertDialog.Builder(requireActivity()) builder.setMessage(R.string.dialog_text) .setPositiveButton(R.string.yes) { dialog, which -> intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP logout(sessionManager.fetchAuthToken()!!) GlobalScope.launch{ accountDB.dao().clearAccountInfo() userDB.dao().clearUsers() accountDB.close() userDB.close() } sessionManager.saveAuthToken(null) startActivity(intent) requireActivity().finish() } .setNegativeButton(R.string.no) { dialog, which -> dismiss() } return builder.create() } private fun logout(token: String) { val call = NetworkService().getService().logout("Bearer $token") call.enqueue(object : Callback<Message>{ override fun onResponse(call: Call<Message>, response: Response<Message>) {} override fun onFailure(call: Call<Message>, t: Throwable) {} }) } }
0
Kotlin
0
0
4f4bb1f75beda89d2ffcac7dcc07f6aab1e8bdad
2,473
b-my-friend
MIT License
app/src/main/java/com/gaboardi/githubtest/adapters/common/NetworkStateItemViewHolder.kt
sedestrian
195,600,716
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 76, "JSON": 3, "XML": 23, "Java": 1}
package com.gaboardi.githubtest.adapters.common import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ProgressBar import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.gaboardi.githubtest.R import com.gaboardi.githubtest.model.base.NetworkState import com.gaboardi.githubtest.model.base.Status class NetworkStateItemViewHolder( itemView: View, private val retryCallback: () -> Unit ) : RecyclerView.ViewHolder(itemView) { private val progressBar = itemView.findViewById<ProgressBar>(R.id.progress_bar) private val retry = itemView.findViewById<Button>(R.id.retry_button) private val errorMsg = itemView.findViewById<TextView>(R.id.error_msg) init { retry.setOnClickListener { retryCallback() } } fun bindTo(networkState: NetworkState?) { progressBar.visibility = toVisibility(networkState?.status == Status.RUNNING) retry.visibility = toVisibility(networkState?.status == Status.FAILED) errorMsg.visibility = toVisibility(networkState?.msg != null) errorMsg.text = networkState?.msg } companion object { fun create(parent: ViewGroup, retryCallback: () -> Unit): NetworkStateItemViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.network_state_item, parent, false) return NetworkStateItemViewHolder(view, retryCallback) } fun toVisibility(constraint: Boolean): Int { return if (constraint) { View.VISIBLE } else { View.GONE } } } }
1
null
1
1
237c7182575677013ab39919b7bbf142fa6bf705
1,767
GitHub-Test
MIT License
typescript-kotlin/src/main/kotlin/typescript/isFunctionExpression.fun.kt
turansky
393,199,102
false
null
// Automatically generated - do not modify! @file:JsModule("typescript") @file:JsNonModule package typescript external fun isFunctionExpression(node: Node): Boolean /* node is FunctionExpression */
0
Kotlin
1
10
bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0
201
react-types-kotlin
Apache License 2.0
src/main/java/pers/shawxingkwok/ktutil/MutableList.swap.kt
ShawxingKwok
660,855,232
false
null
package pers.shawxingkwok.ktutil /** * Swap values between those at [i] and [j]. * * Usage example: * * ``` * mutableListOf(1, 2, 3).apply{ swap(0, 2) } // 3, 2, 1 */ public fun <E> MutableList<E>.swap(i: Int, j: Int){ this[i] = this[j].also { this[j] = this[i] } }
0
Kotlin
0
0
e6f87523040dfba3c68713019fd4cfd32f57efe2
277
KtUtil
Apache License 2.0
Meld-Module-Entities/src/main/kotlin/io/github/daylightnebula/meld/entities/LivingEntity.kt
DaylightNebula
652,923,400
false
{"Kotlin": 199201, "Python": 792}
package io.github.daylightnebula.meld.entities import io.github.daylightnebula.meld.entities.metadata.EntityMetadata import io.github.daylightnebula.meld.entities.metadata.entityMetadata import org.cloudburstmc.math.vector.Vector2f import org.cloudburstmc.math.vector.Vector3f import java.util.* abstract class LivingEntity( uid: UUID = UUID.randomUUID(), id: Int = EntityController.nextID(), type: EntityType = EntityType.ARMOR_STAND, metadata: EntityMetadata = entityMetadata(), dimension: String = "overworld", position: Vector3f = Vector3f.from(0.0, 0.0, 0.0), startVelocity: Vector3f = Vector3f.ZERO, startRotation: Vector2f = Vector2f.ZERO, var headYaw: Float = 0f, val health: Health = Health(1.0) ): Entity( uid, id, type, metadata, dimension, position, startVelocity, startRotation ) class Health( private val maxHealth: Double = 1.0, private var health: Double = maxHealth ) { fun setHealth(health: Double) { this.health = health } }
0
Kotlin
0
1
2290a5266ae56ef2e59cad88fc1f38e825b2cc88
1,002
Meld
Apache License 2.0
bitcoinkit/src/main/kotlin/io/horizontalsystems/bitcoinkit/blocks/MerkleBlockExtractor.kt
diop
180,641,789
true
{"Kotlin": 544801, "Java": 48890}
package io.horizontalsystems.bitcoinkit.blocks import io.horizontalsystems.bitcoinkit.core.toHexString import io.horizontalsystems.bitcoinkit.models.MerkleBlock import io.horizontalsystems.bitcoinkit.network.messages.MerkleBlockMessage import io.horizontalsystems.bitcoinkit.utils.MerkleBranch class MerkleBlockExtractor(private val maxBlockSize: Int) { fun extract(message: MerkleBlockMessage): MerkleBlock { val matchedHashes = mutableListOf<ByteArray>() val merkleRoot = MerkleBranch().calculateMerkleRoot(message.txCount, message.hashes, message.flags, matchedHashes) message.apply { if (txCount < 1 || txCount > maxBlockSize / 60) { throw InvalidMerkleBlockException(String.format("Transaction count %d is not valid", txCount)) } if (hashCount < 0 || hashCount > txCount) { throw InvalidMerkleBlockException(String.format("Hash count %d is not valid", hashCount)) } if (flagsCount < 1) { throw InvalidMerkleBlockException(String.format("Flag count %d is not valid", flagsCount)) } if (!header.merkleRoot.contentEquals(merkleRoot)) { throw InvalidMerkleBlockException("Merkle root is not valid") } } return MerkleBlock(message.header, matchedHashes.map { it.toHexString() }) } } class InvalidMerkleBlockException(message: String) : Exception(message)
0
Kotlin
0
0
fb11666b177815e0210c4d6072f201101151acdc
1,472
bitcoin-kit-android
MIT License
app/src/main/java/com/eugenio/marvelsuperheroes/core/data/Routes.kt
EugenioGutierrezC
696,859,384
false
{"Kotlin": 75462}
package com.eugenio.marvelsuperheroes.core.data sealed class Routes(val route: String) { object CharactersList: Routes("charactersList") object CharacterDetail: Routes("characterDetail/{characterId}") { fun createRoute(characterId: Int) = "characterDetail/$characterId" } }
0
Kotlin
0
0
ab95e890d20330809d51266b760942bd1ce8cdd4
294
MarvelSuperHeroes
Apache License 2.0
buildSrc/src/main/kotlin/Dependencies.kt
play-iot
340,598,938
false
null
import org.gradle.api.Project object PluginLibs { object Version { const val jvm = "1.5.31" const val sonarQube = "3.3" const val nexusPublish = "1.1.0" const val gradlePluginPublish = "0.18.0" const val jacocoLogger = "2.0.0" const val testLogger = "3.1.0" const val jooq = "5.2.1" const val docker = "7.4.0" const val shadow = "6.1.0" const val testcontainers = "1.17.3" const val yaml = "1.30" } const val sonarQube = "org.sonarqube" const val nexusPublish = "io.github.gradle-nexus.publish-plugin" const val gradlePluginPublish = "com.gradle.plugin-publish" const val jvm = "jvm" object Depends { const val docker = "com.bmuschko:gradle-docker-plugin:${Version.docker}" const val jacocoLogger = "gradle.plugin.org.barfuin.gradle.jacocolog:gradle-jacoco-log:${Version.jacocoLogger}" const val nexusPublish = "io.github.gradle-nexus:publish-plugin:${Version.nexusPublish}" const val sonarQube = "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:${Version.sonarQube}" const val shadow = "com.github.jengelman.gradle.plugins:shadow:${Version.shadow}" const val testLogger = "com.adarshr:gradle-test-logger-plugin:${Version.testLogger}" const val yaml = "org.yaml:snakeyaml:${Version.yaml}" const val jooq = "nu.studer:gradle-jooq-plugin:${Version.jooq}" const val testcontainers = "org.testcontainers:testcontainers:${Version.testcontainers}" } } object TestLibs { object Version { const val junit5 = "5.7.0" } const val junit5Api = "org.junit.jupiter:junit-jupiter-api:${Version.junit5}" const val junit5Engine = "org.junit.jupiter:junit-jupiter-engine:${Version.junit5}" } fun prop(project: Project, key: String, fallback: String = ""): String { return if (project.hasProperty(key)) project.property(key) as String? ?: fallback else fallback }
7
Kotlin
0
0
745114919875223760cffb90c7e307f9a3591b1f
1,988
gradle-plugin
Apache License 2.0
app/src/main/java/com/beam/todo_app/addTask/domain/AddTasksUseCase.kt
breduarm
795,098,204
false
{"Kotlin": 19575}
package com.beam.todo_app.addTask.domain import com.beam.todo_app.addTask.data.TaskRepository import com.beam.todo_app.addTask.presentation.model.TaskModel import javax.inject.Inject class AddTasksUseCase @Inject constructor( private val taskRepository: TaskRepository ) { suspend operator fun invoke(task: TaskModel) { taskRepository.create(task) } }
0
Kotlin
0
0
e4227505283910c3a6028e914a6e0a00f93b9e4a
373
todo_app
Apache License 2.0
UIDemo/app/src/main/java/ch/hslu/informatik/mobpro/ui_demo/MainActivity.kt
kevinforter
773,829,665
false
{"Kotlin": 17373, "HTML": 9513}
package ch.hslu.informatik.mobpro.ui_demo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(R.id.activity_main_fragment_container, MainFragment.newInstance()) .commit() } } }
0
Kotlin
0
0
0df379901396f8eab8ecf6e850b8305f52fc93a9
540
mobpro_workspace
MIT License
src/main/kotlin/no/nav/pensjon/simulator/core/domain/regler/beregning2011/MinstePensjonsniva.kt
navikt
753,551,695
false
{"Kotlin": 1687999, "Java": 2774, "Dockerfile": 144}
package no.nav.pensjon.simulator.core.domain.regler.beregning2011 import com.fasterxml.jackson.annotation.JsonIgnore import no.nav.pensjon.simulator.core.domain.regler.Merknad import no.nav.pensjon.simulator.core.domain.regler.kode.FormelKodeCti import no.nav.pensjon.simulator.core.domain.regler.kode.MinstepenNivaCti import java.io.Serializable class MinstePensjonsniva : Serializable { var belop: Double = 0.0 var sats: Double = 0.0 var benyttetYug: Int? = null var pro_rata_teller_mnd: Int = 0 var pro_rata_nevner_mnd: Int = 0 var pro_rata_brok: Double = 0.0 var formelKode: FormelKodeCti? = null /** * Minstepensjonsnivå. Kan være lav, ordinær og forhøyet. Benytter tabellen */ var satsType: MinstepenNivaCti? = null var merknadListe: MutableList<Merknad> = mutableListOf() var faktisk_tt_avtaleland_mnd: Int = 0 @JsonIgnore var belopIkkeProratisert: Double = 0.0 constructor() : super() { formelKode = FormelKodeCti("MPNx") } constructor(mpn: MinstePensjonsniva) : super() { belop = mpn.belop sats = mpn.sats benyttetYug = mpn.benyttetYug pro_rata_teller_mnd = mpn.pro_rata_teller_mnd pro_rata_nevner_mnd = mpn.pro_rata_nevner_mnd pro_rata_brok = mpn.pro_rata_brok if (mpn.satsType != null) { satsType = MinstepenNivaCti(mpn.satsType) } if (mpn.formelKode != null) { formelKode = FormelKodeCti(mpn.formelKode!!) } for (merknad in mpn.merknadListe) { merknadListe.add(Merknad(merknad)) } belopIkkeProratisert = mpn.belopIkkeProratisert faktisk_tt_avtaleland_mnd = mpn.faktisk_tt_avtaleland_mnd } constructor( belop: Double = 0.0, sats: Double = 0.0, benyttetYug: Int = 0, pro_rata_teller_mnd: Int = 0, pro_rata_nevner_mnd: Int = 0, pro_rata_brok: Double = 0.0, formelKode: FormelKodeCti? = null, satsType: MinstepenNivaCti? = null, merknadListe: MutableList<Merknad> = mutableListOf(), faktisk_tt_avtaleland_mnd: Int = 0, belopIkkeProratisert: Double = 0.0 ) { this.belop = belop this.sats = sats this.benyttetYug = benyttetYug this.pro_rata_teller_mnd = pro_rata_teller_mnd this.pro_rata_nevner_mnd = pro_rata_nevner_mnd this.pro_rata_brok = pro_rata_brok this.formelKode = formelKode this.satsType = satsType this.merknadListe = merknadListe this.faktisk_tt_avtaleland_mnd = faktisk_tt_avtaleland_mnd this.belopIkkeProratisert = belopIkkeProratisert } }
1
Kotlin
0
0
1f7f146757ea054e29a6d82aa656cb21c9c61961
2,691
pensjonssimulator
MIT License
browser-kotlin/src/jsMain/kotlin/web/codecs/VideoDecoderInit.kt
karakum-team
393,199,102
false
{"Kotlin": 6914539}
// Automatically generated - do not modify! package web.codecs import js.objects.JsPlainObject @JsPlainObject sealed external interface VideoDecoderInit { var error: WebCodecsErrorCallback var output: VideoFrameOutputCallback }
0
Kotlin
7
31
c3de7c4098277a67bd40a9f0687579a6b9956cb2
239
types-kotlin
Apache License 2.0
src/main/kotlin/no/nav/familie/ef/sak/service/CachedKodeverkService.kt
blommish
359,371,467
false
{"YAML": 13, "Ignore List": 2, "CODEOWNERS": 1, "Maven POM": 1, "Dockerfile": 1, "Text": 1, "Markdown": 1, "XML": 4, "JSON": 21, "Kotlin": 394, "Java": 1, "GraphQL": 8, "SQL": 43, "Shell": 1}
package no.nav.familie.ef.sak.service import no.nav.familie.ef.sak.integration.FamilieIntegrasjonerClient import no.nav.familie.kontrakter.felles.kodeverk.KodeverkDto import org.slf4j.LoggerFactory import org.springframework.boot.context.event.ApplicationReadyEvent import org.springframework.cache.annotation.CacheConfig import org.springframework.cache.annotation.Cacheable import org.springframework.context.ApplicationListener import org.springframework.context.annotation.Profile import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import org.springframework.stereotype.Service @Service @CacheConfig(cacheManager = "kodeverkCache") class CachedKodeverkService(private val familieIntegrasjonerClient: FamilieIntegrasjonerClient) { @Cacheable("kodeverk_landkoder") fun hentLandkoder(): KodeverkDto { return familieIntegrasjonerClient.hentKodeverkLandkoder() } @Cacheable("kodeverk_poststed") fun hentPoststed(): KodeverkDto { return familieIntegrasjonerClient.hentKodeverkPoststed() } } @Profile("!integrasjonstest") @Component class KodeverkInitializer(private val cachedKodeverkService: CachedKodeverkService) : ApplicationListener<ApplicationReadyEvent> { private val logger = LoggerFactory.getLogger(this::class.java) @Scheduled(cron = "0 0 2 * * *") fun syncKodeverk() { logger.info("Kjører schedulert jobb for å hente kodeverk"); sync() } override fun onApplicationEvent(p0: ApplicationReadyEvent) { sync() } private fun sync() { syncKodeverk("Lantkoder", cachedKodeverkService::hentLandkoder) syncKodeverk("Poststed", cachedKodeverkService::hentPoststed) } private fun syncKodeverk(navn: String, henter: () -> Unit) { try { logger.info("Henter $navn") henter.invoke() } catch (e: Exception) { logger.warn("Feilet henting av $navn ${e.message}") } } }
1
null
1
1
0e850df593c82a910c68c2393e6d2f30fc49eaa7
2,006
familie-ef-sak
MIT License
app/src/main/java/tw/tonyyang/englishwords/ui/base/BaseRecyclerViewHolder.kt
tonyydl
166,625,004
false
null
package tw.tonyyang.englishwords.ui.base import android.view.View import androidx.recyclerview.widget.RecyclerView open class BaseRecyclerViewHolder(itemView: View, onRecyclerViewListener: OnRecyclerViewListener): RecyclerView.ViewHolder(itemView) { init { itemView.setOnClickListener { onRecyclerViewListener.onItemClick(it, absoluteAdapterPosition) } itemView.setOnLongClickListener { return@setOnLongClickListener onRecyclerViewListener.onItemLongClick( it, absoluteAdapterPosition ) } } }
0
Kotlin
1
0
dedfb050f8aea0974622803df395d2aae4767bad
602
EnglishWords
Apache License 2.0
app/src/main/java/com/cactus/pokemon/CustomApplication.kt
rafaelkapi
817,537,357
false
{"Kotlin": 48818}
/* * Copyright (c) * 2018-2021 XP Inc * All Rights Reserved */ package com.cactus.pokemon import com.cactus.pokemon.di.AppComponent import com.cactus.pokemon.di.DaggerAppComponent import dagger.android.AndroidInjector import dagger.android.DaggerApplication class CustomApplication : DaggerApplication() { private lateinit var appComponent: AppComponent override fun applicationInjector(): AndroidInjector<out DaggerApplication> { appComponent = DaggerAppComponent .builder() .application(this) .build() appComponent.inject(this) return appComponent } }
0
Kotlin
0
0
fdbe69fd08e72dc1c96db476e4576dc246c9a8b9
634
PokemonApp
MIT License
libraries/core-utils/src/main/java/id/nz/template/mvvm/core/extension/DataExt.kt
Source-Set-564
211,533,076
false
null
package id.nz.template.mvvm.core.extension import com.google.gson.Gson import com.google.gson.reflect.TypeToken /** * Created by Anwar on 10/7/2019. */ fun Any.jsonify() : String{ return Gson().toJson(this) } fun <T> makeFromJson(json : String, refered : Class<T>) : T{ return Gson().fromJson(json,refered) }
0
Kotlin
0
2
59bb69f0f2e3231064fdb516fe29d18af3e07219
322
Android-MVVM-Sample-Kotlin
MIT License
app/src/main/java/com/allat/mboychenko/silverthread/utils/UpdateAppFunctions.kt
glmcz
269,649,668
true
{"Kotlin": 494342}
package com.allat.mboychenko.silverthread.utils import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.work.WorkManager import com.allat.mboychenko.silverthread.BuildConfig import com.allat.mboychenko.silverthread.data.storage.preferences.Storage import com.allat.mboychenko.silverthread.data.storage.preferences.StorageImplementation import com.allat.mboychenko.silverthread.domain.interactor.FileLoaderDetailsInteractor import com.allat.mboychenko.silverthread.presentation.helpers.* import com.allat.mboychenko.silverthread.presentation.services.EveryDayWork.Companion.DAILY_TIMERS_CHECKER_WORK_TAG fun updateVersion(context: Context, workManager: WorkManager) { runTaskOnBackground(ExecutorThread.IO) { val storage: Storage = StorageImplementation(context) val lastUpdatedVersion = storage.getIntDefault(LAST_UPDATE_VERSION_PREF, 0) if (lastUpdatedVersion < BuildConfig.VERSION_CODE) { updateScript(context, storage, workManager) } storage.putInt(LAST_UPDATE_VERSION_PREF, BuildConfig.VERSION_CODE) } } private fun updateScript(context: Context, storage: Storage, workManager: WorkManager) { if (!storage.getBoolean(PATCH_25_APPLIED_PREF_KEY, false)) { applyPatchVer25(context, storage) storage.putBoolean(PATCH_25_APPLIED_PREF_KEY, true) } if (!storage.getBoolean(PATCH_45_APPLIED_PREF_KEY, false)) { applyPatchVer45(workManager) storage.putBoolean(PATCH_45_APPLIED_PREF_KEY, true) } } private fun applyPatchVer25(context: Context, storage: Storage) { val deprecatedPref = "BOOKS_DOWNLOADS_IDS_PREF_KEY" val oldDownloads: Map<String, Long> = storage.getMap(deprecatedPref) oldDownloads.isEmpty().let { empty -> if(!empty) { FileLoaderDetailsInteractor(storage).putAllLoadingIds(oldDownloads) } } storage.remove(deprecatedPref) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val nManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nManager.deleteNotificationChannel("quotes_notif") } } private fun applyPatchVer45(wm: WorkManager) { wm.cancelUniqueWork(DAILY_TIMERS_CHECKER_WORK_TAG) } private const val LAST_UPDATE_VERSION_PREF = "LAST_UPDATE_VERSION_PREF" private const val PATCH_25_APPLIED_PREF_KEY = "PATCH_25_APPLIED_PREF_KEY" private const val PATCH_45_APPLIED_PREF_KEY = "PATCH_45_APPLIED_PREF_KEY"
0
null
0
0
4928d888e025188ab854f59121b54acfc4c06265
2,508
SilverThread
Apache License 2.0
src/main/kotlin/ru/krindra/vknorthtypes/newsfeed/NewsfeedItemPhotoTagPhotoTags.kt
kravandir
745,597,090
false
{"Kotlin": 633233}
package ru.krindra.vknorthtypes.newsfeed import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import ru.krindra.vknorthtypes.photos.PhotosPhoto @Serializable data class NewsfeedItemPhotoTagPhotoTags ( @SerialName("items") val items: List<PhotosPhoto>? = null, @SerialName("count") val count: Int? = null, )
0
Kotlin
0
0
508d2d1d59c4606a99af60b924c6509cfec6ef6c
346
VkNorthTypes
MIT License
java/kotlin/src/main/kotlin/ibc/lightclients/solomachine/v2/PacketAcknowledgementDataKt.kt
dimitar-petrov
575,395,653
false
null
//Generated by the protocol buffer compiler. DO NOT EDIT! // source: ibc/lightclients/solomachine/v1/solomachine.proto package ibc.lightclients.solomachine.v1; @kotlin.jvm.JvmSynthetic inline fun packetAcknowledgementData(block: ibc.lightclients.solomachine.v1.PacketAcknowledgementDataKt.Dsl.() -> Unit): ibc.lightclients.solomachine.v1.Solomachine.PacketAcknowledgementData = ibc.lightclients.solomachine.v1.PacketAcknowledgementDataKt.Dsl._create(ibc.lightclients.solomachine.v1.Solomachine.PacketAcknowledgementData.newBuilder()).apply { block() }._build() object PacketAcknowledgementDataKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker class Dsl private constructor( @kotlin.jvm.JvmField private val _builder: ibc.lightclients.solomachine.v1.Solomachine.PacketAcknowledgementData.Builder ) { companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: ibc.lightclients.solomachine.v1.Solomachine.PacketAcknowledgementData.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): ibc.lightclients.solomachine.v1.Solomachine.PacketAcknowledgementData = _builder.build() /** * <code>bytes path = 1;</code> */ var path: com.google.protobuf.ByteString @JvmName("getPath") get() = _builder.getPath() @JvmName("setPath") set(value) { _builder.setPath(value) } /** * <code>bytes path = 1;</code> */ fun clearPath() { _builder.clearPath() } /** * <code>bytes acknowledgement = 2;</code> */ var acknowledgement: com.google.protobuf.ByteString @JvmName("getAcknowledgement") get() = _builder.getAcknowledgement() @JvmName("setAcknowledgement") set(value) { _builder.setAcknowledgement(value) } /** * <code>bytes acknowledgement = 2;</code> */ fun clearAcknowledgement() { _builder.clearAcknowledgement() } } } @kotlin.jvm.JvmSynthetic inline fun ibc.lightclients.solomachine.v1.Solomachine.PacketAcknowledgementData.copy(block: ibc.lightclients.solomachine.v1.PacketAcknowledgementDataKt.Dsl.() -> Unit): ibc.lightclients.solomachine.v1.Solomachine.PacketAcknowledgementData = ibc.lightclients.solomachine.v1.PacketAcknowledgementDataKt.Dsl._create(this.toBuilder()).apply { block() }._build()
1
Kotlin
0
0
fe9795120e37a7223f331f48c0dd18c29e6e7cac
2,475
terra.proto
Apache License 2.0
Android/App_YanZiJi/Lib_SerialPort/src/main/java/com/zktony/serialport/protocol/RtuProtocol.kt
OriginalLight
556,213,614
false
{"Kotlin": 6123849, "C#": 376657, "Vue": 164353, "Rust": 101266, "C++": 63250, "TypeScript": 62359, "Python": 28781, "CMake": 18271, "C": 16214, "Less": 2885, "Dockerfile": 1898, "HTML": 648, "JavaScript": 450}
package com.zktony.serialport.protocol import com.zktony.serialport.ext.crc16LE import com.zktony.serialport.ext.toHexString /** * Modbus RTU 协议 */ data class RtuProtocol( var target: Byte = 0x01, var func: Byte = 0x03, var data: ByteArray = byteArrayOf(), val crc: ByteArray = byteArrayOf(0x00.toByte(), 0x00.toByte()) ) { // 生成协议 fun toByteArray(): ByteArray { val byteArray = byteArrayOf(target, func).plus(data) return byteArray.plus(byteArray.crc16LE()) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RtuProtocol if (target != other.target) return false if (func != other.func) return false if (!data.contentEquals(other.data)) return false if (!crc.contentEquals(other.crc)) return false return true } override fun hashCode(): Int { var result = target.hashCode() result = 31 * result + func.hashCode() result = 31 * result + data.contentHashCode() result = 31 * result + crc.contentHashCode() return result } companion object { /** * 解析协议 * @param byteArray ByteArray * @return RtuProtocol */ fun toObject(byteArray: ByteArray): RtuProtocol { try { return RtuProtocol( target = byteArray[0], func = byteArray[1], data = byteArray.copyOfRange(2, byteArray.size - 2), crc = byteArray.copyOfRange(byteArray.size - 2, byteArray.size) ) } catch (e: Exception) { error("to RtuProtocol error by ${byteArray.toHexString()}") } } /** * Verify the protocol * @param byteArray ByteArray * @param block Function1<[@kotlin.ParameterName] RtuProtocol, Unit> * @throws Exception */ @kotlin.jvm.Throws(Exception::class) fun verifyProtocol(byteArray: ByteArray, block: (RtuProtocol) -> Unit) { // crc 校验 val crc = byteArray.copyOfRange(byteArray.size - 2, byteArray.size) val bytes = byteArray.copyOfRange(0, byteArray.size - 2) if (!bytes.crc16LE().contentEquals(crc)) { error("rx crc error by ${byteArray.toHexString()}") } block(toObject(byteArray)) } } }
0
Kotlin
0
1
bcf0671b9e4ad199e579764f29683c1c575369d2
2,511
ZkTony
Apache License 2.0
vector/src/main/java/vmodev/clearkeep/di/AbstractUnifiedSearchActivityFragmentsBuilderModule.kt
telred-llc
194,596,139
false
null
package vmodev.clearkeep.di import dagger.Binds import dagger.Module import dagger.android.ContributesAndroidInjector import vmodev.clearkeep.factories.viewmodels.SearchFilesFragmentViewModelFactory import vmodev.clearkeep.factories.viewmodels.SearchFilesInRoomFragmentViewModelFactory import vmodev.clearkeep.factories.viewmodels.SearchMessageInRoomFragmentViewModelFactory import vmodev.clearkeep.factories.viewmodels.interfaces.IViewModelFactory import vmodev.clearkeep.fragments.Interfaces.IFragment import vmodev.clearkeep.fragments.SearchFilesFragment import vmodev.clearkeep.fragments.SearchFilesInRoomFragment import vmodev.clearkeep.fragments.SearchMessagesInRoomFragment import vmodev.clearkeep.viewmodels.interfaces.AbstractSearchFilesFragmentViewModel import vmodev.clearkeep.viewmodels.interfaces.AbstractSearchFilesInRoomFragmentViewModel import vmodev.clearkeep.viewmodels.interfaces.AbstractSearchMessageInroomFragmentViewModel import javax.inject.Named @Module @Suppress("unused") abstract class AbstractUnifiedSearchActivityFragmentsBuilderModule { @ContributesAndroidInjector(modules = [FragmentSearchMessageInRoomBindModule::class]) abstract fun contributeSearchMessageInRoomFragment(): SearchMessagesInRoomFragment; @ContributesAndroidInjector(modules = [FragmentSearchFileInRoomBindModule::class]) abstract fun contributeSearchFilesInRoomFragment(): SearchFilesInRoomFragment; @Module abstract class FragmentSearchMessageInRoomBindModule { @Binds @Named(IFragment.SEARCH_MESSAGE_IN_ROOM_FRAGMENT) abstract fun bindSearchMessagesInRoomFragment(fragment: SearchMessagesInRoomFragment): IFragment; @Binds abstract fun bindSearchMessageInRoomFragmentViewModelFactory(factory: SearchMessageInRoomFragmentViewModelFactory): IViewModelFactory<AbstractSearchMessageInroomFragmentViewModel>; } @Module abstract class FragmentSearchFileInRoomBindModule { @Binds @Named(IFragment.SEARCH_FILES_IN_ROOM_FRAGMENT) abstract fun bindSearchFilesInRoomFragment(fragment: SearchFilesInRoomFragment): IFragment; @Binds abstract fun bindSearchFilesInRoomFragmentViewModelFactory(factory: SearchFilesInRoomFragmentViewModelFactory): IViewModelFactory<AbstractSearchFilesInRoomFragmentViewModel>; } }
5
null
1
3
2d20e94e9711b51aee89fa569efd61449cc7e9c3
2,328
clearkeep-android
Apache License 2.0
core/src/main/java/com/mohfahmi/storyapp/core/data/repository/story/StoryRepository.kt
MohFahmi27
535,535,970
false
{"Kotlin": 147264}
package com.mohfahmi.storyapp.core.data.repository.story import androidx.lifecycle.LiveData import androidx.paging.* import com.mohfahmi.storyapp.core.data.source.StoryRemoteMediator import com.mohfahmi.storyapp.core.data.source.local.database.StoryDatabase import com.mohfahmi.storyapp.core.data.source.remote.IRemoteDataSource import com.mohfahmi.storyapp.core.data.source.remote.api.ApiService import com.mohfahmi.storyapp.core.domain.models.Story import com.mohfahmi.storyapp.core.domain.models.UploadStory import com.mohfahmi.storyapp.core.utils.ApiResponse import com.mohfahmi.storyapp.core.utils.toMultipartBody import kotlinx.coroutines.flow.Flow import okhttp3.MultipartBody import java.io.File class StoryRepository( private val storyDatabase: StoryDatabase, private val remoteDataSource: IRemoteDataSource, private val apiService: ApiService ) : IStoryRepository { @OptIn(ExperimentalPagingApi::class) override fun getAllStories(token: String): LiveData<PagingData<Story>> { return Pager( config = PagingConfig( pageSize = NETWORK_PAGE_SIZE ), remoteMediator = StoryRemoteMediator(storyDatabase, apiService, "Bearer $token"), pagingSourceFactory = { storyDatabase.storyDao().getAllStories() } ).liveData } override fun getAllWithStories(token: String): Flow<ApiResponse<ArrayList<Story>>> = remoteDataSource.getStoriesWithLocation("Bearer $token") override fun postStory( token: String, description: String, imgStory: File, lat: Double?, lon: Double?, ): Flow<ApiResponse<UploadStory>> { return if (lat == null) { remoteDataSource.uploadStory( "Bearer $token", MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("description", description) .addPart(imgStory.toMultipartBody("photo")) .build() ) } else { remoteDataSource.uploadStory( "Bearer $token", MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("description", description) .addPart(imgStory.toMultipartBody("photo")) .addFormDataPart("lat", lat.toString()) .addFormDataPart("lon", lon.toString()) .build() ) } } private companion object { const val NETWORK_PAGE_SIZE = 5 } }
0
Kotlin
0
3
33e94844c52da1ad24f68e204dc0e220d564c4c4
2,634
MyIntermediateAndroidSubmission
Apache License 2.0
app/src/main/java/com/oyamo/dooka_app/feature_profile/domain/model/Account.kt
oyamo
542,376,763
false
{"Kotlin": 135390}
package com.oyamo.dooka_app.feature_profile.domain.model data class Account( val title: String, val content: String )
0
Kotlin
1
0
f441810c7a49ef1d1e9546e4f62bda4d1b608f8e
126
Dooka
Apache License 2.0
client/client-hci/src/commonMain/kotlin/de/jlnstrk/transit/api/hci/model/composition/HciStcLeavingDirection.kt
jlnstrk
229,599,180
false
{"Kotlin": 729374}
package de.jlnstrk.transit.api.hci.model.composition import de.jlnstrk.transit.api.hafas.HciModel import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @HciModel("1.39") @Serializable public enum class HciStcLeavingDirection { @SerialName("L") LEFT, @SerialName("N") NONE, @SerialName("R") RIGHT, }
0
Kotlin
0
0
9f700364f78ebc70b015876c34a37b36377f0d9c
354
transit
Apache License 2.0
vxutil-vertigram/src/main/kotlin/ski/gagar/vxutil/vertigram/types/ForumTopicReopened.kt
gagarski
314,041,476
false
{"Kotlin": 361258}
package ski.gagar.vxutil.vertigram.types data object ForumTopicReopened
0
Kotlin
0
0
3ee5ab95995c0df14c25cec2b13b62614bcfabea
73
vertigram
Apache License 2.0
app/src/main/java/com/izhal/dicodingsubmission3/db/UserHelper.kt
izhal27
306,797,752
false
null
package com.izhal.dicodingsubmission3.db import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import com.izhal.dicodingsubmission3.db.DatabaseContract.UserColumns.Companion.LOGIN import com.izhal.dicodingsubmission3.db.DatabaseContract.UserColumns.Companion.TABLE_NAME import com.izhal.dicodingsubmission3.db.DatabaseContract.UserColumns.Companion._ID import java.sql.SQLException class UserHelper(context: Context) { companion object { private const val DB_TABLE = TABLE_NAME private lateinit var dbHelper: DatabaseContract.DatabaseHelper private lateinit var db: SQLiteDatabase private var INSTANCE: UserHelper? = null fun getInstance(context: Context): UserHelper = INSTANCE ?: synchronized(this) { INSTANCE ?: UserHelper(context) } } init { dbHelper = DatabaseContract.DatabaseHelper(context) } @Throws(SQLException::class) fun open() { db = dbHelper.writableDatabase } fun isOpen(): Boolean { return db.isOpen() } fun close() { dbHelper.close() if (db.isOpen) { db.close() } } fun getAll(): Cursor { return db.query( DB_TABLE, null, null, null, null, null, "$_ID ASC" ) } fun getById(id: String): Cursor { return db.query( DB_TABLE, null, "$_ID = ?", arrayOf(id), null, null, null, null ) } fun getByLoginId(loginId: String): Cursor { return db.query( DB_TABLE, null, "$LOGIN = ?", arrayOf(loginId), null, null, null, null ) } fun insert(values: ContentValues?): Long { return db.insert(DB_TABLE, null, values) } fun update(id: String, values: ContentValues?): Int { return db.update(DB_TABLE, values, "$_ID = ?", arrayOf(id)) } fun delete(id: String): Int { return db.delete(DB_TABLE, "$_ID = ?", arrayOf(id)) } fun deleteByLogin(loginId: String): Int { return db.delete(DB_TABLE, "$LOGIN = ?", arrayOf(loginId)) } }
0
Kotlin
0
0
3678024e23694966b1901712277a1ab6f7abaaa9
2,119
dicoding-submission-3
MIT License
conductor-modules/codegen-lint/src/main/java/com/lalafo/codegen/lint/constants.kt
lalafo-dev
248,189,821
true
{"Gradle": 13, "Markdown": 3, "Java Properties": 5, "Shell": 2, "Ignore List": 4, "Batchfile": 1, "Text": 2, "YAML": 1, "INI": 4, "Java": 109, "XML": 48, "Kotlin": 23, "Proguard": 1}
/* * Copyright 2020 Lalafo. * * 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.lalafo.codegen.lint internal object Constants { const val LIB_NAME = "'conductor-codegen'" object Annotations { const val CONTROLLER_BUNDLE = "com.lalafo.codegen.injection.ControllerBundle" const val CONTROLLER_INJECT = "com.lalafo.codegen.injection.InjectController" const val CONTROLLER_INJECT_FACTORY = "com.lalafo.codegen.injection.InjectController.Factory" const val KOTLIN_NULLABLE = "org.jetbrains.annotations.Nullable" const val ANDROID_NULLABLE = "androidx.annotation.Nullable" const val INJECT = "javax.inject.Inject" } object Conductor { const val CONTROLLER = "com.bluelinelabs.conductor.Controller" const val CONTROLLER_ARGS = "com.bluelinelabs.conductor.ControllerArgs" } }
2
Java
0
10
84eb0716927f86270610304ea1f8082e99bdd9b2
1,381
Conductor
Apache License 2.0
app/src/main/java/ir/nima/navigationcomponent/FragmentHomeButten.kt
nimasaeedvand
724,579,107
false
{"Kotlin": 21608}
package ir.nima.navigationcomponent import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import ir.nima.navigationcomponent.databinding.DeletItemBinding import ir.nima.navigationcomponent.databinding.EdtTaskBinding import ir.nima.navigationcomponent.databinding.FragmentHome2Binding // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [FragmentHomeButten.newInstance] factory method to * create an instance of this fragment. */ class FragmentHomeButten : Fragment() , Godata ,evant{ lateinit var binding: FragmentHome2Binding lateinit var datalist:ArrayList<data> lateinit var adaptor: Adaptor override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentHome2Binding.inflate(layoutInflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { datalist = arrayListOf(data("go gym" , "1402/2/8") , data("simple" , "1402/8/9")) adaptor = Adaptor(datalist,this) binding.rrcyclerMain.adapter = adaptor binding.rrcyclerMain.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false) binding.fabMain.setOnClickListener{ val dialog = Fragment_add(this) dialog.show(childFragmentManager,null) } binding.rrcyclerMain.setOnClickListener { Toast.makeText(context, "item select", Toast.LENGTH_SHORT).show() } } override fun GOdata(date: String, task: String) { val newtask = data(task, date) adaptor.addnewtask(newtask) } override fun longclick(data: data, position: Int) { val dialog = AlertDialog.Builder(requireContext()).create() val dialogDeleteBinding = DeletItemBinding.inflate(layoutInflater) dialog.setView(dialogDeleteBinding.root) dialog.setCancelable(true) dialog.show() dialogDeleteBinding.btnNo.setOnClickListener { dialog.dismiss() } dialogDeleteBinding.btnYes.setOnClickListener { adaptor.deletItem(data , position) dialog.dismiss() } } override fun onClick(data: data, position: Int) { val dialog = AlertDialog.Builder(requireContext()).create() val dialogDeleteBinding = EdtTaskBinding.inflate(layoutInflater) dialog.setView(dialogDeleteBinding.root) dialog.setCancelable(true) dialogDeleteBinding.edtDate.setText(data.time) dialogDeleteBinding.edtNewtask.setText(data.task) dialog.show() dialogDeleteBinding.btnCancle.setOnClickListener { dialog.dismiss() } dialogDeleteBinding.btnAdd.setOnClickListener { val newtask = dialogDeleteBinding.edtNewtask.text.toString() val newdate = dialogDeleteBinding.edtDate.text.toString() adaptor.updateitem(data(newtask,newdate),position) dialog.dismiss() } } }
0
Kotlin
0
0
98de21286669312520fcb62fe9a2f8b497960c74
3,549
tamrin
MIT License
app/src/main/java/com/wagarcdev/der/utils/Extensions.kt
wagarcdev
546,044,448
false
null
package com.wagarcdev.der.utils import android.content.Context import com.wagarcdev.der.utils.Constants.IMAGES_FOLDER import java.io.File /** * Extension to get a [File] image on app [IMAGES_FOLDER]. */ fun Context.imageFile( fileName: String ) = File("$filesDir/$IMAGES_FOLDER/$fileName")
0
Kotlin
0
0
2578dde2f1bb801b2fd04f49964878ac4159dc25
297
DER
MIT License
rampsdk/src/main/java/network/ramp/sdk/ui/activity/Contract.kt
RampNetwork
380,937,927
false
{"Kotlin": 37160}
package network.ramp.sdk.ui.activity import network.ramp.sdk.facade.Config internal interface Contract { interface View { fun showDialog() fun close() fun sendPostMessage(data: String) } interface Presenter { fun handlePostMessage(json: String) fun buildUrl(config: Config): String } }
3
Kotlin
5
5
5b9b5e1ca46db021682312253805cd637f4ef314
351
ramp-sdk-android
MIT License
android/core/adapter/src/main/java/dylan/kwon/voetchain/core/adapter/config/ConfigAdapterModule.kt
dylan-kwon
823,387,423
false
{"Kotlin": 320698, "Solidity": 9240, "JavaScript": 8572}
package dylan.kwon.voetchain.core.adapter.config import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dylan.kwon.votechain.core.domain.config.port.ConfigPort import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) abstract class ConfigAdapterModule { @Binds @Singleton abstract fun bindsConfigAdapter( configAdapter: ConfigAdapter ): ConfigPort }
0
Kotlin
0
2
69a7999d8c11fde1b95c079380e8deecbba65659
465
vote-chain
Apache License 2.0
org.librarysimplified.audiobook.tests/src/test/java/org/librarysimplified/audiobook/tests/local/ExoDownloadTest.kt
ThePalaceProject
379,956,255
false
{"Kotlin": 718883, "Java": 2554}
package org.librarysimplified.audiobook.tests.local import android.app.Application import android.content.Context import org.librarysimplified.audiobook.tests.open_access.ExoDownloadContract import org.mockito.Mockito import org.slf4j.Logger import org.slf4j.LoggerFactory class ExoDownloadTest : ExoDownloadContract() { override fun log(): Logger { return LoggerFactory.getLogger(ExoDownloadTest::class.java) } override fun context(): Application { return Mockito.mock(Application::class.java) } }
1
Kotlin
1
1
d8e2d9dde4c20391075fcc6c527c9b9845b92a8e
518
android-audiobook
Apache License 2.0
plugins/radar-android-phone/src/main/java/org/radarbase/passive/phone/PhoneBluetoothProvider.kt
RADAR-base
85,591,443
false
{"C++": 2958963, "Kotlin": 809848, "Java": 517842, "C": 289748, "HTML": 42350, "PHP": 10200, "Makefile": 8527, "RenderScript": 997}
/* * Copyright 2017 The Hyve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.radarbase.passive.phone import android.Manifest.permission.* import android.content.pm.PackageManager import android.os.Build import org.radarbase.android.BuildConfig import org.radarbase.android.RadarService import org.radarbase.android.source.BaseSourceState import org.radarbase.android.source.SourceProvider import org.radarbase.passive.phone.PhoneSensorProvider.Companion.MODEL import org.radarbase.passive.phone.PhoneSensorProvider.Companion.PRODUCER open class PhoneBluetoothProvider(radarService: RadarService) : SourceProvider<BaseSourceState>(radarService) { override val description: String get() = radarService.getString(R.string.phone_bluetooth_description) override val serviceClass: Class<PhoneBluetoothService> = PhoneBluetoothService::class.java override val pluginNames = listOf( "phone_bluetooth", "bluetooth", ".phone.PhoneBluetoothProvider", "org.radarbase.passive.phone.PhoneBluetoothProvider", "org.radarcns.phone.PhoneBluetoothProvider") override val displayName: String get() = radarService.getString(R.string.bluetooth_devices) override val isDisplayable: Boolean = false override val permissionsNeeded: List<String> = buildList { add(ACCESS_COARSE_LOCATION) add(ACCESS_FINE_LOCATION) add(BLUETOOTH) add(BLUETOOTH_ADMIN) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { add(BLUETOOTH_SCAN) add(BLUETOOTH_CONNECT) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { add(ACCESS_BACKGROUND_LOCATION) } } override val featuresNeeded: List<String> = listOf(PackageManager.FEATURE_BLUETOOTH) override val sourceProducer: String = PRODUCER override val sourceModel: String = MODEL override val version: String = BuildConfig.VERSION_NAME }
40
C++
7
5
f62557c1721e9f4b74a84fbadfb3b052d6bab8e7
2,499
radar-commons-android
Apache License 2.0
Code/app/src/main/java/com/example/mapofitness/screens/profile/GenderBottomSheet.kt
CS683
701,049,927
false
{"Kotlin": 116413}
package com.example.mapofitness.screens.profile import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.mapofitness.common.composable.BottomSheetContainer import com.example.mapofitness.common.composable.BottomSheetTitle import com.example.mapofitness.common.composable.InfiniteCircularList import com.example.mapofitness.common.composable.SaveButton import com.example.mapofitness.data.local.entity.Gender import com.example.mapofitness.data.local.entity.UserManager import com.example.mapofitness.theme.SkyBlue @Composable fun GenderBottomSheet(onDismiss: () -> Unit , viewModel: PersonalInfoViewModel) { var gender by remember { mutableStateOf(getGender(UserManager.getGender())) } BottomSheetContainer { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { BottomSheetTitle(onDismiss = onDismiss, textValue = "Gender") Spacer(modifier = Modifier.height(8.dp)) Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) { InfiniteCircularList( width = 100.dp, itemHeight = 40.dp, items = listOf("Other", "Female", "Male"), initialItem = gender, textStyle = TextStyle(fontSize = 13.sp), textColor = Color.LightGray, selectedTextColor = SkyBlue, onItemSelected = { i, item -> gender = item } ) } Spacer(modifier = Modifier.weight(1f)) SaveButton{ onSave(gender, viewModel, onDismiss) } } } } private fun onSave(gender: String, viewModel: PersonalInfoViewModel, onDismiss: () -> Unit) { val currentGender = when(gender) { "Male" -> Gender.MALE "Female" -> Gender.FEMALE else -> { Gender.UNKNOWN } } UserManager.setGender(currentGender) UserManager.setUserData() viewModel.updateGender(currentGender) onDismiss() } private fun getGender(gender: Gender): String { return when(gender) { Gender.FEMALE -> "Female" Gender.MALE -> "Male" else -> { "Other" } } }
0
Kotlin
0
0
2b444856cbeaeb9aaab3881ffe25f44bcdf85bcd
3,108
MapoFitness
MIT License
interfaces/src/main/kotlin/com/noxcrew/interfaces/event/DrawPaneEvent.kt
Noxcrew
764,059,799
false
{"Kotlin": 111397}
package com.noxcrew.interfaces.event import com.noxcrew.interfaces.view.InterfaceView import org.bukkit.entity.Player import org.bukkit.event.HandlerList import org.bukkit.event.player.PlayerEvent /** An event emitted when the inventory of [player] is drawn. */ public class DrawPaneEvent( player: Player, /** The view that was drawn. */ public val view: InterfaceView, /** Whether any slots in the regular inventory were drawn. */ public val isRegularInventory: Boolean, /** Whether any slots in the player inventory were drawn. */ public val isPlayerInventory: Boolean ) : PlayerEvent(player) { public companion object { @JvmStatic public val handlerList: HandlerList = HandlerList() } override fun getHandlers(): HandlerList = handlerList }
0
Kotlin
4
22
66363479038df90195c6c2a187a9fc83d992b075
804
interfaces-kotlin
MIT License
zzsong-device-server/src/main/kotlin/com/zzsong/device/server/infrastructure/repository/SentCommandRepositoryImpl.kt
Songzhizong
465,969,434
false
null
package com.zzsong.device.server.infrastructure.repository import com.zzsong.device.server.domain.model.command.SentCommandDo import com.zzsong.device.server.domain.model.command.SentCommandRepository import kotlinx.coroutines.reactor.awaitSingle import kotlinx.coroutines.reactor.awaitSingleOrNull import org.springframework.data.mongodb.core.ReactiveMongoTemplate import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.Query import org.springframework.stereotype.Repository /** * @author 宋志宗 on 2022/4/5 */ @Repository class SentCommandRepositoryImpl( private val template: ReactiveMongoTemplate, private val databaseIDGenerator: DatabaseIDGenerator, ) : SentCommandRepository { override suspend fun insert(sentCommandDo: SentCommandDo): SentCommandDo { sentCommandDo.id = databaseIDGenerator.generate() return template.insert(sentCommandDo).awaitSingle() } override suspend fun findAndRemoveTimeout(): List<SentCommandDo> { val criteria = Criteria.where("timeoutTimestamp").lt(System.currentTimeMillis()) val query = Query.query(criteria) return template.findAllAndRemove(query, SentCommandDo::class.java) .collectList().awaitSingleOrNull() ?: emptyList() } }
0
Kotlin
0
0
06f8f2664499e92576b0bc329083ec15bebfdad9
1,263
zzsong-device
MIT License
model/src/main/java/com/ericafenyo/bikediary/model/Gender.kt
ericafenyo
309,510,894
false
null
/* * The MIT License (MIT) * * Copyright (C) 2021 Eric Afenyo * * 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.ericafenyo.bikediary.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable enum class Gender { @SerialName("male") MALE, @SerialName("female") FEMALE, @SerialName("unspecified") UNSPECIFIED; }
10
Kotlin
0
0
3b9b5b9440270d102c04893d3903fb1d198c0883
1,407
bike-diary
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/riskprofiler/dao/OcgmRepository.kt
ministryofjustice
166,393,369
false
null
package uk.gov.justice.digital.hmpps.riskprofiler.dao import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory import org.springframework.stereotype.Repository import uk.gov.justice.digital.hmpps.riskprofiler.datasourcemodel.FileType import uk.gov.justice.digital.hmpps.riskprofiler.datasourcemodel.Ocgm import uk.gov.justice.digital.hmpps.riskprofiler.datasourcemodel.OcgmList import java.time.LocalDateTime @Repository class OcgmRepository : DataRepository<OcgmList>() { override fun doProcess( csvData: List<List<String>>, filename: String, timestamp: LocalDateTime, data: ImportedFile<OcgmList>, ) { data.fileTimestamp = timestamp data.fileName = filename data.fileType = FileType.OCGM data.reset() csvData.stream().filter { data.index.getAndIncrement() > 0 } .forEach { p -> try { val key = p[Ocgm.NOMIS_ID_POSITION] if (StringUtils.isNotBlank(key)) { if (!NOMS_ID_REGEX.matcher(key).matches()) { log.warn("Invalid Key in line {} for Key {}", data.index.get(), key) data.linesInvalid.incrementAndGet() } else { val ocgId = p[Ocgm.OCG_ID_POSITION] if (StringUtils.isBlank(ocgId)) { log.warn("No OCG Id in line {} for Key {}", data.index.get(), key) data.linesInvalid.incrementAndGet() } else { val ocgmLine = Ocgm(key, StringUtils.trimToNull(ocgId), StringUtils.trimToNull(p[Ocgm.STANDING_POSITION])) val dataSet = data.dataSet!![key] if (dataSet != null) { dataSet.data.add(ocgmLine) } else { data.dataSet!![key] = OcgmList(key, ocgmLine, null) } data.linesProcessed.incrementAndGet() } } } else { log.warn("Missing key in line {} key [{}]", data.index.get(), key) data.linesInvalid.incrementAndGet() } } catch (e: Exception) { log.warn("Error in Line {} data [{}]", data.index.get(), p) data.linesError.incrementAndGet() } } log.info( "Lines total {}, processed {}, dups {}, invalid {}, errors {}", data.index.get(), data.linesProcessed.get(), data.linesDup.get(), data.linesInvalid.get(), data.linesError.get(), ) } companion object { private val log = LoggerFactory.getLogger(OcgmRepository::class.java) } }
15
null
1
3
92f99609e15b5a12e44cb44d0e65a1f910ef8d76
2,555
offender-risk-profiler
MIT License
ffi/src/main/kotlin/gay/pizza/pork/ffi/FfiMacPlatform.kt
GayPizzaSpecifications
680,636,847
false
{"Kotlin": 253081}
package gay.pizza.pork.ffi import java.nio.file.Path import kotlin.io.path.* object FfiMacPlatform : FfiPlatform { private val frameworksDirectories = listOf( "/Library/Frameworks" ) override fun findLibrary(name: String): Path? { val frameworksToCheck = frameworksDirectories.map { frameworkDirectory -> Path("$frameworkDirectory/$name.framework/$name") } for (framework in frameworksToCheck) { if (!framework.exists()) continue return if (framework.isSymbolicLink()) { return framework.parent.resolve(framework.readSymbolicLink()).absolute() } else { framework.absolute() } } return null } }
1
Kotlin
1
0
fdac4fb96ab3ed6b27368e10ecfb1361c047f9e5
675
pork
MIT License
ProjectFeedget/presentation/src/main/java/kr/mashup/feedget/presentation/intro/IntroPresenter.kt
mash-up-kr
109,485,907
false
{"Java": 101694, "Kotlin": 74233}
package kr.mashup.feedget.presentation.intro import io.reactivex.observers.DisposableSingleObserver import kr.mashup.feedget.domain.interactor.usecases.IsLogined import kr.mashup.feedget.domain.interactor.usecases.Register import kr.mashup.feedget.entity.SignIn import javax.inject.Inject class IntroPresenterImpl @Inject constructor( override val view: IntroView, private val isLogined: IsLogined, private val register: Register ) : IntroPresenter { override fun initialize() { isLogined.execute(object : DisposableSingleObserver<Boolean>() { override fun onSuccess(t: Boolean) { if (t) view.startMain() } override fun onError(e: Throwable) { e.printStackTrace() } }) } override fun onFacebookCallbackSuccess() { view.requestLoginFB() } override fun onRequestLoginFBSuccess(name: String, email: String, token: String) { register.execute(object : DisposableSingleObserver<SignIn>() { override fun onSuccess(t: SignIn) { view.startMain() } override fun onError(e: Throwable) { e.printStackTrace() } }, Register.Params( name, name, email, token )) } }
1
null
1
1
78dd05a711215f55d9a3bf8bde7c2349ee134f73
1,370
feedget-android
Apache License 2.0
src/test/kotlin/com/dupont/midi/input/ParserListenerStub.kt
dupontgu
121,136,119
false
null
package com.dupont.midi.input import com.dupont.midi.message.ChanneledMessage import com.dupont.midi.message.ControlChangeMessage import com.dupont.midi.message.MidiMessage class ParserListenerStub : MpeParserListener { val globalMessages = Array<MidiMessage?>(10) { null } val zoneMessages = Array<Pair<Int, MidiMessage>?>(10) { null } val fingers = Array<Pair<Int, FingerInput>?>(10) { null } val zonePitchBends = Array<Pair<Int, ChanneledMessage.PitchBendMessage>?>(10) { null } private var counter = 0 override fun onGlobalMessage(midiMessage: MidiMessage) { globalMessages[counter++] = midiMessage } override fun onZoneMessage(zoneId: Int, midiMessage: MidiMessage) { zoneMessages[counter++] = zoneId to midiMessage } override fun onFinger(zoneId: Int, finger: FingerInput) { fingers[counter++] = zoneId to finger } override fun onZonePitchBend(pitchBendMessage: ChanneledMessage.PitchBendMessage, zoneId: Int) { zonePitchBends[counter++] = zoneId to pitchBendMessage } override fun onAfterTouch(afterTouchMessage: ChanneledMessage.AfterTouchMessage, zoneId: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onProgramChange(programChangeMessage: ChanneledMessage.ProgramChangeMessage, zoneId: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onChannelPressure(channelPressureMessage: ChanneledMessage.ChannelPressureMessage, zoneId: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onControlChange(controlChangeMessage: ControlChangeMessage.GenericCcMessage, zoneId: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onRpnMessage(rpnMessage: ControlChangeMessage.RpnMessage, zoneId: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onNrpnMessage(nrpnMessage: ControlChangeMessage.NrpnMessage, zoneId: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onSystemCommonMessage(systemCommonMessage: MidiMessage.SystemCommonMessage) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }
0
Kotlin
1
3
c47298c64ab7aeb636da734c858982cb1f56d8b6
2,583
mpe-kt
MIT License
convert_string_to_char_array.kt
MarcosFloresta
223,296,767
false
null
import java.util.Arrays fun main(args: Array<String>) { val st = "This is great" val chars = st.toCharArray() println(Arrays.toString(chars)) }
0
Kotlin
0
1
eed7ca2520491200579253e95acd6ee94a0fa92e
155
kotlin-examples
MIT License
app/src/main/java/tech/touraine/timer/Buttons.kt
CedricGatay
230,894,492
true
{"Kotlin": 21304}
package tech.touraine.timer import android.view.KeyEvent import com.google.android.things.contrib.driver.button.Button import com.google.android.things.contrib.driver.button.ButtonInputDriver import java.io.Closeable class Buttons(private val buttonDrivers: List<ButtonInputDriver> = listOf( registerButtonDriver(Buttons.BUTTON_A_GPIO_PIN, KeyEvent.KEYCODE_A), registerButtonDriver(Buttons.BUTTON_B_GPIO_PIN, KeyEvent.KEYCODE_B), registerButtonDriver(Buttons.BUTTON_C_GPIO_PIN, KeyEvent.KEYCODE_C))) : Closeable { companion object { const val BUTTON_A_GPIO_PIN = "GPIO6_IO14" const val BUTTON_B_GPIO_PIN = "GPIO6_IO15" const val BUTTON_C_GPIO_PIN = "GPIO2_IO07" private fun registerButtonDriver(pin: String, keycode: Int): ButtonInputDriver { val driver = ButtonInputDriver(pin, Button.LogicState.PRESSED_WHEN_LOW, keycode) driver.register() return driver } } override fun close() { buttonDrivers.forEach(ButtonInputDriver::close) } }
0
null
0
0
69bd88e3d2fd7cd714924f889932b0b15ceb4ac7
1,065
TouraineTechTimer
MIT License
media/src/commonMain/kotlin/dev/icerock/moko/media/picker/MediaPickerController.kt
icerockdev
204,862,829
false
null
/* * Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.moko.media.picker import dev.icerock.moko.media.Bitmap import dev.icerock.moko.media.FileMedia import dev.icerock.moko.media.Media import dev.icerock.moko.permissions.PermissionsController internal const val DEFAULT_MAX_IMAGE_WIDTH = 1024 internal const val DEFAULT_MAX_IMAGE_HEIGHT = 1024 expect interface MediaPickerController { val permissionsController: PermissionsController suspend fun pickImage(source: MediaSource): Bitmap suspend fun pickImage(source: MediaSource, maxWidth: Int, maxHeight: Int): Bitmap suspend fun pickMedia(): Media suspend fun pickFiles(): FileMedia }
19
null
12
92
40c777bd3fccac60bfda5b1886514e6054e132a3
731
moko-media
Apache License 2.0
tests/push-apps-unit-tests/src/test/kotlin/unit/ServiceCreatorTest.kt
cloudfoundry-incubator
114,146,752
false
null
package unit import com.nhaarman.mockito_kotlin.* import org.assertj.core.api.Assertions.assertThat import org.cloudfoundry.tools.pushapps.CloudFoundryClient import org.cloudfoundry.tools.pushapps.config.ServiceConfig import org.cloudfoundry.tools.pushapps.ServiceCreator import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import reactor.core.publisher.Flux import reactor.core.publisher.Mono class ServiceCreatorTest : Spek({ data class TestContext( val serviceCreator: ServiceCreator, val mockCloudFoundryClient: CloudFoundryClient, val serviceConfig: ServiceConfig ) fun buildTestContext(): TestContext { val mockCloudFoundryClient = mock<CloudFoundryClient>() val serviceConfig = ServiceConfig( name = "some-service", plan = "some-plan", broker = "some-broker", optional = true ) val serviceCreator = ServiceCreator( serviceConfigs = listOf(serviceConfig), cloudFoundryClient = mockCloudFoundryClient, maxInFlight = 1 ) return TestContext(serviceCreator, mockCloudFoundryClient, serviceConfig) } describe("#createServices") { it("it creates the services and returns a success result") { val tc = buildTestContext() whenever(tc.mockCloudFoundryClient.listServices()).thenReturn(Flux.fromIterable(emptyList())) whenever(tc.mockCloudFoundryClient.createService(any())).thenReturn(Mono.empty()) val results = tc.serviceCreator.createServices().toIterable().toList() assertThat(results).hasSize(1) verify(tc.mockCloudFoundryClient, times(1)) .createService(tc.serviceConfig) val firstResult = results[0] assertThat(firstResult.description).isEqualTo("Create service ${tc.serviceConfig.name}") assertThat(firstResult.didSucceed).isTrue() } it("it returns a failure result when creating a service fails") { val tc = buildTestContext() whenever(tc.mockCloudFoundryClient.listServices()).thenReturn(Flux.fromIterable(emptyList())) whenever(tc.mockCloudFoundryClient.createService(any())).thenReturn( Mono.fromSupplier { throw Exception("lemons") } ) val results = tc.serviceCreator.createServices().toIterable().toList() assertThat(results).hasSize(1) verify(tc.mockCloudFoundryClient, times(1)) .createService(tc.serviceConfig) val result = results[0] assertThat(result.didSucceed).isFalse() assertThat(result.description).isEqualTo("Create service ${tc.serviceConfig.name}") assertThat(result.error!!.message).contains("lemons") } it("it includes whether the service was optional in the result") { val tc = buildTestContext() whenever(tc.mockCloudFoundryClient.listServices()).thenReturn(Flux.fromIterable(emptyList())) whenever(tc.mockCloudFoundryClient.createService(any())).thenReturn( Mono.fromSupplier { throw Exception("lemons") } ) val results = tc.serviceCreator.createServices().toIterable().toList() assertThat(results).hasSize(1) verify(tc.mockCloudFoundryClient, times(1)) .createService(tc.serviceConfig) val result = results[0] assertThat(result.operationConfig.optional).isTrue() } it("it does not try to create services that already exist") { val tc = buildTestContext() whenever(tc.mockCloudFoundryClient.listServices()).thenReturn(Flux.fromIterable(listOf(tc.serviceConfig.name))) val results = tc.serviceCreator.createServices().toIterable().toList() assertThat(results).isEmpty() verify(tc.mockCloudFoundryClient, times(0)).createService(any()) } } })
10
Kotlin
2
1
e4971e4f85de88b9a08eccf998172842aa784666
4,103
push-apps
Apache License 2.0
projects/prisoner-profile-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/integrations/delius/documents/entity/Offence.kt
ministryofjustice
500,855,647
false
{"Kotlin": 4262046, "HTML": 70066, "D2": 42781, "Ruby": 25921, "Shell": 19356, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2447, "JavaScript": 1372, "Python": 268}
package uk.gov.justice.digital.hmpps.integrations.delius.documents.entity import jakarta.persistence.* import org.hibernate.annotations.Immutable import org.hibernate.annotations.SQLRestriction @Entity @Immutable @SQLRestriction("soft_deleted = 0") class MainOffence( @OneToOne @JoinColumn(name = "event_id") val event: Event?, @ManyToOne @JoinColumn(name = "offence_id") val offence: Offence, @Column(columnDefinition = "number") val softDeleted: Boolean, @Id @Column(name = "main_offence_id") val id: Long, ) @Entity @Immutable @Table(name = "r_offence") data class Offence( @Column val subCategoryDescription: String, @Id @Column(name = "offence_id") val id: Long )
3
Kotlin
0
2
3f85ef8108aa583819eeee66d9d436a760028962
742
hmpps-probation-integration-services
MIT License
src/main/kotlin/net/wiredtomato/burgered/data/gen/provider/BurgeredEnUsLangProvider.kt
wired-tomato
835,870,549
false
{"Kotlin": 95855, "Java": 1521}
package net.wiredtomato.burgered.data.gen.provider import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput import net.fabricmc.fabric.api.datagen.v1.provider.FabricLanguageProvider import net.minecraft.block.Block import net.minecraft.item.ItemGroup import net.minecraft.registry.HolderLookup import net.minecraft.registry.Registries import net.minecraft.registry.RegistryKeys import net.minecraft.util.Identifier import net.wiredtomato.burgered.Burgered import net.wiredtomato.burgered.data.text.CommonText import net.wiredtomato.burgered.util.id import java.util.concurrent.CompletableFuture import kotlin.jvm.optionals.getOrElse class BurgeredEnUsLangProvider( output: FabricDataOutput, lookup: CompletableFuture<HolderLookup.Provider> ) : FabricLanguageProvider(output, lookup) { override fun generateTranslations(registryLookup: HolderLookup.Provider, translationBuilder: TranslationBuilder) { registryLookup.getLookup(RegistryKeys.ITEM).getOrElse { return } .holders() .filter { it.registryKey.value.namespace == Burgered.MOD_ID } .map { it.value() } .forEach { translationBuilder.add(it, genLang(it.id)) } registryLookup.getLookup(RegistryKeys.ITEM_GROUP).getOrElse { return } .holders() .filter { it.registryKey.value.namespace == Burgered.MOD_ID } .map { it.value() } .forEach { translationBuilder.add(it.id.toTranslationKey("itemgroup"), genLang(it.id)) } translationBuilder.add(CommonText.INGREDIENTS, "Ingredients: ") translationBuilder.add(CommonText.CANT_BE_PUT_ON_BURGER, "You can't put %s on this burger!") translationBuilder.add(CommonText.BURGER_MAX_SIZE, "Sorry, I can't let you put anymore ingredient on this burger.") translationBuilder.add(CommonText.SLOPPINESS, "Sloppiness: %s") translationBuilder.add("emi.category.burgered.grilling", "Grilling") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.maxRenderedBurgerIngredients", "Max Rendered Burger Ingredients") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.maxRenderedBurgerIngredients.tooltip", "Maximum number of ingredients to render per burger.") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.maxSloppinessRotationX", "Max Sloppiness Rotation X") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.maxSloppinessRotationX.tooltip", "Maximum amount to rotate burger ingredients along X-axix (in degrees).") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.maxSloppinessRotationY", "Max Sloppiness Rotation Y") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.maxSloppinessRotationY.tooltip", "Maximum amount to rotate burger ingredients along Y-axix (in degrees).") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.maxSloppinessRotationZ", "Max Sloppiness Rotation Z") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.maxSloppinessRotationZ.tooltip", "Maximum amount to rotate burger ingredients along Z-axix (in degrees).") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.renderNoTransform", "Always Render With no Default Item Transformations") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.renderNoTransform.tooltip", "Always render burgers with no default item transformations.\nDISABLING THIS MAY CAUSE VISUAL ARTIFACTING WITH SOME INGREDIENTS AND ADDON MODS!!!") translationBuilder.add("${Burgered.MOD_ID}.midnightconfig.category.rendering", "Rendering") } private fun genLang(identifier: Identifier): String = identifier.path.titleCase() private fun String.titleCase(): String { return split("_").joinToString(" ") { it.replaceFirstChar(Char::uppercaseChar) } } val ItemGroup.id get() = Registries.ITEM_GROUP.getId(this)!! val Block.id get() = Registries.BLOCK.getId(this) }
0
Kotlin
0
0
c4f7c275fea3d0517ca6f26c5a295c7fa500752a
3,961
burgered
MIT License
ktlint-gradle-plugin/src/main/kotlin/com/rickbusarow/ktlint/KtLintPlugin.kt
RBusarow
624,506,118
false
null
/* * Copyright (C) 2023 <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.rickbusarow.ktlint import com.rickbusarow.ktlint.internal.capitalize import com.rickbusarow.ktlint.internal.resolveInParentOrNull import org.gradle.api.NamedDomainObjectProvider import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.ModuleDependency import org.gradle.api.tasks.TaskProvider import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension /** */ @Suppress("UnnecessaryAbstractClass") abstract class KtLintPlugin : Plugin<Project> { override fun apply(target: Project) { val configProvider: NamedDomainObjectProvider<Configuration> = target.configurations.register("ktlint") target.plugins.withId("org.jetbrains.kotlin.jvm") { registerKotlinTasks(target, configProvider) } target.plugins.withId("org.jetbrains.kotlin.android") { registerKotlinTasks(target, configProvider) } target.plugins.withId("org.jetbrains.kotlin.js") { registerKotlinTasks(target, configProvider) } target.plugins.withId("org.jetbrains.kotlin.multiplatform") { registerKotlinTasks(target, configProvider) } if (target == target.rootProject) { target.tasks.register("ktlintFormat", KtlintFormatTask::class.java) { task -> task.sourceFiles.setFrom() task.ktlintClasspath.setFrom(configProvider) task.sourceFilesShadow.set(target.buildDir.resolve("outputs/ktlint/root")) task.editorConfig.fileValue(target.projectDir.resolveInParentOrNull(".editorconfig")) } target.tasks.register("ktlintCheck", KtlintCheckTask::class.java) { task -> task.sourceFiles.setFrom() task.ktlintClasspath.setFrom(configProvider) task.sourceFilesShadow.set(target.buildDir.resolve("outputs/ktlint/root")) task.editorConfig.fileValue(target.projectDir.resolveInParentOrNull(".editorconfig")) } } if (target == target.rootProject) { target.tasks.register("syncRuleSetJars", KtLintSyncRuleSetJarTask::class.java) { sync -> val jarFolder = target.buildDir.resolve("ktlint-rules-jars") val xml = target.rootProject.file(".idea/ktlint.xml") sync.jarFolder.set(jarFolder) sync.xmlFile.set(xml) sync.inputs.file(xml) sync.onlyIf { xml.exists() } val noTransitive = configProvider.map { original -> val copy = original.copy() copy.dependencies.clear() copy.dependencies.addAll( original.dependencies.map { dep -> when (dep) { is ModuleDependency -> dep.copy().also { it.setTransitive(false) } else -> dep.copy() } } ) copy } sync.from(noTransitive) sync.into(jarFolder) } target.tasks.named("prepareKotlinBuildScriptModel") { it.dependsOn("syncRuleSetJars") } } // target.dependencies.add("ktlint", target.libsCatalog.dependency("ktlint-ruleset-experimental")) // target.dependencies.add("ktlint", target.libsCatalog.dependency("ktlint-ruleset-standard")) } private fun registerKotlinTasks( target: Project, configProvider: NamedDomainObjectProvider<Configuration>? ) { val extension = target.extensions.getByType(KotlinProjectExtension::class.java) val sourceSetNames = extension.sourceSets.names val pairs = sourceSetNames.map { sourceSetName -> registerFormatCheckPair(target, extension, sourceSetName, configProvider) } val formatTasks = pairs.map { it.first } val lintTasks = pairs.map { it.second } target.tasks.register("ktlintFormat", KtlintTask::class.java) { task -> task.sourceFiles.setFrom() task.ktlintClasspath.setFrom(configProvider) task.dependsOn(formatTasks) task.sourceFilesShadow.set(target.buildDir.resolve("outputs/ktlint/root")) task.editorConfig.fileValue(target.projectDir.resolveInParentOrNull(".editorconfig")) } target.tasks.register("ktlintCheck", KtlintCheckTask::class.java) { task -> task.sourceFiles.setFrom() task.ktlintClasspath.setFrom(configProvider) task.dependsOn(lintTasks) task.sourceFilesShadow.set(target.buildDir.resolve("outputs/ktlint/root")) task.editorConfig.fileValue(target.projectDir.resolveInParentOrNull(".editorconfig")) } } private fun registerFormatCheckPair( target: Project, extension: KotlinProjectExtension, sourceSetName: String, configProvider: NamedDomainObjectProvider<Configuration>? ): Pair<TaskProvider<KtlintTask>, TaskProvider<KtlintTask>> { val formatTaskName = "ktlintFormat${sourceSetName.capitalize()}" val formatTask = target.tasks.register(formatTaskName, KtlintTask::class.java) { task -> val sourceSet = extension.sourceSets.getByName(sourceSetName) task.sourceFiles.from(sourceSet.kotlin) task.ktlintClasspath.setFrom(configProvider) task.sourceFilesShadow.set(target.buildDir.resolve("outputs/ktlint/$sourceSetName")) task.editorConfig.fileValue(target.projectDir.resolveInParentOrNull(".editorconfig")) } val checkTaskName = "ktlintCheck${sourceSetName.capitalize()}" val lintTask = target.tasks.register(checkTaskName, KtlintTask::class.java) { task -> val sourceSet = extension.sourceSets.getByName(sourceSetName) task.sourceFiles.from(sourceSet.kotlin) task.ktlintClasspath.setFrom(configProvider) task.mustRunAfter(formatTask) task.sourceFilesShadow.set(target.buildDir.resolve("outputs/ktlint/$sourceSetName")) task.editorConfig.fileValue(target.projectDir.resolveInParentOrNull(".editorconfig")) } return formatTask to lintTask } }
7
Kotlin
0
0
69e76490710a992e4ccba07f4dac1054cab0d8d5
6,374
ktlint-gradle-plugin
Apache License 2.0
examples/resilience4j/src/test/kotlin/example/spring/boot/resilience/timelimiter/DownstreamServiceWithAnnotationBasedTimeLimiterTests.kt
test-automation-in-practice
506,693,260
false
null
package example.spring.boot.resilience.timelimiter import com.ninjasquad.springmockk.MockkBean import example.spring.boot.resilience.Tripwire import io.github.resilience4j.springboot3.timelimiter.autoconfigure.TimeLimiterAutoConfiguration import io.mockk.every import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.ImportAutoConfiguration import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.annotation.EnableAspectJAutoProxy import org.springframework.context.annotation.Import import org.springframework.test.context.ActiveProfiles import java.lang.Thread.sleep import java.util.concurrent.ExecutionException import java.util.concurrent.TimeoutException @ActiveProfiles("test") @MockkBean(Tripwire::class, relaxUnitFun = true) @SpringBootTest(classes = [DownstreamServiceWithAnnotationBasedTimeLimiterTestsConfiguration::class]) class DownstreamServiceWithAnnotationBasedTimeLimiterTests( @Autowired val tripwire: Tripwire, @Autowired val cut: DownstreamServiceWithAnnotationBasedTimeLimiter ) { val isbn = "978-1804941836" @Test fun `returns result if operation takes less than threshold`() { val result = cut.getNumberOfPages(isbn) assertThat(result.get()).isEqualTo(42) } @Test fun `without fallback a timeout exception is thrown if operation takes longer than threshold`() { every { tripwire.possiblyWait() } answers { sleep(1_000) } val ex = assertThrows<ExecutionException> { cut.getNumberOfPages(isbn).get() } assertThat(ex).hasCauseInstanceOf(TimeoutException::class.java) } @Test fun `with fallback that fallback is returned if operation takes longer than threshold`() { every { tripwire.possiblyWait() } answers { sleep(1_000) } val result = cut.getNumberOfPagesWithFallback(isbn) assertThat(result.get()).isNull() } } @EnableAspectJAutoProxy @ImportAutoConfiguration(TimeLimiterAutoConfiguration::class) @Import(DownstreamServiceWithAnnotationBasedTimeLimiter::class, Tripwire::class) private class DownstreamServiceWithAnnotationBasedTimeLimiterTestsConfiguration
0
null
0
54
5a4b1fc0cc693a1af50a88057d04516a1303afa9
2,384
cnt-spring-boot
Apache License 2.0
kazuki-ksp/src/main/kotlin/com/anaplan/engineering/kazuki/ksp/InbuiltNames.kt
anaplan-engineering
715,012,365
false
{"Kotlin": 245808, "Shell": 827}
package com.anaplan.engineering.kazuki.ksp import com.squareup.kotlinpoet.MemberName internal object InbuiltNames { internal const val corePackage = "com.anaplan.engineering.kazuki.core" internal const val coreInternalPackage = "com.anaplan.engineering.kazuki.core.internal" internal val mkSet = MemberName(corePackage, "mk_Set") internal val mkSet1 = MemberName(corePackage, "mk_Set1") internal val asSet = MemberName(corePackage, "as_Set") internal val asSet1 = MemberName(corePackage, "as_Set1") internal val mkSeq = MemberName(corePackage, "mk_Seq") internal val mkSeq1 = MemberName(corePackage, "mk_Seq1") internal val forall = MemberName(corePackage, "forall") }
0
Kotlin
0
0
f58f59281219ba3bf08402041dcb55170bb4cbe3
707
kazuki
MIT License
Application/src/main/java/com/example/android/bluetoothchat/BluetoothChatFragment.kt
solidogen
203,795,479
true
{"Kotlin": 66653}
/* * Copyright (C) 2014 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. */ package com.example.android.bluetoothchat import android.app.Activity import android.bluetooth.BluetoothAdapter import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Message import androidx.fragment.app.Fragment import android.view.KeyEvent import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.ArrayAdapter import android.widget.Button import android.widget.EditText import android.widget.ListView import android.widget.TextView import android.widget.Toast import com.example.android.common.logger.Log /** * This fragment controls Bluetooth to communicate with other devices. */ class BluetoothChatFragment : Fragment() { // Layout Views private var mConversationView: ListView? = null private var mOutEditText: EditText? = null private var mSendButton: Button? = null /** * Name of the connected device */ private var mConnectedDeviceName: String? = null /** * Array adapter for the conversation thread */ private var mConversationArrayAdapter: ArrayAdapter<String>? = null /** * String buffer for outgoing messages */ private var mOutStringBuffer: StringBuffer? = null /** * Local Bluetooth adapter */ private var mBluetoothAdapter: BluetoothAdapter? = null /** * Member object for the chat services */ private var mChatService: BluetoothChatService? = null /** * The action listener for the EditText widget, to listen for the return key */ private val mWriteListener = TextView.OnEditorActionListener { view, actionId, event -> // If the action is a key-up event on the return key, send the message if (actionId == EditorInfo.IME_NULL && event.action == KeyEvent.ACTION_UP) { val message = view.text.toString() sendMessage(message) } true } /** * The Handler that gets information back from the BluetoothChatService */ private val mHandler = object : Handler() { override fun handleMessage(msg: Message) { val activity = activity when (msg.what) { Constants.MESSAGE_STATE_CHANGE -> when (msg.arg1) { BluetoothChatService.STATE_CONNECTED -> { setStatus(getString(R.string.title_connected_to, mConnectedDeviceName)) mConversationArrayAdapter!!.clear() } BluetoothChatService.STATE_CONNECTING -> setStatus(R.string.title_connecting) BluetoothChatService.STATE_LISTEN, BluetoothChatService.STATE_NONE -> setStatus(R.string.title_not_connected) } Constants.MESSAGE_WRITE -> { val writeBuf = msg.obj as ByteArray // construct a string from the buffer val writeMessage = String(writeBuf) mConversationArrayAdapter!!.add("Me: $writeMessage") } Constants.MESSAGE_READ -> { val readBuf = msg.obj as ByteArray // construct a string from the valid bytes in the buffer val readMessage = String(readBuf, 0, msg.arg1) mConversationArrayAdapter!!.add("$mConnectedDeviceName: $readMessage") } Constants.MESSAGE_DEVICE_NAME -> { // save the connected device's name mConnectedDeviceName = msg.data.getString(Constants.DEVICE_NAME) if (null != activity) { Toast.makeText(activity, "Connected to " + mConnectedDeviceName!!, Toast.LENGTH_SHORT).show() } } Constants.MESSAGE_TOAST -> if (null != activity) { Toast.makeText(activity, msg.data.getString(Constants.TOAST), Toast.LENGTH_SHORT).show() } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) // Get local Bluetooth adapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter() // If the adapter is null, then Bluetooth is not supported if (mBluetoothAdapter == null) { val activity = activity Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show() activity!!.finish() } } override fun onStart() { super.onStart() // If BT is not on, request that it be enabled. // setupChat() will then be called during onActivityResult if (!mBluetoothAdapter!!.isEnabled) { val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) startActivityForResult(enableIntent, REQUEST_ENABLE_BT) // Otherwise, setup the chat session } else if (mChatService == null) { setupChat() } } override fun onDestroy() { super.onDestroy() if (mChatService != null) { mChatService!!.stop() } } override fun onResume() { super.onResume() // Performing this check in onResume() covers the case in which BT was // not enabled during onStart(), so we were paused to enable it... // onResume() will be called when ACTION_REQUEST_ENABLE activity returns. if (mChatService != null) { // Only if the state is STATE_NONE, do we know that we haven't started already if (mChatService!!.connectionState == BluetoothChatService.STATE_NONE) { // Start the Bluetooth chat services mChatService!!.start() } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { mConversationView = view.findViewById<View>(R.id.`in`) as ListView mOutEditText = view.findViewById<View>(R.id.edit_text_out) as EditText mSendButton = view.findViewById<View>(R.id.button_send) as Button } /** * Set up the UI and background operations for chat. */ private fun setupChat() { Log.d(TAG, "setupChat()") // Initialize the array adapter for the conversation thread mConversationArrayAdapter = ArrayAdapter(activity!!, R.layout.message) mConversationView!!.adapter = mConversationArrayAdapter // Initialize the compose field with a listener for the return key mOutEditText!!.setOnEditorActionListener(mWriteListener) // Initialize the send button with a listener that for click events mSendButton!!.setOnClickListener { // Send a message using content of the edit text widget val view = view if (null != view) { val textView = view.findViewById<View>(R.id.edit_text_out) as TextView val message = textView.text.toString() sendMessage(message) } } // Initialize the BluetoothChatService to perform bluetooth connections mChatService = BluetoothChatService(mHandler) // Initialize the buffer for outgoing messages mOutStringBuffer = StringBuffer("") } /** * Makes this device discoverable for 300 seconds (5 minutes). */ private fun ensureDiscoverable() { if (mBluetoothAdapter!!.scanMode != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { val discoverableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE) discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300) startActivity(discoverableIntent) } } /** * Sends a message. * * @param message A string of text to send. */ private fun sendMessage(message: String) { // Check that we're actually connected before trying anything if (mChatService!!.connectionState != BluetoothChatService.STATE_CONNECTED) { Toast.makeText(activity, R.string.not_connected, Toast.LENGTH_SHORT).show() return } // Check that there's actually something to send if (message.isNotEmpty()) { // Get the message bytes and tell the BluetoothChatService to write val send = message.toByteArray() mChatService!!.write(send) // Reset out string buffer to zero and clear the edit text field mOutStringBuffer!!.setLength(0) mOutEditText!!.setText(mOutStringBuffer) } } /** * Updates the status on the action bar. * * @param resId a string resource ID */ private fun setStatus(resId: Int) { val activity = activity ?: return val actionBar = activity.actionBar ?: return actionBar.setSubtitle(resId) } /** * Updates the status on the action bar. * * @param subTitle status */ private fun setStatus(subTitle: CharSequence) { val activity = activity ?: return val actionBar = activity.actionBar ?: return actionBar.subtitle = subTitle } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_CONNECT_DEVICE_SECURE -> // When DeviceListActivity returns with a device to connect if (resultCode == Activity.RESULT_OK) { connectDevice(data!!, true) } REQUEST_CONNECT_DEVICE_INSECURE -> // When DeviceListActivity returns with a device to connect if (resultCode == Activity.RESULT_OK) { connectDevice(data!!, false) } REQUEST_ENABLE_BT -> // When the request to enable Bluetooth returns if (resultCode == Activity.RESULT_OK) { // Bluetooth is now enabled, so set up a chat session setupChat() } else { // User did not enable Bluetooth or an error occurred Log.d(TAG, "BT not enabled") Toast.makeText(activity, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show() activity!!.finish() } } } /** * Establish connection with other device * * @param data An [Intent] with [DeviceListActivity.EXTRA_DEVICE_ADDRESS] extra. * @param secure Socket Security type - Secure (true) , Insecure (false) */ private fun connectDevice(data: Intent, secure: Boolean) { // Get the device MAC address val address = data.extras!! .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS) // Get the BluetoothDevice object val device = mBluetoothAdapter!!.getRemoteDevice(address) // Attempt to connect to the device mChatService!!.connect(device, secure) } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater!!.inflate(R.menu.bluetooth_chat, menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item!!.itemId) { R.id.secure_connect_scan -> { // Launch the DeviceListActivity to see devices and do scan val serverIntent = Intent(activity, DeviceListActivity::class.java) startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE) return true } R.id.insecure_connect_scan -> { // Launch the DeviceListActivity to see devices and do scan val serverIntent = Intent(activity, DeviceListActivity::class.java) startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE) return true } R.id.discoverable -> { // Ensure this device is discoverable by others ensureDiscoverable() return true } } return false } companion object { private val TAG = "BluetoothChatFragment" // Intent request codes private val REQUEST_CONNECT_DEVICE_SECURE = 1 private val REQUEST_CONNECT_DEVICE_INSECURE = 2 private val REQUEST_ENABLE_BT = 3 } }
0
Kotlin
0
0
001a68617a81bb61c910bbc419b262a480f20e06
13,494
android-BluetoothChat
Apache License 2.0
src/main/kotlin/com/github/cout970/lhl/services/MyApplicationService.kt
cout970
519,561,729
false
{"Kotlin": 6732}
package com.github.cout970.lhl.services import com.github.cout970.lhl.MyBundle class MyApplicationService { init { println(MyBundle.message("applicationService")) } }
0
Kotlin
1
1
8fd906222f4431b31020d17b80ef9dce98ea31ef
186
LHL
Apache License 2.0
src/main/kotlin/com/github/wangfuhao0000/dbspstudio/listeners/MyProjectManagerListener.kt
wangfuhao0000
503,593,907
false
null
package com.github.wangfuhao0000.dbspstudio.listeners import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManagerListener import com.github.wangfuhao0000.dbspstudio.services.MyProjectService internal class MyProjectManagerListener : ProjectManagerListener { override fun projectOpened(project: Project) { project.service<MyProjectService>() } }
0
Kotlin
0
0
7b9dbe91038bed4917b268610ddee1aff194be93
446
dbspstudio
Apache License 2.0
app/src/main/java/com/example/sampleapp/utils/common/LoadMoreListener.kt
uditbhaskar
344,421,725
false
null
package com.example.sampleapp.utils.common interface LoadMoreListener { fun onLoadMore() }
0
Kotlin
3
4
2924b289de462517e54c013dd0ecbf0ae69247ed
96
MVVMBaseArchitecture
Apache License 2.0
app/src/main/java/com/tanishkej/onerep/ui/workouts/states/WorkoutListUiState.kt
TaniaLemus
791,409,242
false
{"Kotlin": 47072}
package com.tanishkej.onerep.ui.workouts.states import com.tanishkej.onerep.data.model.WorkoutGroups sealed interface WorkoutListUiState { data class Success(val workoutGroups: List<WorkoutGroups>) : WorkoutListUiState data object Error : WorkoutListUiState data object Loading : WorkoutListUiState }
0
Kotlin
0
0
957221ea91b4ecd6cf288f705b77c0fd0f776044
313
ONE-Rep
MIT License
app/src/main/java/de/dertyp7214/rboardthememanager/helper/DownloadHelper.kt
AndroBuddy
226,158,514
true
{"Kotlin": 120776}
package de.dertyp7214.rboardthememanager.helper import android.content.Context import android.widget.ImageView import android.widget.ProgressBar import com.afollestad.materialdialogs.MaterialDialog import com.downloader.Error import com.downloader.OnDownloadListener import com.downloader.PRDownloader import de.dertyp7214.rboardthememanager.R import java.io.File class DownloadHelper(private val context: Context) { private var from = "" private var to = "" private var fileName = "" private var listener: DownloadListener = object : DownloadListener { override fun start() {} override fun progress(progress: Int, current: Long, total: Long) {} override fun error(error: String) {} override fun end(path: String) {} } fun from(url: String): DownloadHelper { from = url return this } fun to(path: String): DownloadHelper { to = path return this } fun fileName(name: String): DownloadHelper { fileName = name return this } fun setListener(l: DownloadListener): DownloadHelper { listener = l return this } fun start() { PRDownloader.download(from, to, fileName) .build() .setOnStartOrResumeListener { listener.start() } .setOnProgressListener { val progress = (it.currentBytes.toFloat() / it.totalBytes.toFloat()) * 100F listener.progress(progress.toInt(), it.currentBytes, it.totalBytes) } .start(object : OnDownloadListener { override fun onDownloadComplete() { listener.end(File(to, fileName).absolutePath) } override fun onError(error: Error?) { listener.error(error?.connectionException?.localizedMessage ?: "") } }) } } fun downloadDialog(context: Context): Pair<ProgressBar, MaterialDialog> { lateinit var progressBar: ProgressBar val dialog = MaterialDialog(context).show { setContentView(R.layout.download_alert) cancelable(false) cancelOnTouchOutside(false) progressBar = findViewById(R.id.progressbar_downloading) val imageView = findViewById<ImageView>(R.id.dialog_image_view) imageView.viewTreeObserver.addOnGlobalLayoutListener { progressBar.scaleY = imageView.measuredHeight.toFloat() } } return Pair(progressBar, dialog) } interface DownloadListener { fun start() fun progress(progress: Int, current: Long, total: Long) fun error(error: String) fun end(path: String) }
0
null
0
0
98d55156b32930cfab007733c2f06fd620b43617
2,666
Rboard-Theme-Manager
MIT License
domain/src/main/java/com/gmart/domain/repository/AuthRepository.kt
gimartinez17
771,233,885
false
{"Kotlin": 515365, "CMake": 1625, "C++": 259}
package com.gmart.domain.repository import com.gmart.domain.model.Account import com.gmart.domain.model.Authorization import com.gmart.domain.model.Resource import kotlinx.coroutines.flow.Flow interface AuthRepository { suspend fun createRequestToken(redirectTo: String): Flow<Resource<String>> suspend fun createAccessToken(token: String): Flow<Resource<Authorization>> suspend fun signOut(accessToken: String): Flow<Resource<String>> suspend fun getAccountDetails(userName: String): Flow<Resource<Account>> }
0
Kotlin
1
1
da0854981d865fb7207767ae3e6a4c8ce1f441a8
529
movies-app
MIT License
mobile/src/main/java/be/mygod/vpnhotspot/util/UnblockCentral.kt
Mygod
116,107,171
false
null
package be.mygod.vpnhotspot.util import android.annotation.SuppressLint import android.net.MacAddress import android.net.wifi.SoftApConfiguration import android.net.wifi.p2p.WifiP2pConfig import android.service.quicksettings.TileService import androidx.annotation.RequiresApi import org.lsposed.hiddenapibypass.HiddenApiBypass /** * The central object for accessing all the useful blocked APIs. Thanks Google! * * Lazy cannot be used directly as it will create inner classes. */ @SuppressLint("BlockedPrivateApi", "DiscouragedPrivateApi", "SoonBlockedPrivateApi") object UnblockCentral { var needInit = true /** * Retrieve this property before doing dangerous shit. */ private val init by lazy { if (needInit) check(HiddenApiBypass.setHiddenApiExemptions("")) } @RequiresApi(33) fun getCountryCode(clazz: Class<*>) = init.let { clazz.getDeclaredMethod("getCountryCode") } @RequiresApi(33) fun setRandomizedMacAddress(clazz: Class<*>) = init.let { clazz.getDeclaredMethod("setRandomizedMacAddress", MacAddress::class.java) } @get:RequiresApi(31) val SoftApConfiguration_BAND_TYPES get() = init.let { SoftApConfiguration::class.java.getDeclaredField("BAND_TYPES").get(null) as IntArray } @RequiresApi(31) fun getApInstanceIdentifier(clazz: Class<*>) = init.let { clazz.getDeclaredMethod("getApInstanceIdentifier") } @get:RequiresApi(29) val WifiP2pConfig_Builder_mNetworkName get() = init.let { WifiP2pConfig.Builder::class.java.getDeclaredField("mNetworkName").apply { isAccessible = true } } val TileService_mToken get() = init.let { TileService::class.java.getDeclaredField("mToken").apply { isAccessible = true } } }
13
null
368
3,709
4434df0309b41f61f509c4248d1348ec8ec47180
1,745
VPNHotspot
Apache License 2.0
app/src/main/java/com/capstone/siapabisa/ui/main/UserActivity.kt
Capstone-C23-PC622
642,864,844
false
null
package com.capstone.siapabisa.ui.main import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.capstone.siapabisa.R class UserActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user) } }
0
Kotlin
0
0
b635f670ed533f2acb7a93b21b89d8e3f0e55b72
343
Mobile-Development
MIT License
0373.Find K Pairs with Smallest Sums.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
internal class Solution { fun kSmallestPairs(nums1: IntArray, nums2: IntArray, k: Int): List<List<Int>> { var k = k val q: PriorityQueue<IntArray> = PriorityQueue(Comparator.comparingInt { a -> a.get(0) }) for (i in 0 until min(nums1.size, k)) { q.offer(intArrayOf(nums1[i] + nums2[0], i, 0)) } val ans: List<List<Int>> = ArrayList() while (!q.isEmpty() && k > 0) { val e: IntArray = q.poll() ans.add(Arrays.asList(nums1[e[1]], nums2[e[2]])) --k if (e[2] + 1 < nums2.size) { q.offer(intArrayOf(nums1[e[1]] + nums2[e[2] + 1], e[1], e[2] + 1)) } } return ans } }
0
Kotlin
0
0
71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48
641
kotlin-leetcode
MIT License
src/main/kotlin/readinglist/domain/Movie.kt
praveenKajla
101,145,121
false
{"JavaScript": 50277, "CSS": 27347, "Kotlin": 8063, "HTML": 926}
package readinglist import com.fasterxml.jackson.annotation.JsonIgnoreProperties import java.util.* import javax.persistence.* @Entity data class Movie(@Id @GeneratedValue(strategy= GenerationType.AUTO) val idd : Long?=null, var watcher:String?=null, val vote_count:Long, val id:String?, val runtime:Int?, val vote_average:Float, val title:String, val popularity:Float, val poster_path:String, val original_language:String, val original_title:String, val backdrop_path:String, val adult:Boolean, @Column(length=9000)val overview:String?, val release_date:String)
0
JavaScript
0
7
08912043559c8bc7636d7e87deec6077e9fe6f64
838
react-kotlin-app
MIT License
runtime/src/main/java/jp/co/soramitsu/runtime/DefinitionsFetcher.kt
metrocoindev
372,627,505
true
{"Kotlin": 1715024}
package jp.co.soramitsu.runtime import retrofit2.http.GET import retrofit2.http.Path interface DefinitionsFetcher { @GET("//raw.githubusercontent.com/valentunn/py-scale-codec/test/rococo_crowdloans/scalecodec/type_registry/{fileName}") suspend fun getDefinitionsByFile(@Path("fileName") fileName: String): String } suspend fun DefinitionsFetcher.getDefinitionsByNetwork(networkName: String): String { return getDefinitionsByFile(fileName(networkName)) } fun fileName(networkName: String) = "$networkName.json"
0
null
0
0
cdb76cfdc1486e171c98aae3650e1d2e224a185a
527
fearless-Android
Apache License 2.0
src/main/kotlin/utils/Utils.kt
GibsonRuitiari
451,852,891
false
{"Kotlin": 87529, "Procfile": 66}
package utils import backend.comic_models.SMangaPage import com.github.kittinunf.fuel.Fuel import com.github.kittinunf.fuel.core.FileDataPart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import mu.KLogger import net.lingala.zip4j.ZipFile import java.net.URL import java.nio.file.Path import java.time.LocalDateTime import java.util.concurrent.CompletableFuture import kotlin.coroutines.* import kotlin.io.path.* private const val serverUrl = "https://transfer.sh/" private const val contentType="application/cbz" typealias ReadProgress = (Int)->Unit /** * Uploads a comic book to the remote server * @param currentPath the path where the comic book is located * @param logger for logging purposes * @param progressBlock for reporting the progress to client/user */ suspend fun uploadComicToRemoteServer(currentPath: Path, logger:KLogger, progressBlock:ReadProgress):String? = withContext(Dispatchers.IO){ val file = FileDataPart.from(currentPath.absolutePathString(), contentType = contentType) var progressToReport = 0 val (_,_, result) = Fuel.upload(serverUrl) .add { file} .progress { readBytes, totalBytes -> val percentageDownloaded = readBytes *100.0 / totalBytes if (percentageDownloaded - progressToReport >=5){ progressToReport = percentageDownloaded.toInt() logger.info { "progress: $progressToReport" } progressBlock.invoke(progressToReport) } }.responseString() val downloadUrl:String?=when(result){ is com.github.kittinunf.result.Result.Failure->{ logger.error { "${LocalDateTime.now()}: the following error occurred while uploading file: ${result.getException()}" } null } is com.github.kittinunf.result.Result.Success->{ val anteriorUrl=result.value.removePrefix(serverUrl) val downloadUrl="https://transfer.sh/get/$anteriorUrl" logger.info { "${LocalDateTime.now()} downloaded successfully ${System.lineSeparator()} This is the url: $downloadUrl" } println(downloadUrl) downloadUrl } } return@withContext downloadUrl } /** * Creates a temporary base directory to be used for housing * all downloaded comics. The temporary comics housed will be deleted upon * successful uploads */ fun createBaseTmpDir(dirName:String="comics_tmp"):Path{ val tmpBaseDir = Path(System.getProperty("user.dir"),dirName) if (tmpBaseDir.notExists()) tmpBaseDir.createDirectory() return tmpBaseDir } /** * Like its counterpart above, this creates a zip file (a comic book archive) inside the base directory * Upon successful upload, this zip will be deleted * It is to be noted the zip file ends with .cbz which is the default format for comic books * archive */ fun createTempZipFile(baseDir: Path, zipFileName: String): ZipFile { return ZipFile(baseDir.resolve(zipFileName).toFile()) } fun createTempImgSaveDir(baseDir: Path,dirName:String):Path{ return createTempDirectory(baseDir,dirName) } /** * Iterates through the list of comic pages and adds *them, to the given zip file, as .png */ suspend fun saveComicImagesToZip(pages:List<SMangaPage>, zipFile: ZipFile, saveDir:Path){ withContext(Dispatchers.IO){ pages.forEach { URL(it.pageThumbnail).openStream().use { is_-> val picture = saveDir.resolve("${it.pageDetail}.png") picture.outputStream().use { os-> is_.copyTo(os) } zipFile.addFile(picture.toFile()) } } } } // adapted from kotlinx.coroutines.examples.usage suspend fun <T> CompletableFuture<T>.await(): T = suspendCoroutine { whenComplete { res, ex -> if (ex == null) it.resume(res) else it.resumeWithException(ex) } } fun <T> future(context: CoroutineContext = Dispatchers.IO, block: suspend () -> T): CompletableFuture<T> = CompletableFutureCoroutine<T>(context).also { block.startCoroutine(completion = it) } class CompletableFutureCoroutine<T>(override val context: CoroutineContext) : CompletableFuture<T>(), Continuation<T> { override fun resumeWith(result: Result<T>) { if (result.isSuccess) { complete(result.getOrThrow()) } else { completeExceptionally(result.exceptionOrNull()) } } }
0
Kotlin
0
1
4a2f4320207a4ff53754aa5ebc90715958a2baf6
4,491
Comics-Telegram-Bot
Apache License 2.0
app/src/main/java/com/team/testscanner/ui/activities/TestScreen.kt
mukulasija
600,352,382
false
{"Kotlin": 196047}
package com.team.testscanner.ui.activities import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.Drawable import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.CountDownTimer import android.util.Base64 import android.util.Log import android.view.View import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.target.CustomTarget import com.bumptech.glide.request.transition.Transition import com.google.firebase.firestore.FirebaseFirestore import com.team.testscanner.R import com.team.testscanner.adapters.OptionAdapter import com.team.testscanner.models.Attempt import com.team.testscanner.models.OptionSelector import com.team.testscanner.models.Question import com.team.testscanner.models.Quiz import java.util.concurrent.TimeUnit class TestScreen : AppCompatActivity() { lateinit var firestore: FirebaseFirestore var quizzes : MutableList<Quiz>? = null var questions: MutableMap<String, Question>? = null var index = 1 private var studentId : String = "" lateinit var btnNext : Button lateinit var btnPrevious : Button lateinit var optionSelectorList : MutableList<OptionSelector> lateinit var btnSubmit : Button lateinit var questionImageView : ImageView lateinit var tvTimer : TextView lateinit var timer : CountDownTimer private lateinit var mode : String lateinit var tvqNo : TextView private var appSwitchCount = 0 private var score = 0 private lateinit var loadingPB: ProgressBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_test_screen) btnPrevious = findViewById<Button>(R.id.btnPrev) btnNext = findViewById<Button>(R.id.btnNext) btnSubmit = findViewById<Button>(R.id.btnSubmit) loadingPB = findViewById(R.id.idPBTestLoading) studentId = intent.getStringExtra("studentId").toString() mode = intent.getStringExtra("mode").toString() loadingPB.visibility= View.VISIBLE questionImageView = findViewById(R.id.question_Image) tvTimer = findViewById(R.id.tvTimer) tvqNo = findViewById(R.id.tvqNo) questionImageView.visibility=View.GONE setUpFirestore() setUpEventListener() } fun updateStudentAttempt(quizId : String){ var selectedOptions : MutableList<String> = mutableListOf() var index = 1 while(index <= questions!!.size){ selectedOptions.add(optionSelectorList[index-1].userAnswer) index=index+1 } quizzes!![0].isAttempted=true if(studentId.length==0){ Toast.makeText(this,"can't varify student Id, try again later",Toast.LENGTH_SHORT).show() return } var attempt = Attempt(studentId,studentId,selectedOptions,score) updateStudentAttemptToFirebase(quizId,attempt) } private fun updateStudentAttemptToFirebase(quizId : String, attempt: Attempt){ var enrollmentCollection = FirebaseFirestore.getInstance().collection("quizAttempts") enrollmentCollection.whereEqualTo("quizId",quizId) .get() .addOnSuccessListener {querySnapshot -> if (querySnapshot.isEmpty) { // No document found, create a new one val newDocument = hashMapOf( "quizId" to quizId, "attemptList" to mutableListOf(attempt) ) // Add the new document to Firestore enrollmentCollection .add(newDocument) .addOnSuccessListener { documentReference -> Toast.makeText(this,"updated Successfully",Toast.LENGTH_SHORT).show() // New document added successfully // Handle success if needed } .addOnFailureListener { e -> // Handle failures } } else{ var document = querySnapshot.documents[0] val attemptList = document.get("attemptList") as MutableList<Attempt>? attemptList!!.add(attempt) document.reference.update("attemptList",attemptList) .addOnSuccessListener { Toast.makeText(this,"updated Successfully",Toast.LENGTH_SHORT).show() } .addOnFailureListener { } } } .addOnFailureListener { } } // private fun updateStudentAttemptToFirebase(quizId : String, attempt: Attempt){ // val collectionRef = FirebaseFirestore.getInstance().collection("quizAttempts").document(quizId) // collectionRef.update(studentId,attempt) // .addOnSuccessListener { // Toast.makeText(this,"Result updated successfully",Toast.LENGTH_SHORT).show() // } // .addOnFailureListener { // // } //// collectionRef.get().addOnSuccessListener { documentSnapshot -> //// if (documentSnapshot.exists()) { //// val data = documentSnapshot.data //// if (data != null) { //// val map = data as? MutableMap<String, Attempt> //// //// // Assuming "your_map_field_name" is the name of your map field in Firestore //// map?.let { //// // Update the value for a specific key in the map //// it[studentId]?.apply { //// // Update the values as needed //// //// } //// //// // Update the map field in Firestore //// collectionRef.update("your_map_field_name", map) //// .addOnSuccessListener { //// // Map field updated successfully //// } //// .addOnFailureListener { exception -> //// // Handle the failure to update the map field //// } //// } //// } //// } //// collectionRef.document(quizId).set(attempt) //// .addOnSuccessListener { //// Toast.makeText(this,"Result updated successfully",Toast.LENGTH_SHORT).show() //// }.addOnFailureListener { //// showProgressBar(false) //// Toast.makeText(this,"Some Error Occurred, Please Try Again",Toast.LENGTH_SHORT).show() //// } // } private fun setUpEventListener() { // timer.start() btnPrevious.setOnClickListener { index-- bindViews() } btnNext.setOnClickListener { index++ bindViews() } btnSubmit.setOnClickListener { if(mode=="teacher"){ return@setOnClickListener Toast.makeText(this,"preview ended",Toast.LENGTH_SHORT).show() super.onBackPressed() timer.cancel() finish() } // Toast.makeText(this,"ended",Toast.LENGTH_SHORT).show() showProgressBar(true) updateAttempt() calculateScore() if(mode!="teacher"){ // Toast.makeText(this,"mode implemented",Toast.LENGTH_SHORT).show() updateStudentAttempt(quizzes!![0].id) Log.d("mode imp",mode) // addResponses(quizzes!![0]) } // Toast.makeText(this,"mode implemented",Toast.LENGTH_SHORT).show() val intent = Intent(this,TeacherHomeActivity::class.java) startActivity(intent) finishAffinity() // Log.d("FINALQUIZ", questions.toString()) // val intent = Intent(this, ResultActivity::class.java) // val json = Gson().toJson(quizzes!![0]) //// Toast.makeText(this,json.toString(),Toast.LENGTH_SHORT).show() // intent.putExtra("QUIZ", json) // startActivity(intent) } } override fun onPause() { super.onPause() // Increment the counter when the user leaves the app appSwitchCount++ } override fun onResume() { super.onResume() // Check if the user has switched out of the app more than once if (appSwitchCount > 1) { // Show a dialog prompting the user about leaving the app multiple times showAlertDialog() } // Reset the counter when the user returns to the app } private fun showAlertDialog() { val alertDialogBuilder = AlertDialog.Builder(this) alertDialogBuilder.setTitle("Alert") alertDialogBuilder.setMessage("You have switched out of the app multiple times.") alertDialogBuilder.setPositiveButton("Submit") { _, _ -> // Perform the action to submit the test (e.g., click the submit button) // Replace the following line with your submit button click action clickSubmitButton() } alertDialogBuilder.setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss() } val alertDialog = alertDialogBuilder.create() alertDialog.show() if(appSwitchCount>2){ Toast.makeText(this,"Auto Submitted due to tab Switching",Toast.LENGTH_SHORT).show() clickSubmitButton() } } // Replace this function with your actual logic to click the submit button private fun clickSubmitButton() { btnSubmit.callOnClick() // Perform the action to click the submit button // For example: // submitButton.performClick() } override fun onBackPressed() { super.onBackPressed() timer.cancel() finish() } private fun addResponses(quiz : Quiz) { val collectionRef = FirebaseFirestore.getInstance().collection("quizzes") collectionRef.document(quiz.id).set(quiz) .addOnSuccessListener { Toast.makeText(this,"Result updated successfully",Toast.LENGTH_SHORT).show() }.addOnFailureListener { showProgressBar(false) Toast.makeText(this,"Some Error Occurred, Please Try Again",Toast.LENGTH_SHORT).show() } } private fun calculateScore() { score = 0 for (entry in quizzes!![0].questions.entries) { val question = entry.value if (question.answer == question.userAnswer) { score += quizzes!![0].marksPerQuestion } } // val txtScore = findViewById<TextView>(R.id.test_score) // txtScore.text = "Your Score : $score" quizzes!![0].score=score } private fun updateAttempt() { var index = 1 while(index <= questions!!.size){ questions!!["$index"]!!.userAnswer= optionSelectorList[index-1].userAnswer index=index+1 } quizzes!![0].isAttempted=true } private fun showProgressBar(bol : Boolean){ if(bol){ questionImageView.visibility=View.GONE loadingPB.visibility=View.VISIBLE } else{ questionImageView.visibility=View.VISIBLE loadingPB.visibility=View.GONE } } private fun bindViews() { //yet to implement firebase database and delete this dummydatafunction btnPrevious.visibility = View.GONE btnNext.visibility = View.GONE showProgressBar(true) if(index == 1){ //first question btnNext.visibility = View.VISIBLE } else if(index == questions!!.size) { // last question btnPrevious.visibility = View.VISIBLE } else{ // Middle btnPrevious.visibility = View.VISIBLE btnNext.visibility = View.VISIBLE } val optionList = findViewById<RecyclerView>(R.id.optionList) if(questions!!.size==0){ Toast.makeText(this,"No questions in the Test",Toast.LENGTH_SHORT).show() return } val question = questions!!["$index"] val qno = index tvqNo.text= "Q.$qno Single Choice" val imageMap = quizzes!![0].imMap val optionSelector = optionSelectorList[index-1] question?.let { loadBase64ImageWithUrl(imageMap[it.imageUrl],it.ytop,it.yend) // setImageWithData(it.imageUrl,it.ytop,it.yend); val optionAdapter = OptionAdapter(this, optionSelector,it,0) optionList.layoutManager = LinearLayoutManager(this) optionList.adapter = optionAdapter optionList.setHasFixedSize(true) } } private fun setUpFirestore() { firestore = FirebaseFirestore.getInstance() var id = intent.getStringExtra("id") if (id != null) { firestore.collection("quizzes").whereEqualTo("id",id) .get() .addOnSuccessListener { if(it != null && !it.isEmpty){ quizzes = it.toObjects(Quiz::class.java) questions = quizzes!![0].questions optionSelectorList = MutableList(questions!!.size) { OptionSelector(userAnswer = "neg")} bindViews() timer = object : CountDownTimer(quizzes!![0].duration.toLong(), 1000) { // Callback function, fired on regular interval override fun onTick(millisUntilFinished: Long) { val hours = TimeUnit.MILLISECONDS.toHours(millisUntilFinished) val minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(hours) val seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(minutes) - TimeUnit.HOURS.toSeconds(hours) val timerText = String.format("%02d:%02d:%02d", hours, minutes, seconds) tvTimer.text = timerText } // Callback function, fired // when the time is up override fun onFinish() { btnSubmit.callOnClick() } } showProgressBar(false) timer.start() } } } } private fun addDummyData() { questions = mutableMapOf("question1" to Question("https://www.researchgate.net/publication/255640421/figure/fig1/AS:392587958603776@1470611671200/Sample-image-and-its-feature-extraction-results-Left-Original-image-right-segmented.png",300,317,"option2","")) // questions!!.put("question2", questions!!["question1"]!!) val question3 = Question("https://drive.google.com/file/d/140erkr0zjU_Y52GUpxeCcqmkwa_Bx7Qt/view?usp=share_link") questions!!.put("question2", Question("kkk")) questions!!.put("question3",Question("kkdd")) quizzes = mutableListOf(Quiz("1","title", questions!!)) firestore = FirebaseFirestore.getInstance() val firebasecollection = firestore.collection("quizzes") firebasecollection.document("quiz1").set(quizzes!![0]) // questions = mutableMapOf("question1" to question3) } fun loadBase64ImageWithUrl(base64Image: String?, ytop: Int, yend: Int) { val decodedBytes = Base64.decode(base64Image, Base64.DEFAULT) val bitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size) val croppedBitmap = Bitmap.createBitmap( bitmap, 0, ytop, bitmap.width, yend - ytop ) Glide.with(questionImageView) .load(croppedBitmap) .into(questionImageView) showProgressBar(false) } private fun setImageWithData(imageUrl: String, ytop: Int, yend: Int) { val imageView = findViewById<ImageView>(R.id.question_Image) // Glide.with(this) // .load(imageUrl) // .into(imageView) // return // // Load the image using Glide Glide.with(this) .asBitmap() .load(imageUrl) .into(object : CustomTarget<Bitmap>() { override fun onResourceReady( resource: Bitmap, transition: Transition<in Bitmap>? ) { // Get the cropped portion of the image val croppedBitmap = Bitmap.createBitmap( resource, 0, // x-coordinate of the top-left corner of the cropped area ytop, // y-coordinate of the top-left corner of the cropped area resource.width, // width of the cropped area yend - ytop // height of the cropped area ) // Set the cropped bitmap to the ImageView val croppedImageView = findViewById<ImageView>(R.id.question_Image) croppedImageView.setImageBitmap(croppedBitmap) } override fun onLoadCleared(placeholder: Drawable?) { // Not implemented } }) } }
1
Kotlin
0
2
f295880dda54ac0deb42443aacf214c0dcdceab4
18,319
TestScanner
MIT License
geary-core/src/commonMain/kotlin/com/mineinabyss/geary/engine/GearyEngine.kt
MineInAbyss
306,093,350
false
null
package com.mineinabyss.geary.engine import com.mineinabyss.geary.components.ComponentInfo import com.mineinabyss.geary.components.events.EntityRemoved import com.mineinabyss.geary.context.QueryContext import com.mineinabyss.geary.datatypes.* import com.mineinabyss.geary.datatypes.maps.ClassToComponentMap import com.mineinabyss.geary.datatypes.maps.TypeMap import com.mineinabyss.geary.engine.archetypes.Archetype import com.mineinabyss.geary.helpers.componentId import com.mineinabyss.geary.helpers.parents import com.mineinabyss.geary.helpers.removeParent import com.mineinabyss.geary.helpers.toGeary import com.mineinabyss.geary.systems.GearyListener import com.mineinabyss.geary.systems.GearySystem import com.mineinabyss.geary.systems.QueryManager import com.mineinabyss.geary.systems.TickingSystem import com.mineinabyss.geary.systems.accessors.RelationWithData import kotlinx.atomicfu.atomic import kotlinx.atomicfu.locks.SynchronizedObject import kotlinx.atomicfu.locks.synchronized import kotlinx.coroutines.* import org.koin.core.component.inject import org.koin.core.logger.Logger import kotlin.coroutines.CoroutineContext import kotlin.reflect.KClass import kotlin.time.Duration /** * The default implementation of Geary's Engine. * * This engine uses [Archetype]s. Each component is an entity itself with an id associated with it. * We keep track of each entity's components in the form of it's [GearyType] stored in the [typeMap]. * * Learn more [here](https://github.com/MineInAbyss/Geary/wiki/Basic-ECS-engine-architecture). */ public open class GearyEngine(override val tickDuration: Duration) : TickingEngine(), QueryContext { protected val logger: Logger by inject() @PublishedApi internal val typeMap: TypeMap = TypeMap() override val queryManager: QueryManager by inject() private val currId = atomic(0L) final override val rootArchetype: Archetype = Archetype(this, GearyType(), 0) private val archetypes = mutableListOf(rootArchetype) private val removedEntities = EntityStack() private val classToComponentMap = ClassToComponentMap() override val coroutineContext: CoroutineContext = (CoroutineScope(Dispatchers.Default) + CoroutineName("Geary Engine")).coroutineContext public val archetypeCount: Int get() = archetypes.size private val archetypeWriteLock = SynchronizedObject() private val classToComponentMapLock = SynchronizedObject() private val registeredSystems: MutableSet<TickingSystem> = mutableSetOf() private val registeredListeners: MutableSet<GearyListener> = mutableSetOf() //TODO what data structure is most efficient here? private val queuedCleanup = mutableSetOf<Archetype>() private val runningAsyncJobs = mutableSetOf<Job>() private var iterationJob: Job? = null private val safeDispatcher = Dispatchers.Default.limitedParallelism(1) internal fun init() { //Register an entity for the ComponentInfo component, otherwise getComponentIdForClass does a StackOverflow val componentInfo = newEntity() classToComponentMap[ComponentInfo::class] = componentInfo.id componentInfo.set(ComponentInfo(ComponentInfo::class), noEvent = true) } override fun start(): Boolean { return super.start().also { if (it) { init() } } } /** Describes how to individually tick each system */ protected open suspend fun TickingSystem.runSystem() { doTick() } private fun createArchetype(prevNode: Archetype, componentEdge: GearyComponentId): Archetype { val arc = Archetype(this, prevNode.type.plus(componentEdge), archetypes.size).also { archetypes += it } arc.componentRemoveEdges[componentEdge] = prevNode prevNode.componentAddEdges[componentEdge] = arc queryManager.registerArchetype(arc) return arc } override fun newEntity(initialComponents: Collection<GearyComponent>): GearyEntity { val entity = try { removedEntities.pop() } catch (e: Exception) { currId.getAndIncrement().toGeary() } createRecord(entity, initialComponents) return entity } private fun createRecord(entity: GearyEntity, initialComponents: Collection<GearyComponent>) { val ids = initialComponents.map { componentId(it::class) or HOLDS_DATA } val addTo = getArchetype(GearyType(ids)) val record = Record(rootArchetype, -1) addTo.addEntityWithData( record, initialComponents.toTypedArray().apply { sortBy { addTo.indexOf(componentId(it::class)) } }, entity, ) typeMap.set(entity, record) } override fun addSystem(system: GearySystem) { // Track systems right at startup since they are likely going to tick very soon anyways and we don't care about // any hiccups at that point. when (system) { is TickingSystem -> { if (system in registeredSystems) return queryManager.trackQuery(system) registeredSystems.add(system) } is GearyListener -> { if (system in registeredListeners) return system.start() queryManager.trackEventListener(system) registeredListeners.add(system) } else -> system.onStart() } } override fun getRecord(entity: GearyEntity): Record = typeMap.get(entity) override fun setRecord(entity: GearyEntity, record: Record) { typeMap.set(entity, record) } override fun getComponentFor(entity: GearyEntity, componentId: GearyComponentId): GearyComponent? { val (archetype, row) = getRecord(entity) entity.getRecord() return archetype[row, componentId.let { if (it.hasRole(RELATION)) it else it.withRole(HOLDS_DATA) }] } override fun scheduleSystemTicking() { var tick = 0L launch { while (true) { tick(tick++) delay(tickDuration) } } } override fun getComponentsFor(entity: GearyEntity): Array<GearyComponent> { val (archetype, row) = getRecord(entity) return archetype.getComponents(row).also { array -> for (relation in archetype.relationsWithData) { val i = archetype.indexOf(relation.id) array[i] = RelationWithData(array[i], null, relation) } } } override fun getRelationsWithDataFor( entity: GearyEntity, kind: GearyComponentId, target: GearyEntityId, ): List<RelationWithData<*, *>> { val (arc, row) = getRecord(entity) return arc.getRelations(kind, target).map { relation -> RelationWithData( data = if (kind.hasRole(HOLDS_DATA)) arc[row, relation.id] else null, targetData = if (target.hasRole(HOLDS_DATA)) arc[row, relation.target.withRole(HOLDS_DATA)] else null, relation = relation ) } } override fun addComponentFor( entity: GearyEntity, componentId: GearyComponentId, noEvent: Boolean ) { getRecord(entity).apply { archetype.addComponent(this, componentId.withoutRole(HOLDS_DATA), !noEvent) } } override fun setComponentFor( entity: GearyEntity, componentId: GearyComponentId, data: GearyComponent, noEvent: Boolean ) { getRecord(entity).apply { // Only add HOLDS_DATA if this isn't a relation. All relations implicitly hold data currently and that bit // corresponds to the component part of the relation. val componentWithRole = componentId.withRole(HOLDS_DATA) archetype.setComponent(this, componentWithRole, data, !noEvent) } } override fun removeComponentFor(entity: GearyEntity, componentId: GearyComponentId): Boolean = getRecord(entity).run { val a = archetype.removeComponent(this, componentId.withRole(HOLDS_DATA)) val b = archetype.removeComponent(this, componentId.withoutRole(HOLDS_DATA)) a || b // return whether anything was changed } override fun hasComponentFor(entity: GearyEntity, componentId: GearyComponentId): Boolean = componentId in getRecord(entity).archetype override fun removeEntity(entity: GearyEntity, event: Boolean) { if (event) entity.callEvent(EntityRemoved()) // remove all children of this entity from the ECS as well entity.apply { children.forEach { // Remove self from the child's parents or remove the child if it no longer has parents if (parents == setOf(this)) it.removeEntity(event) else it.removeParent(this) } } val (archetype, row) = getRecord(entity) archetype.scheduleRemoveRow(row) typeMap.remove(entity) //add current id into queue for reuse removedEntities.push(entity) } override fun clearEntity(entity: GearyEntity) { val (archetype, row) = getRecord(entity) archetype.scheduleRemoveRow(row) rootArchetype.addEntityWithData(getRecord(entity), arrayOf()) } override fun getArchetype(id: Int): Archetype = archetypes[id] override fun getArchetype(type: GearyType): Archetype = synchronized(archetypeWriteLock) { var node = rootArchetype type.forEach { compId -> node = if (compId in node.componentAddEdges) node.componentAddEdges[compId] else createArchetype(node, compId) } return node } override fun getOrRegisterComponentIdForClass(kClass: KClass<*>): GearyComponentId = synchronized(classToComponentMapLock) { val id = classToComponentMap[kClass] if (id == (-1L).toULong()) return registerComponentIdForClass(kClass) return id } private fun registerComponentIdForClass(kClass: KClass<*>): GearyComponentId { val compEntity = newEntity(initialComponents = listOf(ComponentInfo(kClass))) classToComponentMap[kClass] = compEntity.id return compEntity.id } internal fun scheduleRemove(archetype: Archetype) { queuedCleanup += archetype } override fun runSafely(scope: CoroutineScope, job: Job) { launch(safeDispatcher) { iterationJob?.join() runningAsyncJobs += job job.invokeOnCompletion { launch(safeDispatcher) { runningAsyncJobs -= job } } job.start() } } override suspend fun tick(currentTick: Long): Unit = coroutineScope { // Create a job but don't start it val job = launch(start = CoroutineStart.LAZY) { cleanup() registeredSystems .filter { currentTick % (it.interval / tickDuration).toInt().coerceAtLeast(1) == 0L } .forEach { try { it.runSystem() } catch (e: Exception) { logger.error("Error while running system ${it::class.simpleName}") e.printStackTrace() } } } // Await completion of all other jobs iterationJob = job withContext(safeDispatcher) { runningAsyncJobs.joinAll() } // Tick all systems logger.debug("Started engine tick") job.start() job.join() iterationJob = null logger.debug("Finished engine tick") } private fun cleanup() { queuedCleanup.forEach { archetype -> archetype.cleanup() } queuedCleanup.clear() } }
19
Kotlin
9
23
b4e5b1b5365d600cdd5eda11ae4d4a0c8249165b
12,003
Geary
MIT License
kotlin-4-devs-java/src/test/kotlin/br/com/erudio/_0506/TestPalindrome.kt
leandrocgsi
463,957,505
false
null
package br.com.erudio._0506 import br.com.erudio.section05._0507.isPalindrome import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test /* private fun isPalindrome(str: String): Boolean { TODO("not implemented") } */ class Test { @Test fun `"civic" is a palindrome`() { isPalindrome("civic") shouldBeEqualTo true } @Test fun `" civic" is not a palindrome`() { isPalindrome(" civic") shouldBeEqualTo false } @Test fun `"civic " is not a palindrome`() { isPalindrome("civic ") shouldBeEqualTo false } @Test fun `"greetings" is not a palindrome`() { isPalindrome("greetings") shouldBeEqualTo false } @Test fun `"1000000001" a palindrome`() { isPalindrome("1000000001") shouldBeEqualTo true } @Test fun `"Fish hsif" is not a palindrome`() { isPalindrome("Fish hsif") shouldBeEqualTo false } @Test fun `"pennep" a palindrome`() { isPalindrome("pennep") shouldBeEqualTo true } }
0
Kotlin
1
2
fed429722c6590867027c18464cc642b8a42135a
1,044
kotlin-4-devs-java
Apache License 2.0
app/src/main/java/com/mty/bangcalendar/ui/search/SearchViewModel.kt
mty1122
485,456,860
false
null
package com.mty.bangcalendar.ui.search import android.graphics.drawable.Drawable import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import com.mty.bangcalendar.logic.Repository import com.mty.bangcalendar.logic.model.Event class SearchViewModel : ViewModel() { private val searchEventLiveData = MutableLiveData<Int>() val event: LiveData<Event?> = Transformations.switchMap(searchEventLiveData) { Repository.getEventById(it) } fun getEventById(id: Int) { searchEventLiveData.value = id } private val searchCharacterLiveData = MutableLiveData<String>() val character = Transformations.switchMap(searchCharacterLiveData) { Repository.getCharacterByName(it) } fun getCharacterByName(name: String) { searchCharacterLiveData.value = name } suspend fun getEventPic(eventId: String, onPicReady: (Drawable) -> Unit) { Repository.getEventPic(eventId)?.let { onPicReady(it) } } }
0
Kotlin
0
0
bbf2f22bc7ac93b150a0b8454227576ab4189069
1,087
BangCalendar
Apache License 2.0
build-logic/wasm-builder/icu/src/main/kotlin/ru/pixnews/wasm/builder/icu/IcuBuildHostToolchainTask.kt
illarionov
769,429,996
false
{"Kotlin": 1268944, "C": 66048, "C++": 61910}
/* * Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. * SPDX-License-Identifier: Apache-2.0 */ package ru.pixnews.wasm.builder.icu import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.ProjectLayout import org.gradle.api.model.ObjectFactory import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.Internal import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity.RELATIVE import org.gradle.api.tasks.TaskAction import org.gradle.kotlin.dsl.property import org.gradle.process.ExecOperations import ru.pixnews.wasm.builder.icu.IcuBuildDefaults.ICU_BUILD_TOOLCHAIN_DIR import java.io.File import javax.inject.Inject /** * Builds the ICU toolchain for the local system, which is then used in cross-compilation * to generate and package data. * * https://unicode-org.github.io/icu/userguide/icu4c/build.html#how-to-cross-compile-icu */ @CacheableTask public abstract class IcuBuildHostToolchainTask @Inject constructor( private val execOperations: ExecOperations, objects: ObjectFactory, layout: ProjectLayout, ) : DefaultTask() { @get:InputDirectory @PathSensitive(RELATIVE) public val icuSource: DirectoryProperty = objects.directoryProperty() @get:OutputDirectory @Optional public val outputDirectory: DirectoryProperty = objects.directoryProperty().convention( layout.buildDirectory.dir(ICU_BUILD_TOOLCHAIN_DIR), ) @get:Internal public val maxJobs: Property<Int> = objects.property<Int>().convention( Runtime.getRuntime().availableProcessors(), ) private val icuConfigurePath: File get() = icuSource.file("source/configure").get().asFile @TaskAction public fun build() { buildToolchain() } private fun buildToolchain() { val dstDir = outputDirectory.get().asFile dstDir.mkdirs() val hostEnv = System.getenv().filterKeys { it == "PATH" } execOperations.exec { commandLine = listOf(icuConfigurePath.absolutePath) workingDir = dstDir environment = hostEnv }.rethrowFailure().assertNormalExitValue() execOperations.exec { commandLine = listOf("gmake", "-j${maxJobs.get()}") workingDir = dstDir environment = hostEnv }.rethrowFailure().assertNormalExitValue() } }
1
Kotlin
0
2
6ed3a38f52b22f1481cad4cecd72943a018a5dd4
2,758
wasm-sqlite-open-helper
Apache License 2.0
app/src/main/java/com/sohezsoft/student/data/repository/structure/setting/SettingItemData.kt
sohez
736,656,472
false
{"Kotlin": 146004}
package com.sohezsoft.student.data.repository.structure.setting data class SettingItemData( val id:Int, val name:String, val icon : Int, )
0
Kotlin
0
3
263dc5174aead634af62c925be850fc3093a86c6
152
StudentPortalApp
MIT License
chat/src/main/java/com/crafttalk/chat/domain/repository/IAuthRepository.kt
AndSky90
400,089,101
true
{"Kotlin": 334797}
package com.crafttalk.chat.domain.repository import com.crafttalk.chat.domain.entity.auth.Visitor import com.crafttalk.chat.presentation.ChatEventListener import java.io.File interface IAuthRepository { fun logIn( visitor: Visitor, successAuthUi: (() -> Unit)?, failAuthUi: (() -> Unit)?, successAuthUx: () -> Unit, failAuthUx: () -> Unit, getPersonPreview: (personId: String) -> String?, updatePersonName: (personId: String?, currentPersonName: String?) -> Unit, chatEventListener: ChatEventListener? ) fun logOut(uuid: String, filesDir: File) }
0
null
0
0
23a69456b0616dc4cf26c1915edc4c00d3f783c5
624
crafttalk-android-sdk
Apache License 2.0
cordapp/src/main/kotlin/com/survey/flows/TradeBuildingFlow.kt
CaisR3
141,169,653
false
{"Kotlin": 68056, "Java": 1893, "HTML": 672}
package com.survey.flows import co.paralleluniverse.fibers.Suspendable import com.survey.Helper.getSurveyByLinearId import com.survey.SurveyContract import com.survey.SurveyContract.Companion.SURVEY_CONTRACT_ID import com.survey.SurveyState import net.corda.confidential.IdentitySyncFlow import net.corda.core.contracts.Command import net.corda.core.contracts.UniqueIdentifier import net.corda.core.flows.* import net.corda.core.identity.Party import net.corda.core.node.services.vault.builder import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.TransactionBuilder import net.corda.core.utilities.ProgressTracker import net.corda.core.utilities.unwrap import net.corda.finance.POUNDS import net.corda.finance.contracts.asset.Cash import javax.annotation.Signed object TradeBuildingFlow{ // ************* // TradeBuildingFlow : buyer Responder flow that verifies the encoded survey has been recieved // and procedes to issue payment to the seller and royalty to the initial issuer. // ************* @InitiatedBy(TradeFlow.Initiator::class) @StartableByRPC class Responder(val counterPartySession: FlowSession) : FlowLogic<Unit>() { @Suspendable override fun call(): Unit { val builder = counterPartySession.receive<TransactionBuilder>().unwrap { it } val surveyState = builder.outputStates().first().data as SurveyState if(surveyState.owner == ourIdentity) { Cash.generateSpend(serviceHub, builder, (surveyState.resalePrice * 0.8).POUNDS, counterPartySession.counterparty) Cash.generateSpend(serviceHub, builder, (surveyState.resalePrice * 0.2).POUNDS, surveyState.issuer) } else { throw FlowException("We're not the new survey owner, not paying!") } builder.verify(serviceHub) val ptx = serviceHub.signInitialTransaction(builder) counterPartySession.send(ptx) } } }
1
Kotlin
2
1
1eeab93d94845022ed802172bfd23d0f095a0848
2,010
survey
Apache License 2.0
language-detector/src/main/kotlin/edu/ucu/languagedetector/infrastructure/evaluator/EvaluatorConfiguration.kt
Yaroslaww-1
649,850,018
false
null
package edu.ucu.languagedetector.infrastructure.evaluator import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.ConfigurationPropertiesScan @ConfigurationProperties(prefix = "evaluator") @ConfigurationPropertiesScan data class EvaluatorConfiguration( val host: String ) {}
0
Kotlin
0
0
e89100dd4f815c422f498709dfea240aebeafb19
350
twitter-analyser
MIT License
domain/src/main/kotlin/com/example/domain/user/Gender.kt
PARKPARKWOO
737,782,254
false
{"Kotlin": 262302}
package com.example.domain.user enum class Gender { MALE, FEMALE, }
11
Kotlin
0
0
4611e34d120ac1251f94c984ca3096b2a36bf2e6
77
barbellrobot-backend
Apache License 2.0
src/main/kotlin/ru/qiwi/devops/mission/control/web/security/Grant.kt
qiwi
329,911,226
false
null
package ru.qiwi.devops.mission.control.web.security import org.springframework.security.core.authority.SimpleGrantedAuthority enum class Grant { READ_CLUSTERS, READ_DEPLOYMENTS, READ_LOGS, RESTART_DEPLOYMENT, SCALE_DEPLOYMENT; val publicName = this.name.toLowerCase() override fun toString() = publicName fun toAuthority() = SimpleGrantedAuthority(publicName) companion object { fun parse(name: String): Grant { return valueOf(name.toUpperCase()) } } }
1
Kotlin
1
1
a5b4a1dc716841bbf0439fa309e3a2b85bbeb1d3
526
k8s-mission-control
MIT License
app/src/main/java/com/breezefieldaereo/fcm/api/UpdateDeviceTokenRepo.kt
DebashisINT
876,752,370
false
{"Kotlin": 16011993, "Java": 1030008}
package com.breezefieldaereo.fcm.api import com.breezefieldaereo.app.Pref import com.breezefieldaereo.base.BaseResponse import io.reactivex.Observable /** * Created by Saikat on 27-02-2019. */ class UpdateDeviceTokenRepo(val apiService: UpdateDeviceTokenApi) { fun updateDeviceToken(deviceToken: String): Observable<BaseResponse> { return apiService.updateDeviceToken(Pref.user_id!!, Pref.session_token!!, deviceToken, "Android") } }
0
Kotlin
0
0
19b7be34bb719573e71738d1e91a26681a4a7bde
454
Aereo
Apache License 2.0
shared/java/top/fpsmaster/features/impl/render/MotionBlur.kt
FPSMasterTeam
816,161,662
false
{"Java": 620089, "Kotlin": 396547, "GLSL": 2647}
package top.fpsmaster.features.impl.render import net.minecraft.client.Minecraft import net.minecraft.client.gui.ScaledResolution import net.minecraft.client.renderer.GlStateManager import net.minecraft.client.renderer.OpenGlHelper import net.minecraft.client.renderer.Tessellator import net.minecraft.client.renderer.vertex.DefaultVertexFormats import net.minecraft.client.shader.Framebuffer import org.lwjgl.opengl.GL11 import top.fpsmaster.event.Subscribe import top.fpsmaster.event.events.EventMotionBlur import top.fpsmaster.features.manager.Category import top.fpsmaster.features.manager.Module import top.fpsmaster.features.settings.impl.NumberSetting import top.fpsmaster.interfaces.ProviderManager import top.fpsmaster.utils.OptifineUtil import top.fpsmaster.utils.Utility import top.fpsmaster.wrapper.renderEngine.bufferbuilder.WrapperBufferBuilder class MotionBlur : Module("MotionBlur", Category.RENDER) { private var blurBufferMain: Framebuffer? = null private var blurBufferInto: Framebuffer? = null private var multiplier = NumberSetting("Multiplier", 2, 0, 10, 0.5) init { addSettings(multiplier) } override fun onEnable() { super.onEnable() if (OptifineUtil.isFastRender()) { OptifineUtil.setFastRender(false) } } private fun checkFramebufferSizes(framebuffer: Framebuffer?, width: Int, height: Int): Framebuffer { var framebuffer = framebuffer if (framebuffer == null || framebuffer.framebufferWidth != width || framebuffer.framebufferHeight != height) { if (framebuffer == null) { framebuffer = Framebuffer(width, height, true) } else { framebuffer.createBindFramebuffer(width, height) } framebuffer.setFramebufferFilter(9728) } return framebuffer } private fun drawTexturedRectNoBlend( x: Float, y: Float, width: Float, height: Float, uMin: Float, uMax: Float, vMin: Float, vMax: Float, filter: Int ) { GlStateManager.enableTexture2D() GL11.glTexParameteri(3553, 10241, filter) GL11.glTexParameteri(3553, 10240, filter) val tessellator = Tessellator.getInstance() val worldrenderer = WrapperBufferBuilder(tessellator) worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX) worldrenderer.pos(x, y + height, 0.0).tex(uMin.toDouble(), vMax.toDouble()).endVertex() worldrenderer.pos(x + width, y + height, 0.0).tex(uMax.toDouble(), vMax.toDouble()).endVertex() worldrenderer.pos(x + width, y, 0.0).tex(uMax.toDouble(), vMin.toDouble()).endVertex() worldrenderer.pos(x, y, 0.0).tex(uMin.toDouble(), vMin.toDouble()).endVertex() tessellator.draw() GL11.glTexParameteri(3553, 10241, 9728) GL11.glTexParameteri(3553, 10240, 9728) } @Subscribe fun renderOverlay(event: EventMotionBlur?) { if (ProviderManager.mcProvider.getPlayer() == null || ProviderManager.mcProvider.getPlayer()!!.ticksExisted < 20) return if (mc.currentScreen == null) { if (OpenGlHelper.isFramebufferEnabled()) { val sr = ScaledResolution(Minecraft.getMinecraft()) val width = mc.framebuffer.framebufferWidth val height = mc.framebuffer.framebufferHeight GlStateManager.matrixMode(5889) GlStateManager.loadIdentity() GlStateManager.ortho( 0.0, (width / sr.scaleFactor).toDouble(), (height / sr.scaleFactor).toDouble(), 0.0, 2000.0, 4000.0 ) GlStateManager.matrixMode(5888) GlStateManager.loadIdentity() GlStateManager.translate(0f, 0f, -2000f) blurBufferMain = checkFramebufferSizes(blurBufferMain, width, height) blurBufferInto = checkFramebufferSizes(blurBufferInto, width, height) blurBufferInto!!.framebufferClear() blurBufferInto!!.bindFramebuffer(true) OpenGlHelper.glBlendFunc(770, 771, 0, 1) GlStateManager.disableLighting() GlStateManager.disableFog() GlStateManager.disableBlend() mc.framebuffer.bindFramebufferTexture() GlStateManager.color(1f, 1f, 1f, 1f) drawTexturedRectNoBlend( 0.0f, 0.0f, (width / sr.scaleFactor).toFloat(), (height / sr.scaleFactor).toFloat(), 0.0f, 1.0f, 0.0f, 1.0f, 9728 ) GlStateManager.enableBlend() blurBufferMain!!.bindFramebufferTexture() GlStateManager.color(1f, 1f, 1f, multiplier.value.toFloat() / 10 - 0.1f) drawTexturedRectNoBlend( 0f, 0f, (width / sr.scaleFactor).toFloat(), (height / sr.scaleFactor).toFloat(), 0f, 1f, 1f, 0f, 9728 ) mc.framebuffer.bindFramebuffer(true) blurBufferInto!!.bindFramebufferTexture() GlStateManager.color(1f, 1f, 1f, 1f) GlStateManager.enableBlend() OpenGlHelper.glBlendFunc(770, 771, 1, 771) drawTexturedRectNoBlend( 0.0f, 0.0f, (width / sr.scaleFactor).toFloat(), (height / sr.scaleFactor).toFloat(), 0.0f, 1.0f, 0.0f, 1.0f, 9728 ) val tempBuff = blurBufferMain blurBufferMain = blurBufferInto blurBufferInto = tempBuff } } } }
14
Java
34
97
34a00cc1834e80badd0df6f5d17ae027163d0ce9
6,192
FPSMaster
MIT License
app/src/main/java/com/spin/id/api/response/feed/like/LikeFeedData.kt
RifqiFadhell
501,564,017
false
null
package com.spin.id.api.response.feed.like data class LikeFeedData( val like_status: String )
0
Kotlin
0
0
ac0082e9f8ce71f3e17c758e59d925bfed2ec753
98
SPIN
Apache License 2.0
src/main/kotlin/io/ghostbuster91/docker/compose/logger/keyboard/KeyboardLayout.kt
ghostbuster91
156,066,934
false
null
package io.ghostbuster91.docker.compose.logger.keyboard import com.googlecode.lanterna.input.KeyStroke import io.ghostbuster91.docker.compose.logger.Action import io.ghostbuster91.docker.compose.logger.Effect import io.ghostbuster91.docker.compose.logger.UserCommand interface KeyboardLayout : AddServiceMapping, RemoveServiceMapping, ControlMapping, SingleServiceMapping, ServiceMapping, EffectsMapping { fun mapCommand(keyStroke: KeyStroke) : Action } interface AddServiceMapping { fun isAddKey(keyStroke: KeyStroke): Boolean fun mapAddKey(keyStroke: KeyStroke): UserCommand.Add } interface RemoveServiceMapping { fun isRemoveKey(keyStroke: KeyStroke): Boolean fun mapRemoveKey(keyStroke: KeyStroke): UserCommand.Remove } interface ControlMapping { fun isControlKey(keyStroke: KeyStroke): Boolean fun mapControlKey(keyStroke: KeyStroke): UserCommand.Control fun getControlMapping() : List<String> } interface SingleServiceMapping { fun isSingleServiceKey(keyStroke: KeyStroke): Boolean fun mapSingleServiceKey(keyStroke: KeyStroke): UserCommand.Single } interface EffectsMapping { fun isEffectKey(keyStroke: KeyStroke) : Boolean fun mapEffectKey(keyStroke: KeyStroke) : Effect }
2
Kotlin
0
2
b4eac8d1b30cfa9fdf900c035c89bbefc483e710
1,235
dcl-fast-switcher
MIT License