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/com/amazon/ion/plugin/intellij/editor/typed/ProcessPairedBracesTypeEventHandler.kt
amazon-ion
60,200,377
false
{"Kotlin": 99919, "Lex": 14583, "HTML": 659}
package com.amazon.ion.plugin.intellij.editor.typed import com.amazon.ion.plugin.intellij.psi.IonFile import com.amazon.ion.plugin.intellij.psi.IonTypes.LOB_END import com.amazon.ion.plugin.intellij.psi.IonTypes.RBRACE import com.amazon.ion.plugin.intellij.psi.IonTypes.RBRACKET import com.amazon.ion.plugin.intellij.psi.IonTypes.RPAREN import com.intellij.codeInsight.highlighting.BraceMatchingUtil import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.project.Project import com.intellij.psi.TokenType.BAD_CHARACTER private val logger = logger<ProcessPairedBracesTypeEventHandler>() /** * Event Handler which processes a missed use case of paired braces. * * Typically all paired braces are handled through {@see IonCodeBraceMatcher}, however * there is a situation where the ordered of brace pairs returned from IonCodeBraceMatcher causes * certain brace pairs from being missed due to the brace matching algorithm matching braces outside * of the parent braces like this: * * Bug: * { * list: [ * { <- start brace * ] * } <- end brace * * This brace matcher will look to see if the currently typed brace has a match within any parent braces. */ class ProcessPairedBracesTypeEventHandler : IonTypeEventHandler { override fun characterTyped(character: Char, project: Project, editor: EditorEx, file: IonFile) { // Check if the character is an open brace, if not then short circuit. val bracePair = BracePairs.firstOrNull { character.toString() == it.left } ?: return // Create an iterator at the offset and check if we run into a closing brace. val iterator = editor.createIteratorAtTyped() val offset = editor.caretModel.offset // Resolve the brace pair matcher and find the opposite brace type. val bracePairMatcher = BraceMatchingUtil.getBraceMatcher(file.fileType, iterator) val oppositeBraceType = bracePairMatcher.getOppositeBraceTokenType(iterator.tokenType) val firstCloseBracketOrBadCharacter = iterator.sequence().first { CloseBraceElements.contains(it) || it == BAD_CHARACTER } // Check if there is a bad character before we reach the correct closing bracket // for the brace pair. if (firstCloseBracketOrBadCharacter != oppositeBraceType) { logger.debug { "TypeEventHandler '$character': Adding closing bracket '${bracePair.right}'" } editor.document.insertString(offset, bracePair.right) } } } private data class BracePair(val left: String, val right: String) private val BracePairs = listOf( BracePair("(", ")"), BracePair("{", "}"), BracePair("[", "]") ) private val CloseBraceElements = setOf(RBRACE, RPAREN, RBRACKET, LOB_END)
13
Kotlin
22
29
3dab4e1787dee0e4ddb9c5336c781ec1652cd412
2,872
ion-intellij-plugin
Apache License 2.0
envoy-control-tests/src/main/kotlin/pl/allegro/tech/servicemesh/envoycontrol/config/envoy/ResponseWithBody.kt
allegro
209,142,074
false
null
package pl.allegro.tech.servicemesh.envoycontrol.config.envoy import com.fasterxml.jackson.databind.ObjectMapper import okhttp3.Response import pl.allegro.tech.servicemesh.envoycontrol.config.service.EchoContainer data class ResponseWithBody(val response: Response) { companion object { private val objectMapper by lazy { ObjectMapper() } } val body = response.body?.string() ?: "" fun isFrom(echoContainer: EchoContainer) = body.contains(echoContainer.response) fun isOk() = response.isSuccessful fun bodyJsonField(field: String) = objectMapper.readTree(body).at(field) }
48
null
31
99
58be4d6702680854152a51d3559872e43e45df8c
610
envoy-control
Apache License 2.0
src/main/kotlin/com/vincentcarrier/kgrid/core/MutableGrid.kt
Vincent-Carrier
130,376,173
false
null
package com.vincentcarrier.kgrid.core interface MutableGrid<E> : Grid<E> { operator fun set(x: Int, y: Int, value: E) } fun <E> MutableGrid<E>.swap(x1: Int, y1: Int, x2: Int, y2: Int) { val value1 = this[x1, y1] this[x1, y1] = this[x2, y2] this[x2, y2] = value1 }
0
Kotlin
0
2
8f3fd0be509cd3f2791f04c3a0b9bd8b7eb2e843
270
kgrid
MIT License
src/jvmMain/kotlin/de/datlag/k2k/connect/ConnectionClient.kt
DatL4g
465,054,141
false
{"Kotlin": 21896}
package de.datlag.k2k.connect import de.datlag.k2k.Host import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import java.io.DataOutputStream import java.net.InetAddress import java.net.Socket actual object ConnectionClient { internal actual fun send( bytes: ByteArray, host: Host, port: Int, scope: CoroutineScope ): Job = scope.launch(Dispatchers.IO) { var socket: Socket? = null try { val destinationAddress = InetAddress.getByName(host.hostAddress) socket = Socket(destinationAddress, port) val output = DataOutputStream(socket.getOutputStream()) output.writeInt(bytes.size) output.write(bytes) } catch (ignored: Exception) { // Host is unknown // or // Socket closed // or // Socket not connected // or // Socket output shutdown } finally { socket?.close() } } }
1
Kotlin
0
20
f2b284ab7ec0961f44e298b78b3054649f9cbd33
1,098
Klient2Klient
Apache License 2.0
compiler/testData/diagnostics/tests/multiplatform/java/varPropertyAgainstJavaField.kt
JetBrains
3,432,266
false
null
// MODULE: m1-common // FILE: common.kt expect class Foo { var foo: Int } // MODULE: m2-jvm()()(m1-common) // FILE: jvm.kt actual typealias Foo = JavaFoo // FILE: JavaFoo.java public class JavaFoo { public int foo = 0; }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
231
kotlin
Apache License 2.0
core-starter/src/main/kotlin/com/labijie/application/exception/PermissionDeniedException.kt
hongque-pro
309,874,586
false
{"Kotlin": 1035991, "Java": 72766}
package com.labijie.application.exception import com.labijie.application.ApplicationErrors import com.labijie.application.ErrorCodedException /** * * @author lishiwen * @date 19-12-18 * @since JDK1.8 */ class PermissionDeniedException(message:String? = null) : ErrorCodedException(ApplicationErrors.PermissionDenied, message?:"Permission Denied")
0
Kotlin
0
7
864eee31688dcb57ff186ab66cfedebacdee0e8d
358
application-framework
Apache License 2.0
app/src/main/java/com/cesarwillymc/jpmorgantest/presentation/MainViewModel.kt
cesarwillymc
699,947,692
false
{"Kotlin": 134046, "Java": 3910}
package com.cesarwillymc.jpmorgantest.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.cesarwillymc.jpmorgantest.domain.usecase.GetRecentlySearchedUseCase import com.cesarwillymc.jpmorgantest.ui.navigation.route.MainRoute import com.cesarwillymc.jpmorgantest.util.state.isSuccess import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( private val getRecentlySearchedUseCase: GetRecentlySearchedUseCase ) : ViewModel() { private val _startDestination = MutableStateFlow<String?>(null) val startDestination get() = _startDestination init { loadRecentlySearched() } fun loadRecentlySearched() { viewModelScope.launch { getRecentlySearchedUseCase().let { result -> when { result.isSuccess -> { _startDestination.update { MainRoute.Detail.path } } else -> { _startDestination.update { MainRoute.Search.path } } } } } } }
0
Kotlin
0
0
832154825f03a17ff81b87c0ae9b3e6edefbbd5c
1,306
JPMorganTest
Apache License 2.0
src/main/kotlin/io/dp/RemovingBoxes.kt
jffiorillo
138,075,067
false
{"Gradle Kotlin DSL": 2, "Shell": 2, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 1, "Java": 11, "Kotlin": 286, "Markdown": 3}
package io.dp import io.utils.runTests const val MAX_INPUT_SIZE = 100 // https://leetcode.com/problems/remove-boxes/ class RemovingBoxes { fun execute(input: IntArray, dp: Array<Array<IntArray>> = Array(MAX_INPUT_SIZE) { Array(MAX_INPUT_SIZE) { IntArray(MAX_INPUT_SIZE) } }, left: Int = 0, right: Int = input.size - 1, s: Int = 0): Int { var leftTrim = left var streak = s if (left > right) return 0 if (dp[left][right][streak] > 0) { return dp[left][right][streak] } if (streak == 0) streak = 1 while (leftTrim < right && input[leftTrim] == input[leftTrim + 1]) { leftTrim++ streak++ } var max = execute(input, dp, leftTrim + 1, right, 0) + streak * streak for (index in leftTrim..right) { if (input[index] == input[left]) { max = maxOf(max, execute(input, dp, leftTrim, index - 1, streak + 1) + execute(input, dp, index + 1, right, 0)) } } dp[left][right][s] = max return dp[left][right][s] } } fun main() { runTests(listOf( intArrayOf(1, 3, 2, 2, 2, 3, 4, 3, 1) to 23 )) { (input, value) -> value to RemovingBoxes().execute(input) } }
1
null
1
1
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,218
coding
MIT License
demo/svg/swing/src/main/kotlin/demo/svgMapping/ReferenceSvgDemo.kt
JetBrains
571,767,875
false
{"Kotlin": 175627}
/* * Copyright (c) 2023 JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package demo.svgMapping import demo.svgMapping.utils.DemoWindow import demo.svgModel.ReferenceSvgModel fun main() { DemoWindow("Reference SVG", listOf(ReferenceSvgModel.createModel())).open() }
3
Kotlin
2
88
1649c1d8232895073ad31baea0625bf29f925b17
344
lets-plot-skia
MIT License
ff4j-spring-boot-autoconfigure/src/main/kotlin/org/ff4j/spring/boot/autoconfigure/FF4JConfiguration.kt
DerekRoy
156,486,921
true
{"Maven POM": 6, "Ignore List": 1, "Text": 2, "YAML": 2, "Markdown": 1, "Java": 44, "XML": 1, "Kotlin": 54, "Gherkin": 14}
/* * * 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. * * Copyright 2013-2016 the original author or authors. */ package org.ff4j.spring.boot.autoconfigure import org.ff4j.FF4j import org.springframework.boot.autoconfigure.condition.ConditionalOnClass import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration /** * Created by Paul * * @author [<NAME>](mailto:<EMAIL>) */ @Configuration @ConditionalOnClass(FF4j::class) @ComponentScan(value = ["org.ff4j.spring.boot.web.api", "org.ff4j.services", "org.ff4j.aop", "org.ff4j.spring"]) class FF4JConfiguration { val fF4j: FF4j @Bean @ConditionalOnMissingBean get() = FF4j() }
0
Java
0
0
563c6d27501bc54f9308024d9efd33d331e22f8d
1,350
ff4j-spring-boot-starter-parent
Apache License 2.0
app/src/main/java/com/example/cityapiclient/MainActivity.kt
santansarah
517,438,488
false
{"Kotlin": 51943}
package com.example.cityapiclient import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.lifecycle.lifecycleScope import com.example.cityapiclient.data.UserPreferencesManager import com.example.cityapiclient.presentation.AppRoot import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.runBlocking import javax.inject.Inject @AndroidEntryPoint class MainActivity : ComponentActivity() { /** * Use Hilt to get my Datastore. */ @Inject lateinit var userPreferencesManager: UserPreferencesManager @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { val windowSize = calculateWindowSizeClass(this) // uncomment this to test onboarding screens. /* runBlocking { userPreferencesManager.setLastOnboardingScreen(0) }*/ /** * Call my container here, which provides the background for all layouts * and serves the content, depending on the current screen size. */ AppRoot(windowSize = windowSize, userPreferencesManager) } } }
0
Kotlin
2
7
fce45824a4c75e7f076029c98afa15d2fe70b1f0
1,486
city-api-client
MIT License
secdra-account/src/main/kotlin/com/junjie/secdraaccount/service/AccountService.kt
lipstick-49
208,569,806
true
{"Kotlin": 244725, "HTML": 4151}
package com.junjie.secdraaccount.service import com.junjie.secdradata.database.primary.entity.User import com.junjie.secdradata.database.account.entity.Account import java.util.* interface AccountService { fun get(id: String): Account /** * 是否存在手机 */ fun existsByPhone(phone: String): Boolean /** * 注册 */ fun signUp(phone: String, password: String, rePasswordDate: Date): Account /** * 登录 */ fun signIn(phone: String, password: String): Account /** * 修改密码 */ fun forgot(phone: String, password: String, rePasswordTime: Date): User }
0
null
0
0
b4317e70fad3256c82a9c418cb2aa25fe14ef62f
614
secdra
MIT License
src/main/kotlin/com/github/mrgaabriel/ayla/website/Website.kt
MrGaabriel
143,538,052
false
null
package com.github.mrgaabriel.ayla.website import com.github.mrgaabriel.ayla.utils.extensions.ayla import com.github.mrgaabriel.ayla.utils.logger import org.jooby.Err import org.jooby.Kooby import org.jooby.Request import java.io.File class Website(val websiteUrl: String) : Kooby({ val logger by logger() port(ayla.config.websitePort) assets("/**", File("frontend").toPath()).onMissing(0) before { req, rsp -> req.set("start", System.currentTimeMillis()) logger.info("${req.ip} -> ${req.method()} ${req.path()} (${req.userAgent()})") } complete("*") { req, rsp, cause -> if (cause.isPresent) { val cause = cause.get() if (cause is Err) { if (cause.statusCode() == 404) return@complete } logger.error("${req.ip} -> ${req.method()} ${req.path()} (${req.userAgent()}) - ERROR!", cause) return@complete } val start = req.get<Long>("start") logger.info("${req.ip} -> ${req.method()} ${req.path()} (${req.userAgent()}) - OK! ${System.currentTimeMillis() - start}ms") } err { req, rsp, err -> if (err.statusCode() == 404) { rsp.send("Erro 404!!!") } } use(Routes()) }) fun Request.userAgent(): String { return this.header("User-Agent").value() } val Request.ip: String get() { val forwardedForHeader = this.header("X-Forwarded-For") return if (forwardedForHeader.isSet) forwardedForHeader.value() else this.ip() } val Request.path: String get() { val queryString = if (this.queryString().isPresent) "?" + this.queryString().get() else "" return this.path() + queryString }
20
Kotlin
1
4
51768344e6b0b53fbbb5fb298cb88dea848a5faa
1,809
Ayla
MIT License
samples/connectivity/bluetooth/ble/src/main/java/com/example/platform/connectivity/bluetooth/ble/FindDevicesSample.kt
android
623,336,962
false
null
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.platform.connectivity.bluetooth.ble import android.Manifest import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.os.Build import androidx.annotation.RequiresApi import androidx.annotation.RequiresPermission import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.core.content.getSystemService import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.MultiplePermissionsState import com.google.accompanist.permissions.rememberMultiplePermissionsState import com.google.android.catalog.framework.annotations.Sample import kotlinx.coroutines.launch import java.util.concurrent.TimeUnit @RequiresApi(Build.VERSION_CODES.M) @Sample( name = "Find devices sample", description = "This example will demonstrate how to scanning for Low Energy Devices", documentation = "https://developer.android.com/guide/topics/connectivity/bluetooth" ) @Composable fun FindDevicesSample() { val context = LocalContext.current val bluetoothManager = context.getSystemService<BluetoothManager>() if (bluetoothManager == null || bluetoothManager.adapter == null) { Text(text = "Sample not supported in this device. Missing the Bluetooth Manager") } else { FindBLEDevicesScreen(FindDeviceController(bluetoothManager.adapter)) } } @SuppressLint("MissingPermission") @RequiresApi(Build.VERSION_CODES.M) @OptIn(ExperimentalPermissionsApi::class) @Composable private fun FindBLEDevicesScreen( findDeviceController: FindDeviceController, ) { val multiplePermissionsState = rememberMultiplePermissionsState(FindDeviceController.bluetoothPermissionSet) Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { if (multiplePermissionsState.allPermissionsGranted) { ListOfDevicesWidget(findDeviceController) } else { PermissionWidget(multiplePermissionsState) } } } @OptIn(ExperimentalPermissionsApi::class) @Composable private fun PermissionWidget(permissionsState: MultiplePermissionsState) { var showRationale by remember(permissionsState) { mutableStateOf(false) } if (showRationale) { AlertDialog(onDismissRequest = { showRationale = false }, title = { Text(text = "") }, text = { Text(text = "") }, confirmButton = { TextButton(onClick = { permissionsState.launchMultiplePermissionRequest() }) { Text("Continue") } }, dismissButton = { TextButton(onClick = { showRationale = false }) { Text("Dismiss") } }) } Button(onClick = { if (permissionsState.shouldShowRationale) { showRationale = true } else { permissionsState.launchMultiplePermissionRequest() } }) { Text(text = "Grant Permission") } } @SuppressLint("InlinedApi") @RequiresApi(Build.VERSION_CODES.M) @RequiresPermission(anyOf = [Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH_SCAN]) @Composable private fun ListOfDevicesWidget(findDeviceController: FindDeviceController) { val isScanning by findDeviceController.isScanning.collectAsState() val coroutineScope = rememberCoroutineScope() Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Button(onClick = { if (isScanning) { findDeviceController.stopScan() } else { coroutineScope.launch { findDeviceController.startScan(TimeUnit.SECONDS.toMillis(30)) } } }) { Text( text = if (isScanning) { "Stop Scanning" } else { "Start Scanning" } ) } ListOfBLEDevices(findDeviceController) } } @RequiresApi(Build.VERSION_CODES.M) @Composable private fun ListOfBLEDevices(findDeviceController: FindDeviceController) { val devices by findDeviceController.listOfDevices.collectAsState() LazyColumn(Modifier.padding(16.dp)) { if (devices.isEmpty()) { item { Text(text = "No devices found") } } items(devices) { item -> BluetoothItem(bluetoothDevice = item) } } } @SuppressLint("MissingPermission") @Composable private fun BluetoothItem(bluetoothDevice: BluetoothDevice) { Text( bluetoothDevice.name, modifier = Modifier .padding(8.dp, 0.dp) ) }
2
Kotlin
16
201
dca2236d7abbea6f6f29e858ce8f083132c75d17
6,375
platform-samples
Apache License 2.0
app/src/main/java/com/example/gamebuddy/domain/model/Pending/PendingFriends.kt
GameBuddyDevs
609,491,782
false
null
package com.example.gamebuddy.domain.model.Pending data class PendingFriends( val userId: String, val username: String, val country: String, val avatar: String )
0
Kotlin
1
3
0a767229f5505e6a68e167aece41c10abb282e1b
178
GameBuddy-Android
MIT License
kamp-core/src/main/kotlin/ch/leadrian/samp/kamp/core/api/data/MutableVehicleParameters.kt
Double-O-Seven
142,487,686
false
null
package ch.leadrian.samp.kamp.core.api.data import ch.leadrian.samp.kamp.core.api.constants.VehicleAlarmState import ch.leadrian.samp.kamp.core.api.constants.VehicleBonnetState import ch.leadrian.samp.kamp.core.api.constants.VehicleBootState import ch.leadrian.samp.kamp.core.api.constants.VehicleDoorLockState import ch.leadrian.samp.kamp.core.api.constants.VehicleEngineState import ch.leadrian.samp.kamp.core.api.constants.VehicleLightsState import ch.leadrian.samp.kamp.core.api.constants.VehicleObjectiveState import ch.leadrian.samp.kamp.core.runtime.data.MutableVehicleParametersImpl interface MutableVehicleParameters : VehicleParameters { override var engine: VehicleEngineState override var lights: VehicleLightsState override var alarm: VehicleAlarmState override var doorLock: VehicleDoorLockState override var bonnet: VehicleBonnetState override var boot: VehicleBootState override var objective: VehicleObjectiveState } fun mutableVehicleParametersOf( engine: VehicleEngineState, lights: VehicleLightsState, alarm: VehicleAlarmState, doorLock: VehicleDoorLockState, bonnet: VehicleBonnetState, boot: VehicleBootState, objective: VehicleObjectiveState ): MutableVehicleParameters = MutableVehicleParametersImpl( engine = engine, lights = lights, alarm = alarm, doorLock = doorLock, bonnet = bonnet, boot = boot, objective = objective )
1
null
1
7
af07b6048210ed6990e8b430b3a091dc6f64c6d9
1,500
kamp
Apache License 2.0
bc-gateway/bc-gateway-ports/bc-gateway-wallet-proxy/src/main/kotlin/co/nilin/opex/bcgateway/ports/walletproxy/model/Amount.kt
opexdev
370,411,517
false
null
package co.nilin.opex.bcgateway.ports.walletproxy.model import java.math.BigDecimal data class Amount(val currency: Currency, val amount: BigDecimal)
29
null
22
51
fedf3be46ee7fb85ca7177ae91b13dbc6f2e8a73
151
core
MIT License
technocracy.foundation/src/main/kotlin/net/cydhra/technocracy/foundation/network/ClientComponentClickPacket.kt
elvissierra
386,150,571
true
{"Kotlin": 1515507, "Java": 34343, "GLSL": 18294}
package net.cydhra.technocracy.foundation.network import io.netty.buffer.ByteBuf import net.cydhra.technocracy.foundation.client.gui.container.TCContainer import net.cydhra.technocracy.foundation.util.player import net.cydhra.technocracy.foundation.util.syncToMainThread import net.minecraftforge.fml.common.network.simpleimpl.IMessage import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler import net.minecraftforge.fml.common.network.simpleimpl.MessageContext class ClientComponentClickPacket(var componentId: Int = -1, var clickType: Int = -1) : IMessage, IMessageHandler<ClientComponentClickPacket, IMessage> { override fun fromBytes(buf: ByteBuf?) { componentId = buf?.readInt()!! clickType = buf.readInt() } override fun toBytes(buf: ByteBuf?) { buf?.writeInt(componentId) buf?.writeInt(clickType) } override fun onMessage(message: ClientComponentClickPacket, ctx: MessageContext): IMessage? { return ctx.syncToMainThread { val container = player.openContainer if (container !is TCContainer) return@syncToMainThread null container.clickComponent(ctx.serverHandler.player, message.componentId, message.clickType) null } } }
0
null
0
0
93e1213a833321b6877f07767771fad65efe2037
1,286
Technocracy
MIT License
app/src/main/java/com/atownsend/fragmentfactorysample/di/AppComponent.kt
alex-townsend
156,447,502
false
null
package com.atownsend.fragmentfactorysample.di import com.atownsend.fragmentfactorysample.App import com.atownsend.fragmentfactorysample.AppModule import dagger.BindsInstance import dagger.Component import javax.inject.Singleton @Component(modules = [AppModule::class]) @Singleton interface AppComponent { fun inject(app: App) @Component.Builder interface Builder { fun build(): AppComponent @BindsInstance fun application(application: App): Builder } }
1
Kotlin
2
16
f03ae43e755062c3fde11c41b44369f62bc9c9a0
479
FragmentFactoryDaggerSample
MIT License
features/fragment_feature/src/main/kotlin/com/backmarket/pocnavigation/fragment_feature/FeatureFragment.kt
PhilippeBoisney
329,027,548
false
null
package com.backmarket.pocnavigation.fragment_feature import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import com.backmarket.pocnavigation.fragment_feature.model.FeatureFragmentViewModel import com.backmarket.pocnavigation.navigation.Navigable import com.backmarket.pocnavigation.navigation.direction.screen.FeatureFragmentDirection import com.backmarket.pocnavigation.navigation.ktx.requireNavParam import kotlinx.android.synthetic.main.fragment_feature.* import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class FeatureFragment : Fragment(R.layout.fragment_feature), Navigable { private val viewModel by viewModel<FeatureFragmentViewModel> { parametersOf(requireNavParam<FeatureFragmentDirection.Params>()) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) bindViewModel() bindViews() } private fun bindViewModel() = viewModel.run { observeNavigation() } private fun bindViews() { btnBack.setOnClickListener { viewModel.onUserClicksOnBack() } } companion object { fun newInstance() = FeatureFragment() } }
0
Kotlin
11
64
3f9d65d98fbb6889e69c03f6b310059e795f5914
1,288
android-multi-modules-navigation-demo
MIT License
app/back/back-trip-app/src/main/kotlin/org/app/back/trip/util/ui/Ui.kt
NikitaBurtelov
481,104,122
false
null
package org.app.back.trip.util.ui class Ui { }
0
Kotlin
0
0
604dea22bfd29cfc145a2d5f03fddd949ba4e60e
47
back-trip
Apache License 2.0
codegen/src/main/kotlin/com/hendraanggrian/ktfx/codegen/Names.kt
hendraanggrian
102,934,147
false
{"Kotlin": 1147480}
package com.hendraanggrian.ktfx.codegen import com.hendraanggrian.kotlinpoet.VARARG import com.hendraanggrian.kotlinpoet.classNameOf import com.hendraanggrian.kotlinpoet.genericsBy import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.MemberName import com.squareup.kotlinpoet.MemberName.Companion.member import com.squareup.kotlinpoet.ParameterSpec val KTFX_LAYOUTS = "ktfx.layouts" val KOTLIN_CONTRACTS = "kotlin.contracts" val OPT_IN = classNameOf("", "OptIn") val EXPERIMENTAL_CONTRACTS: ClassName = classNameOf(KOTLIN_CONTRACTS, "ExperimentalContracts") val CONTRACT = MemberName(KOTLIN_CONTRACTS, "contract") val EXACTLY_ONCE = classNameOf(KOTLIN_CONTRACTS, "InvocationKind").member("EXACTLY_ONCE") val DSL_MARKER = classNameOf(KTFX_LAYOUTS, "KtfxLayoutDslMarker") val T = "T".genericsBy() val S = "S".genericsBy() val X = "X".genericsBy() val Y = "Y".genericsBy() fun List<ParameterSpec>.toString(namedArgument: Boolean, commaSuffix: Boolean): String = buildString { append( joinToString { var s = buildString { append(it.name) if (namedArgument) append(" = ${it.name}") } if (VARARG in it.modifiers) { val index = s.lastIndexOf(it.name) s = s.substring(0, index) + '*' + s.substring(index) } s }, ) if (commaSuffix && isNotEmpty()) append(", ") }
1
Kotlin
2
16
d760e3d6682cc83795e8b74ce87b19f54aba0e10
1,527
ktfx
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsinterventionsservice/jpa/repository/ServiceProviderRepository.kt
uk-gov-mirror
356,783,155
true
{"Kotlin": 419090, "Python": 24480, "Mustache": 3868, "Dockerfile": 981, "Shell": 523}
package uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.repository import org.springframework.data.repository.CrudRepository import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.AuthGroupID import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.ServiceProvider interface ServiceProviderRepository : CrudRepository<ServiceProvider, AuthGroupID>
0
Kotlin
0
0
c6472e5b2eef33bbc1db83cd445f5aa51d474670
395
ministryofjustice.hmpps-interventions-service
MIT License
project-administration/src/main/kotlin/com/example/projectadministration/services/ProjectService.kt
honeyballs
227,557,896
false
null
package com.example.projectadministration.services import com.example.projectadministration.model.aggregates.Project import com.example.projectadministration.model.dto.ProjectCustomerDto import com.example.projectadministration.model.dto.ProjectDto import com.example.projectadministration.model.dto.ProjectEmployeeDto import com.example.projectadministration.repositories.customer.CustomerRepositoryGlobal import com.example.projectadministration.repositories.employee.EmployeeRepositoryImpl import com.example.projectadministration.repositories.project.ProjectRepositoryGlobal import org.springframework.stereotype.Service import java.util.* @Service class ProjectService( val projectRepositoryGlobal: ProjectRepositoryGlobal, val employeeRepository: EmployeeRepositoryImpl, val customerRepositoryGlobal: CustomerRepositoryGlobal, val employeeService: EmployeeService, val eventProducer: EventProducer ) : MappingService<Project, ProjectDto> { fun createProject(projectDto: ProjectDto): ProjectDto { val project = Project.create( projectDto.name, projectDto.description, projectDto.startDate, projectDto.projectedEndDate, projectDto.endDate, projectDto.projectEmployees.map { it.id }.toSet(), projectDto.customer.id ) eventProducer.produceAggregateEvent(project) return mapEntityToDto(project) } fun updateProject(projectDto: ProjectDto): ProjectDto { if (projectDto.id == null || projectDto.id == "") { throw RuntimeException("Id required to update") } return projectRepositoryGlobal.getById(projectDto.id).map { if (it.description != projectDto.description) { it.updateProjectDescription(projectDto.description) } if (it.projectedEndDate != projectDto.projectedEndDate) { it.delayProject(projectDto.projectedEndDate) } if (it.employees != projectDto.projectEmployees.map { it.id }.toSet()) { it.changeEmployeesWorkingOnProject(projectDto.projectEmployees.map { it.id }.toSet()) } eventProducer.produceAggregateEvent(it) mapEntityToDto(it) }.orElseThrow() } fun finishProject(projectDto: ProjectDto): ProjectDto { if (projectDto.id == null || projectDto.id == "") { throw RuntimeException("Id required to update") } return projectRepositoryGlobal.getById(projectDto.id).map { if (projectDto.endDate != null) { it.finishProject(projectDto.endDate) } eventProducer.produceAggregateEvent(it) mapEntityToDto(it) }.orElseThrow() } fun deleteProject(id: String) { projectRepositoryGlobal.getById(id).map { it.delete() eventProducer.produceAggregateEvent(it) }.orElseThrow() } override fun mapEntityToDto(entity: Project): ProjectDto { val employees = employeeRepository.getAllByIdIn(entity.employees.toList()).toSet() val customer = customerRepositoryGlobal.getByIdAndDeletedFalse(entity.customer).orElseThrow() return ProjectDto( entity.id, entity.name, entity.description, entity.startDate, entity.projectedEndDate, entity.endDate, employees.map { ProjectEmployeeDto(it.id, it.firstname, it.lastname, it.mail) }.toSet(), ProjectCustomerDto(customer.id, customer.customerName) ) } override fun mapDtoToEntity(dto: ProjectDto): Project { return Project( dto.name, dto.description, dto.startDate, dto.projectedEndDate, dto.endDate, dto.projectEmployees.map { it.id }.toSet(), dto.customer.id, dto.id ?: UUID.randomUUID().toString() ) } }
0
Kotlin
0
0
96fb9e43eeb8c190e0737216b442e70623d17ab9
4,114
microservice-event-sourcing
MIT License
jipp-pdl/src/main/kotlin/com/hp/jipp/pdl/ColorSpace.kt
HPInc
129,298,798
false
null
// Copyright 2018 HP Development Company, L.P. // SPDX-License-Identifier: MIT package com.hp.jipp.pdl import java.io.InputStream import java.io.OutputStream import kotlin.math.roundToInt /** Identifies a color space which describes how each pixel of image data is encoded. */ @Suppress("MagicNumber") enum class ColorSpace(val bytesPerPixel: Int) { /** Four bytes per pixel: Red, Green, Blue, Alpha. */ Rgba(4), /** Three bytes per pixel: Red, Green, Blue. */ Rgb(3), /** One byte per pixel, between 0x00=Black and 0xFF=White. */ Grayscale(1); /** Return a converter lambda that will copy bytes from this color space to another. */ fun converter(outputColor: ColorSpace): (ByteArray, Int, OutputStream) -> Unit = when (this) { Grayscale -> grayscaleConverter(outputColor) Rgb -> rgbConverter(outputColor) Rgba -> rgbaConverter(outputColor) } /** Return a function that converts a [Grayscale] input array to an [outputColor] output stream. */ private fun grayscaleConverter(outputColor: ColorSpace): (ByteArray, Int, OutputStream) -> Unit = when (outputColor) { Grayscale -> passThrough Rgb -> { input, inputOffset, output -> val byte = input[inputOffset].toInt() output.write(byte) output.write(byte) output.write(byte) } Rgba -> { input, inputOffset, output -> val byte = input[inputOffset].toInt() output.write(byte) output.write(byte) output.write(byte) output.write(MAX_BYTE) } } /** Return a function that converts an [Rgb] input array to an [outputColor] output stream. */ private fun rgbConverter(outputColor: ColorSpace): (ByteArray, Int, OutputStream) -> Unit = when (outputColor) { Grayscale -> { input, inputOffset, output -> output.write(input.rgbLuminosityAt(inputOffset).roundToInt()) } Rgb -> passThrough Rgba -> { input, inputOffset, output -> output.write(input[inputOffset].toInt()) output.write(input[inputOffset + 1].toInt()) output.write(input[inputOffset + 2].toInt()) output.write(MAX_BYTE) } } /** Return a function that converts an [Rgba] input array to an [outputColor] output stream. */ private fun rgbaConverter(outputColor: ColorSpace): (ByteArray, Int, OutputStream) -> Unit = when (outputColor) { Grayscale -> { input, inputOffset, output -> output.write( input.rgbLuminosityAt(inputOffset) .applyAlpha(input[inputOffset + 3].uByteInt) ) } Rgb -> { input, inputOffset, output -> when (val alpha = input[inputOffset + 3].uByteInt) { 0x00 -> { output.write(MAX_BYTE) output.write(MAX_BYTE) output.write(MAX_BYTE) } 0xFF -> output.write(input, inputOffset, 3) else -> { output.write(input[inputOffset].uByteInt.toDouble().applyAlpha(alpha)) output.write(input[inputOffset + 1].uByteInt.toDouble().applyAlpha(alpha)) output.write(input[inputOffset + 2].uByteInt.toDouble().applyAlpha(alpha)) } } } Rgba -> passThrough } /** A converter function that passes data through unmodified. */ private val passThrough = { input: ByteArray, inputOffset: Int, output: OutputStream -> output.write(input, inputOffset, bytesPerPixel) } /** * Find the correct point between this intensity value (0x00-0xFF) and white based on alpha level (0x00-0xFF) * where alpha 0x00 is white and alpha 0xFF is the original intensity. */ private fun Double.applyAlpha(alpha: Int): Int = (this * alpha / MAX_BYTE - alpha + MAX_BYTE).roundToInt() /** Return this unsigned byte as an integer. */ private val Byte.uByteInt get() = toInt().and(MAX_BYTE) /** Measure the luminosity at the specified index. */ private fun ByteArray.rgbLuminosityAt(index: Int) = LUM_R * get(index).uByteInt + LUM_G * get(index + 1).uByteInt + LUM_B * get(index + 2).uByteInt /** Write [input] pixels encoded in this [ColorSpace] to [output] in [outputColor]. */ fun convert(input: InputStream, output: OutputStream, outputColor: ColorSpace) { val inputPixel = ByteArray(bytesPerPixel) val converter = converter(outputColor) while (input.read(inputPixel) != -1) { converter(inputPixel, 0, output) } } companion object { private const val MAX_BYTE = 0xFF /** Red pixel luminosity. */ private const val LUM_R = 0.2126 /** Green pixel luminosity. */ private const val LUM_G = 0.7152 /** Blue pixel luminosity. */ private const val LUM_B = 0.0722 } }
7
null
40
99
f1f96d5da88d24197e7b0f90eec4ceee0fe66550
5,270
jipp
MIT License
dachlatten-compose/src/main/kotlin/de/sipgate/dachlatten/compose/lifecycle/LifecycleObserver.kt
sipgate
695,233,490
false
{"Kotlin": 106054}
package de.sipgate.dachlatten.compose.lifecycle import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.LifecycleObserver @Composable fun LifecycleObserver(lifecycleObserver: LifecycleObserver) { val lifecycle = LocalLifecycleOwner.current DisposableEffect(lifecycle) { lifecycle.lifecycle.addObserver(lifecycleObserver) onDispose { lifecycle.lifecycle.removeObserver(lifecycleObserver) } } }
5
Kotlin
0
1
859b423c9250b318eb2ed8364afa4d154711f6c6
541
dachlatten
Apache License 2.0
src/main/kotlin/jp/nephy/penicillin/core/auth/OAuthUtil.kt
colt005
186,767,944
true
{"Kotlin": 1199305}
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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 jp.nephy.penicillin.core.auth import io.ktor.http.* import io.ktor.util.date.GMTDate import io.ktor.util.flattenForEach import jp.nephy.penicillin.core.request.body.EncodedFormContent import jp.nephy.penicillin.core.request.body.MultiPartContent import jp.nephy.penicillin.core.request.copy import java.util.* import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec /** * OAuth cryptography utilities. */ object OAuthUtil { private const val macAlgorithm = "HmacSHA1" /** * Generates random uuid string with upper case. */ val randomUUID: String get() = UUID.randomUUID().toString().toUpperCase() /** * Current epoch time string in seconds. */ @Suppress("MemberVisibilityCanBePrivate") val currentEpochTime: String get() = "${GMTDate().timestamp / 1000}" /** * Creates initial authorization header components. */ fun initialAuthorizationHeaderComponents(callback: String? = null, nonce: String = randomUUID, timestamp: String = currentEpochTime, consumerKey: String? = null, accessToken: String? = null): MutableMap<String, String?> { requireNotNull(consumerKey) return linkedMapOf( "oauth_signature" to null, "oauth_callback" to callback, "oauth_nonce" to nonce, "oauth_timestamp" to timestamp, "oauth_consumer_key" to consumerKey, "oauth_token" to accessToken, "oauth_version" to "1.0", "oauth_signature_method" to "HMAC-SHA1" ) } /** * Creates signature param. */ fun signatureParam(authorizationHeaderComponent: Map<String, String?>, body: Any, parameters: ParametersBuilder): Map<String, String> { return sortedMapOf<String, String>().also { map -> authorizationHeaderComponent.filterValues { it != null }.forEach { map[it.key.encodeURLParameter()] = it.value?.encodeURLParameter() } if (body !is MultiPartContent) { val forms = (body as? EncodedFormContent)?.forms ?: parametersOf() val params = parameters.copy().build() + forms params.flattenForEach { key, value -> map[key.encodeURLParameter()] = value.encodeURLParameter() } } } } /** * Creates signature param string. */ fun signatureParamString(param: Map<String, String>): String { return param.toList().joinToString("&") { "${it.first}=${it.second}" }.encodeOAuth() } /** * Creates signing base string. */ fun signingBaseString(httpMethod: HttpMethod, url: Url, signatureParamString: String): String { return "${httpMethod.value.toUpperCase()}&${url.toString().split("?").first().encodeOAuth()}&$signatureParamString" } /** * Creates signing key. */ fun signingKey(consumerSecret: String, accessTokenSecret: String? = null): SecretKeySpec { return SecretKeySpec("${consumerSecret.encodeOAuth()}&${accessTokenSecret?.encodeOAuth().orEmpty()}".toByteArray(), macAlgorithm) } /** * Creates signature. */ fun signature(signingKey: SecretKeySpec, signatureBaseString: String): String { return Mac.getInstance(macAlgorithm).apply { init(signingKey) }.doFinal(signatureBaseString.toByteArray()).let { it.encodeBase64() }.encodeOAuth() } }
0
Kotlin
0
0
d5860e3d9c7c95c7d7ec1879c080b114ca77e127
4,671
Penicillin
MIT License
docs/src/test/kotlin/example/test/HookContextTest.kt
intuit
342,405,057
false
null
// This file was automatically generated from key-concepts.md by Knit tool. Do not edit. package com.intuit.hooks.example import org.junit.jupiter.api.Test import kotlinx.knit.test.* class HookContextTest { @Test fun testExampleContext01() { captureOutput("ExampleContext01") { com.intuit.hooks.example.exampleContext01.main() }.verifyOutputLines( "NoisePlugin is doing it's job", "Silence..." ) } }
6
Kotlin
6
30
4e3e909bb2106d34bc82c51ddd76631a0aeffc6c
454
hooks
MIT License
app/src/main/java/me/mahfuzmunna/musicplayer/views/ItemAdapter.kt
mahfuzmunna
693,216,908
false
{"Kotlin": 9915}
package me.mahfuzmunna.musicplayer.views import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import me.mahfuzmunna.musicplayer.models.Track class ItemAdapter(val itemList: ArrayList<String>) : RecyclerView.Adapter<ItemAdapter.ViewHolder>() { class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val text: TextView = itemView.findViewById(android.R.id.text1) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(android.R.layout.simple_list_item_1, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return itemList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = itemList[position] holder.text.text = item } }
0
Kotlin
0
0
a0fb62b7a9b944ca7ef52bb15caed38cd630eadf
992
android-musicplayer
MIT License
app/src/main/java/com/volvocars/mediasample/common/CommonDependencyModule.kt
volvo-cars
467,895,828
false
{"Kotlin": 34192}
/* * Copyright 2022 Volvo Car Corporation * * 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.volvocars.mediasample.common import com.volvocars.mediasample.common.util.ResourceUriUtil import org.koin.android.ext.koin.androidApplication import org.koin.dsl.module object CommonDependencyModule { fun dependencies() = module { single { ResourceUriUtil(context = androidApplication()) } } }
1
Kotlin
14
21
13bb3f066c9b7882005541be53cd6e08f2bda499
930
automotive-media-sample
Apache License 2.0
app/src/main/java/com/linkedintools/service/ServiceUtil.kt
JohannBlake
190,872,147
false
null
package com.linkedintools.service import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.IBinder import com.linkedintools.App import javax.inject.Inject /** * Utility class that provides access to the mService. */ class ServiceUtil @Inject constructor() { var mService: LinkedInService? = null private var mBound: Boolean = false var service: LinkedInService? get() = mService private set(value) {} /** Defines callbacks for service binding, passed to bindService() */ private val mConnection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, mService: IBinder) { if (mBound) { val binder = mService as LinkedInService.LocalBinder [email protected] = binder.getService() App.context.bus.onServiceStarted().onNext(Unit) } } /** * Useless callback. It only gets called if the service crashes or is killed off by the OS. */ override fun onServiceDisconnected(arg0: ComponentName) { mBound = false } } /** * Starts the service. */ fun startService() { Intent(App.context, LinkedInService::class.java).also { intent -> //App.context.unbindService(mConnection) App.context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE) } } var serviceIsRunning: Boolean get() = mBound set(value) { mBound = value if (!mBound) { try { App.context.unbindService(mConnection) } catch (ex: Exception) { } } } }
0
Kotlin
0
0
66d7dc4b9266af3f26b941a045b2cfa0b561ddcf
1,836
AndroidSampleAppLinkedIn
The Unlicense
examples/realworld/src/jvmMain/kotlin/io/realworld/Main.kt
rjaros
706,876,956
false
{"Kotlin": 2351917, "CSS": 9269, "JavaScript": 5178, "HTML": 217}
package io.realworld import dev.kilua.ssr.initSsr import io.ktor.http.* import io.ktor.http.content.* import io.ktor.server.application.* import io.ktor.server.plugins.cachingheaders.* import io.ktor.server.plugins.compression.* fun Application.main() { install(Compression) install(CachingHeaders) { options { call, content -> when (content.contentType?.withoutParameters()) { ContentType.Application.Wasm -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 3600)) ContentType.Application.JavaScript -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 3600)) ContentType.Text.Html -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 3600)) else -> null } } } initSsr() }
0
Kotlin
2
97
524a35c898fe84fa1773b53bf97e701cdc00155b
800
kilua
MIT License
src/main/kotlin/com/hotels/intellij/plugins/network/NetworkToolWindowPanel.kt
ExpediaGroup
97,828,016
false
{"Kotlin": 52256}
/* * Copyright 2017 Expedia 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.hotels.intellij.plugins.network import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBTabbedPane import com.intellij.ui.table.JBTable import java.awt.Component import java.awt.GridLayout import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JSplitPane import javax.swing.JTextArea import javax.swing.SwingConstants import javax.swing.event.ListSelectionEvent import javax.swing.table.DefaultTableCellRenderer /** * The Network tool window panel. Extension of [SimpleToolWindowPanel]. */ class NetworkToolWindowPanel( vertical: Boolean, borderless: Boolean ) : SimpleToolWindowPanel(vertical, borderless) { private val tableModel = NetworkTableModel() private var requestHeaderTextArea: JTextArea? = null private var requestContentTextArea: JTextArea? = null private var responseHeaderTextArea: JTextArea? = null private var responseContentTextArea: JTextArea? = null private var curlTextArea: JTextArea? = null private fun createToolBar() { val defaultActionGroup = DefaultActionGroup() defaultActionGroup.add(StartProxyServerAction(tableModel)) defaultActionGroup.add(StopProxyServerAction()) defaultActionGroup.add(ClearAllViewAction(tableModel)) defaultActionGroup.addSeparator() defaultActionGroup.add(PreferencesAction()) val toolBarPanel = JPanel(GridLayout()) toolBarPanel.add(ActionManager.getInstance().createActionToolbar(NETWORK_TOOLBAR, defaultActionGroup, false).component) toolbar = toolBarPanel } private fun createContent() { val splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, createTableComponent(), createTabbedComponent()) splitPane.dividerSize = 2 setContent(splitPane) } private fun createTableComponent(): Component { val rightAlignedTableCellRenderer = DefaultTableCellRenderer() rightAlignedTableCellRenderer.horizontalAlignment = JLabel.CENTER val table = JBTable(tableModel) table.columnModel.getColumn(1).cellRenderer = rightAlignedTableCellRenderer table.columnModel.getColumn(2).cellRenderer = rightAlignedTableCellRenderer table.columnModel.getColumn(3).cellRenderer = rightAlignedTableCellRenderer table.columnModel.getColumn(4).cellRenderer = rightAlignedTableCellRenderer table.selectionModel.addListSelectionListener { _: ListSelectionEvent? -> if (table.selectedRow >= 0) { ApplicationManager.getApplication().invokeLater { val requestResponse = tableModel.getRow(table.selectedRow) requestHeaderTextArea!!.text = requestResponse.requestHeaders requestHeaderTextArea!!.caretPosition = 0 requestContentTextArea!!.text = requestResponse.requestContent requestContentTextArea!!.caretPosition = 0 responseHeaderTextArea!!.text = requestResponse.responseHeaders responseHeaderTextArea!!.caretPosition = 0 responseContentTextArea!!.text = requestResponse.responseContent responseContentTextArea!!.caretPosition = 0 curlTextArea!!.text = requestResponse.curlRequest curlTextArea!!.caretPosition = 0 } } else { ApplicationManager.getApplication().invokeLater { requestHeaderTextArea!!.text = "" requestContentTextArea!!.text = "" responseHeaderTextArea!!.text = "" responseContentTextArea!!.text = "" curlTextArea!!.text = "" } } } return JBScrollPane(table) } private fun createTabbedComponent(): Component { val tabbedPane = JBTabbedPane(SwingConstants.TOP) tabbedPane.insertTab("Request Headers", null, createRequestHeaderComponent(), "", 0) tabbedPane.insertTab("Request Content", null, createRequestContentComponent(), "", 1) tabbedPane.insertTab("Response Headers", null, createResponseHeaderComponent(), "", 2) tabbedPane.insertTab("Response Content", null, createResponseContentComponent(), "", 3) tabbedPane.insertTab("Curl Request", null, createCurlRequestComponent(), "", 4) return tabbedPane } private fun createRequestHeaderComponent(): Component { requestHeaderTextArea = JTextArea() requestHeaderTextArea!!.isEditable = false return JBScrollPane(requestHeaderTextArea) } private fun createRequestContentComponent(): Component { requestContentTextArea = JTextArea() requestContentTextArea!!.isEditable = false return JBScrollPane(requestContentTextArea) } private fun createResponseHeaderComponent(): Component { responseHeaderTextArea = JTextArea() responseHeaderTextArea!!.isEditable = false return JBScrollPane(responseHeaderTextArea) } private fun createResponseContentComponent(): Component { responseContentTextArea = JTextArea() responseContentTextArea!!.isEditable = false return JBScrollPane(responseContentTextArea) } private fun createCurlRequestComponent(): Component { curlTextArea = JTextArea() curlTextArea!!.isEditable = false return JBScrollPane(curlTextArea) } companion object { const val NETWORK_TOOLBAR = "NetworkToolbar" } /** * Constructor. Used to build the necessary components. * * @param vertical * @param borderless */ init { createToolBar() createContent() } }
5
Kotlin
4
3
7e0f0d8860c905077b4a4c01240e74dfd52bd082
6,585
network-plugin
Apache License 2.0
src/test/kotlin/infrastructure/database/SurgeryReportDatabaseTest.kt
SmartOperatingBlock
638,493,553
false
null
/* * Copyright (c) 2023. Smart Operating Block * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package infrastructure.database import data.SurgicalProcessData.listOfTimedPatientVitalSigns import data.SurgicalProcessData.listOfTimedRoomEnvironmentalData import data.SurgicalProcessData.listOfhealthProfessionalTrackingData import data.SurgicalProcessData.sampleConsumedImplantableMedicalDevices import data.SurgicalProcessData.sampleMedicalTechnologyUsage import data.SurgicalProcessData.simpleSurgicalProcess import entity.healthcareuser.HealthcareUser import entity.healthcareuser.TaxCode import entity.room.RoomType import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.equality.shouldBeEqualToComparingFields import io.kotest.matchers.shouldBe import usecase.ReportGenerationUseCase class SurgeryReportDatabaseTest : StringSpec({ val surgeryReport = ReportGenerationUseCase( simpleSurgicalProcess, listOfTimedPatientVitalSigns, listOfhealthProfessionalTrackingData, mapOf( RoomType.PRE_OPERATING_ROOM to listOfTimedRoomEnvironmentalData, RoomType.OPERATING_ROOM to listOfTimedRoomEnvironmentalData, ), HealthcareUser(TaxCode("taxcode"), "Mario", "Rossi"), sampleConsumedImplantableMedicalDevices, sampleMedicalTechnologyUsage, ).execute() fun getDatabase() = SurgeryReportDatabase("mongodb://localhost:27017") "it should be able to store a surgery report" { withMongo { val database = getDatabase() database.createSurgeryReport(surgeryReport) shouldBe true database.findBy(surgeryReport.surgicalProcessID)?.shouldBeEqualToComparingFields(surgeryReport) } } "it should be able to integrate a surgery report" { val newAdditionalData = "new additional data" withMongo { val database = getDatabase() database.createSurgeryReport(surgeryReport) database.integrateSurgeryReport( surgeryReport.surgicalProcessID, newAdditionalData, ) shouldBe true database.findBy(surgeryReport.surgicalProcessID)?.additionalData shouldBe newAdditionalData } } "it should handle the integration of a non-existing surgery report" { val newAdditionalData = "new additional data" withMongo { val database = getDatabase() database.integrateSurgeryReport( surgeryReport.surgicalProcessID, newAdditionalData, ) shouldBe false } } "it should be possible to retrieve an existing surgery report" { withMongo { val database = getDatabase() database.createSurgeryReport(surgeryReport) database.findBy(surgeryReport.surgicalProcessID)?.shouldBeEqualToComparingFields(surgeryReport) } } "it should handle the request of retrieving a non-existent surgery report" { withMongo { val database = getDatabase() database.findBy(surgeryReport.surgicalProcessID) shouldBe null } } "it should be possible to retrieve the list of the surgery reports available" { withMongo { val database = getDatabase() database.createSurgeryReport(surgeryReport) database.getSurgeryReports().size shouldBe 1 database.getSurgeryReports().contains(surgeryReport) shouldBe true } } "it should be possible to retrieve the list of the surgery reports available even if empty" { withMongo { val database = getDatabase() database.getSurgeryReports().size shouldBe 0 } } })
1
Kotlin
0
1
b93bf4fec6b2b99ae9a6452796c8140f34f2ea2c
3,855
surgery-report-microservice
MIT License
src/jsMain/kotlin/sh/christian/website/composable/MyResume.kt
christiandeange
15,754,740
false
null
package sh.christian.website.composable import androidx.compose.runtime.Composable import org.jetbrains.compose.web.attributes.ATarget.Blank import org.jetbrains.compose.web.attributes.href import org.jetbrains.compose.web.attributes.target import org.jetbrains.compose.web.css.Style import org.jetbrains.compose.web.dom.A import org.jetbrains.compose.web.dom.AttrBuilderContext import org.jetbrains.compose.web.dom.Br import org.jetbrains.compose.web.dom.Div import org.jetbrains.compose.web.dom.Text import org.w3c.dom.HTMLElement import sh.christian.website.icon.EmailIcon import sh.christian.website.icon.GitHubIcon import sh.christian.website.sheet.MyResume import sh.christian.website.sheet.MyResume.flex1 import sh.christian.website.sheet.MyResume.flex2 import sh.christian.website.sheet.MyResume.infocolumn import sh.christian.website.sheet.MyResume.inforow import sh.christian.website.sheet.MyResume.links import sh.christian.website.sheet.MyResume.name import sh.christian.website.sheet.MyResume.phoneCentered import sh.christian.website.sheet.MyResume.resumeHeader import kotlin.text.Typography.nbsp @Composable fun MyResume( attrs: AttrBuilderContext<HTMLElement>? = null, ) { Style(MyResume) Div(attrs) { Div(attrs = { classes(resumeHeader) }) { Name() Links() } Div(attrs = { classes(inforow) }) { Div(attrs = { classes(infocolumn, flex1) }) { Sidebar() } Div(attrs = { classes(infocolumn, flex2) }) { WorkHistory() } } } } @Composable private fun Name() { Div(attrs = { classes(name) }) { Text("<NAME>${nbsp}angelis") } } @Composable private fun Links() { Div(attrs = { classes(links) }) { Link { GitHubIcon() A( href = "https://github.com/christiandeange", attrs = { target(Blank) }, ) { Text("christiandeange") } } Link { EmailIcon() A( href = "mailto:<EMAIL>", attrs = { target(Blank) }, ) { Text("<EMAIL>") } } } } @Composable private fun Sidebar() { Section("Skills") { Div(attrs = { classes(phoneCentered) }) { Skill("Kotlin", 5) Skill("Java", 5) Skill("Gradle", 5) Skill("Bash", 4) Skill("Python", 3) } Br() } Section("Education") { Job("University of Waterloo", "2016") { Point("Bachelor of Software Engineering") Point("Graduated with Distinction") } } Section("Patents") { Job( { A( href = "https://patents.google.com/patent/US11216795B2", attrs = { target(Blank) }, ) { Text("US11216795 B2") } }, "2019" ) { Point( "Pairing merchant Point${nbsp}of${nbsp}Sale with payment${nbsp}reader${nbsp}terminal " + "via server Application${nbsp}Programming${nbsp}Interface." ) } } } @Composable private fun WorkHistory() { Section("Work") { Job("Software Engineer | Stripe", "2022 – present") { Point("Enhancing the Terminal integration experience, building the product that developers use to create in-person payment flows. Maintaining the Terminal SDK for Android, the Terminal docs, and building internal- and external-facing tools to help developers build better integrations.") } Job("Senior Android Engineer | Square", "2020 – 2022") { Point { Text("Started development of ") A( href = "https://developer.squareup.com/docs/terminal-api/overview", attrs = { target(Blank) }, ) { Text("Terminal API") } Text(" to enable merchants with their own existing point of sale system to take payments with Square Terminal. Assisted in maintaining our Gradle Enterprise instance, as well as creating internal build tools for developer efficiency and dependency management.") } } Job("Android Engineer | Square", "2017 – 2020") { Point { Text("Developing new features addressing the needs of small businesses and individual sellers using ") A( href = "https://squareup.com/payments", attrs = { target(Blank) }, ) { Text("Square Point of Sale") } Text(". Designed a native onboarding experience for Canadian sellers.") } } Job("Android Developer | CareZone", "2016 – 2017") { Point("Developed an internal app for inventory management that performs barcode scanning and recording a user's signature. Took full responsibility for development, testing, and internal distribution.") } Job("Android Developer Intern | CareZone", "2015") { Point("Integrated features using the Google Places Android API, and developed a new feature enabling users to track their vitals and visualize their recorded history.") } Job("Software Engineering Intern | Google", "2014") { Point("Worked with multiple teams on designing and creating new Google Play Services APIs. Redesigned the Play Services permissions flow to conform to Material Design.") } Job("Android Developer Intern | CareZone", "2013") { Point("Worked with a small team of developers and designers to build an app from the ground up that allows users to manage health information for their loved ones.") } } }
0
Kotlin
0
0
7b0f5564c052e182a09576fc27063f7a8bc4bea2
5,318
Website
The Unlicense
kotlin-native/Interop/Runtime/src/native/kotlin/kotlinx/cinterop/NativeUtils.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package kotlinx.cinterop import kotlin.native.internal.GCUnsafeCall import kotlin.native.internal.Intrinsic import kotlin.native.internal.TypedIntrinsic import kotlin.native.internal.IntrinsicType internal fun encodeToUtf8(str: String): ByteArray = str.encodeToByteArray() @GCUnsafeCall("Kotlin_CString_toKStringFromUtf8Impl") @ExperimentalForeignApi internal external fun CPointer<ByteVar>.toKStringFromUtf8Impl(): String @ExperimentalForeignApi @TypedIntrinsic(IntrinsicType.INTEROP_BITS_TO_FLOAT) public external fun bitsToFloat(bits: Int): Float @ExperimentalForeignApi @TypedIntrinsic(IntrinsicType.INTEROP_BITS_TO_DOUBLE) public external fun bitsToDouble(bits: Long): Double @Deprecated("Deprecated without replacement as part of the obsolete interop API", level = DeprecationLevel.WARNING) @TypedIntrinsic(IntrinsicType.INTEROP_SIGN_EXTEND) public external inline fun <reified R : Number> Number.signExtend(): R @Deprecated("Deprecated without replacement as part of the obsolete interop API", level = DeprecationLevel.WARNING) @TypedIntrinsic(IntrinsicType.INTEROP_NARROW) public external inline fun <reified R : Number> Number.narrow(): R @ExperimentalForeignApi @TypedIntrinsic(IntrinsicType.INTEROP_CONVERT) public external inline fun <reified R : Any> Byte.convert(): R @ExperimentalForeignApi @TypedIntrinsic(IntrinsicType.INTEROP_CONVERT) public external inline fun <reified R : Any> Short.convert(): R @ExperimentalForeignApi @TypedIntrinsic(IntrinsicType.INTEROP_CONVERT) public external inline fun <reified R : Any> Int.convert(): R @ExperimentalForeignApi @TypedIntrinsic(IntrinsicType.INTEROP_CONVERT) public external inline fun <reified R : Any> Long.convert(): R @ExperimentalForeignApi @TypedIntrinsic(IntrinsicType.INTEROP_CONVERT) public external inline fun <reified R : Any> UByte.convert(): R @ExperimentalForeignApi @TypedIntrinsic(IntrinsicType.INTEROP_CONVERT) public external inline fun <reified R : Any> UShort.convert(): R @ExperimentalForeignApi @TypedIntrinsic(IntrinsicType.INTEROP_CONVERT) public external inline fun <reified R : Any> UInt.convert(): R @ExperimentalForeignApi @TypedIntrinsic(IntrinsicType.INTEROP_CONVERT) public external inline fun <reified R : Any> ULong.convert(): R @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.FILE) @Retention(AnnotationRetention.SOURCE) internal annotation class JvmName(val name: String) @ExperimentalForeignApi public fun cValuesOf(vararg elements: UByte): CValues<UByteVar> = createValues(elements.size) { index -> this.value = elements[index] } @ExperimentalForeignApi public fun cValuesOf(vararg elements: UShort): CValues<UShortVar> = createValues(elements.size) { index -> this.value = elements[index] } @ExperimentalForeignApi public fun cValuesOf(vararg elements: UInt): CValues<UIntVar> = createValues(elements.size) { index -> this.value = elements[index] } @ExperimentalForeignApi public fun cValuesOf(vararg elements: ULong): CValues<ULongVar> = createValues(elements.size) { index -> this.value = elements[index] } @ExperimentalForeignApi public fun UByteArray.toCValues(): CValues<UByteVar> = cValuesOf(*this) @ExperimentalForeignApi public fun UShortArray.toCValues(): CValues<UShortVar> = cValuesOf(*this) @ExperimentalForeignApi public fun UIntArray.toCValues(): CValues<UIntVar> = cValuesOf(*this) @ExperimentalForeignApi public fun ULongArray.toCValues(): CValues<ULongVar> = cValuesOf(*this)
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
3,721
kotlin
Apache License 2.0
measurer/src/commonMain/kotlin/com/github/soushin/measurer/parameter/general/TrackingId.kt
soushin
171,784,688
false
null
package com.github.soushin.measurer.parameter.general import com.github.soushin.measurer.parameter.Parameter import com.github.soushin.measurer.parameter.Type object TrackingId : Parameter { override val name = "tid" override val type = Type.String override val maxLength: Int? = null }
0
Kotlin
0
8
203da2e72e8ee11d32673b59801e4c3db6e5f3c3
301
measurer
Apache License 2.0
core/src/main/java/com/xmartlabs/bigbang/core/module/GsonExclusionStrategy.kt
xmartlabs
50,346,596
false
{"Kotlin": 232568, "Shell": 834}
package com.xmartlabs.bigbang.core.module import com.google.gson.ExclusionStrategy import com.google.gson.FieldAttributes import com.xmartlabs.bigbang.core.common.GsonExclude import com.xmartlabs.bigbang.core.common.GsonExcludeStrategy /** Provides a [ExclusionStrategy] that excludes [GsonExclude] fields and any other specified class. */ open class GsonExclusionStrategy(val excludedClasses: List<Class<Any>>? = null) { /** * Retrieves an [ExclusionStrategy] that excludes [GsonExclude] fields and the classes contained in * `excludedClasses`. * @param strategy the type of the strategy to be retrieved * * * @return the [ExclusionStrategy] for the `strategy` provided */ open fun getExclusionStrategy(strategy: GsonExcludeStrategy?) = object : ExclusionStrategy { override fun shouldSkipField(fieldAttributes: FieldAttributes) = shouldSkipFieldFromSerialization(fieldAttributes) || fieldAttributes.getAnnotation(GsonExclude::class.java) != null && (fieldAttributes.getAnnotation(GsonExclude::class.java).strategy == GsonExcludeStrategy.ALL || fieldAttributes.getAnnotation(GsonExclude::class.java).strategy == strategy) override fun shouldSkipClass(clazz: Class<*>) = false } /** * Returns whether or not the field with `fieldAttributes` should be serialized. * * @param fieldAttributes the attributes of the field to analise * * * @return whether or not the field should be serialized */ protected open fun shouldSkipFieldFromSerialization(fieldAttributes: FieldAttributes) = excludedClasses?.contains(fieldAttributes.declaredClass) ?: false }
1
Kotlin
11
51
74827bec72f607d909fcc923f53cf19d0152e732
1,659
bigbang
Apache License 2.0
app/src/main/java/com/example/githubapisample/data/db/RepoDao.kt
antonkovalyov351
220,315,195
false
null
package com.example.githubapisample.data.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.example.githubapisample.data.db.entity.RepoEntity import com.example.githubapisample.data.db.entity.RepoSearchResultEntity import io.reactivex.Single @Dao interface RepoDao { @Query("SELECT * FROM RepoSearchResultEntity WHERE `query` = :query") fun search(query: String): Single<RepoSearchResultEntity> @Query("SELECT * FROM RepoEntity WHERE id in (:repoIds)") fun loadById(repoIds: List<Int>): Single<List<RepoEntity>> @Query("SELECT * FROM RepoEntity WHERE id is (:repoId)") fun loadById(repoId: Int): Single<RepoEntity> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(repo: RepoEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertRepos(repositories: List<RepoEntity>) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(result: RepoSearchResultEntity) }
1
Kotlin
0
0
c12f26f23bcd75ac1b19fedc2abbe53afea782e7
1,023
GithubApiSample
Apache License 2.0
app/src/main/java/ru/edgecenter/edge_vod/screens/splash/SplashActivity.kt
Edge-Center
613,300,417
false
null
package ru.edgecenter.edge_vod.screens.splash import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import edge_vod.R class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) } }
0
Kotlin
0
0
d70a5c36250e47c9826b7ddc3e08cc59e2cec469
340
android_vod_demo
MIT License
src/main/kotlin/no/nav/syfo/oppfolgingsplan/repository/domain/POppfoelgingsdialog.kt
navikt
656,574,894
false
{"Kotlin": 147900, "Dockerfile": 257}
package no.nav.syfo.oppfolgingsplan.repository.domain import no.nav.syfo.oppfolgingsplan.domain.OppfolgingsplanDTO import no.nav.syfo.oppfolgingsplan.domain.PersonDTO import no.nav.syfo.oppfolgingsplan.domain.VirksomhetDTO import java.time.LocalDateTime data class POppfoelgingsdialog( var id: Long, var uuid: String, var opprettetAv: String?, var aktoerId: String, var created: LocalDateTime?, var samtykkeArbeidsgiver: Boolean?, var virksomhetsnummer: String?, var sistEndretAv: String?, var samtykkeSykmeldt: Boolean?, var sisteInnloggingArbeidsgiver: LocalDateTime?, var sisteInnloggingSykmeldt: LocalDateTime?, var sistAksessertArbeidsgiver: LocalDateTime?, var sistAksessertSykmeldt: LocalDateTime?, var sistEndretArbeidsgiver: LocalDateTime?, var sistEndretSykmeldt: LocalDateTime?, var sistEndret: LocalDateTime?, var smFnr: String?, var opprettetAvFnr: String?, var sistEndretAvFnr: String? ) fun POppfoelgingsdialog.toOppfolgingsplanDTO(): OppfolgingsplanDTO { return OppfolgingsplanDTO( id = this.id, uuid = this.uuid, opprettet = this.created!!, sistEndretAvAktoerId = this.sistEndretAv, sistEndretAvFnr = this.sistEndretAvFnr, opprettetAvAktoerId = this.opprettetAv, opprettetAvFnr = this.opprettetAvFnr, sistEndretDato = this.sistEndret, sistEndretArbeidsgiver = this.sistEndretArbeidsgiver, sistEndretSykmeldt = this.sistEndretSykmeldt, status = null, virksomhet = VirksomhetDTO( navn = null, virksomhetsnummer = this.virksomhetsnummer!! ), godkjentPlan = null, godkjenninger = emptyList(), arbeidsoppgaveListe = emptyList(), arbeidsgiver = PersonDTO( sistAksessert = this.sistAksessertArbeidsgiver, sisteEndring = this.sistEndretArbeidsgiver, sistInnlogget = this.sisteInnloggingArbeidsgiver, samtykke = this.samtykkeArbeidsgiver, aktoerId = null, epost = null, fnr = null, navn = null, tlf = null ), arbeidstaker = PersonDTO( aktoerId = this.aktoerId, fnr = this.smFnr, sistAksessert = this.sistAksessertSykmeldt, sisteEndring = this.sistEndretSykmeldt, sistInnlogget = this.sisteInnloggingSykmeldt, samtykke = this.samtykkeSykmeldt, epost = null, navn = null, tlf = null ), tiltakListe = emptyList(), ) } fun List<POppfoelgingsdialog>.toOppfolgingsplanDTOList(): List<OppfolgingsplanDTO> { return this.map { it.toOppfolgingsplanDTO() } }
6
Kotlin
0
0
ca7b67234f563bcce7f429880b5e7a1ceccaa3c1
2,756
oppfolgingsplan-backend
MIT License
src/jorphan/src/testFixtures/kotlin/org/apache/jorphan/test/JMeterSerialTest.kt
apache
688,352
false
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you 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.apache.jorphan.test import org.junit.jupiter.api.parallel.Execution import org.junit.jupiter.api.parallel.ExecutionMode import org.junit.jupiter.api.parallel.Isolated /** * Used to tag tests which need to be run on their own (in serial) because * either, they cause other tests to fail, or they fail when run in parallel. */ @Isolated @Execution(ExecutionMode.SAME_THREAD) interface JMeterSerialTest
876
null
2095
8,357
872112bf5d08d2f698f765b3c950b2898ec23e98
1,216
jmeter
Apache License 2.0
app/src/main/java/br/com/gilbercs/cartaovisita/data/DataInterfaceDaoCartaoVisita.kt
gilbercs
383,306,346
false
null
package br.com.gilbercs.cartaovisita.data import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface DataInterfaceDaoCartaoVisita { @Query("SELECT * FROM DataCartaoVisita") fun getAll(): LiveData<List<DataCartaoVisita>> @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insert(businessCard: DataCartaoVisita) }
0
Kotlin
0
0
2b087eb0db8551a54922fb6ca76bbbd5c7f1689a
450
CartaoVisita
Apache License 2.0
src/main/kotlin/io/github/edgeatzero/booksource/functions/LocalizationFunction.kt
EdgeAtZero
506,290,698
false
{"Kotlin": 21238}
package io.github.edgeatzero.booksource.functions import java.util.Locale /** * 本地化功能 * */ public interface LocalizationFunction { /** * 当前的语言 * */ public val lang: Locale /** * 支持的语言 * */ public val supportedLang: List<Locale> /** * 语言更改时触发 * */ public fun onLangChanged(lang: Locale) }
0
Kotlin
0
1
c59cc353a6bd46021ede9284ebbd7c2c837b2e48
353
BookSource-api-1.0.x
MIT License
src/main/kotlin/com/mattmik/rapira/visitors/VariableVisitor.kt
rapira-book
519,693,099
true
{"Kotlin": 226030, "ANTLR": 7912}
package com.mattmik.rapira.visitors import com.mattmik.rapira.Environment import com.mattmik.rapira.antlr.RapiraBaseVisitor import com.mattmik.rapira.antlr.RapiraParser import com.mattmik.rapira.errors.InvalidOperationError import com.mattmik.rapira.errors.NonIntegerIndexError import com.mattmik.rapira.objects.RInteger import com.mattmik.rapira.util.andThen import com.mattmik.rapira.util.getOrThrow import com.mattmik.rapira.variables.IndexedVariable import com.mattmik.rapira.variables.SliceVariable import com.mattmik.rapira.variables.Variable /** * A visitor that constructs a [Variable] while walking the tree within a given * [environment]. */ class VariableVisitor(private val environment: Environment) : RapiraBaseVisitor<Variable>() { private val expressionVisitor = ExpressionVisitor(environment) override fun visitVariableCommaIndex(ctx: RapiraParser.VariableCommaIndexContext): Variable { val variable = visit(ctx.variable()) return ctx.commaExpression().expression() .map { val indexValue = expressionVisitor.visit(it) indexValue as? RInteger ?: throw NonIntegerIndexError(indexValue, token = it.start) } .fold(variable) { resultVariable, index -> IndexedVariable(resultVariable, index.value) } } override fun visitVariableColonIndex(ctx: RapiraParser.VariableColonIndexContext): Variable { val variable = visit(ctx.variable()) val leftExpr = ctx.leftExpr?.let { expressionVisitor.visit(it) } val rightExpr = ctx.rightExpr?.let { expressionVisitor.visit(it) } val startIndex = leftExpr ?: RInteger(1) val endIndex = rightExpr ?: ( variable.getValue().andThen { it.length() } .getOrThrow { reason -> InvalidOperationError(reason, token = ctx.variable().start) } ) return SliceVariable(variable, startIndex, endIndex) } override fun visitVariableIdentifier(ctx: RapiraParser.VariableIdentifierContext) = environment[ctx.IDENTIFIER().text] }
0
null
0
0
46f294e59c67747e1c00b5acf32b3cbe44281831
2,091
rapture
Apache License 2.0
app/src/main/java/com/example/pokemonapi/MainActivity.kt
rachelish
706,013,278
false
{"Kotlin": 6682}
package com.example.pokemonapi import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextClock import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.codepath.asynchttpclient.AsyncHttpClient import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler import okhttp3.Headers import org.json.JSONObject class MainActivity : AppCompatActivity() { private lateinit var pokeList: MutableList<String> private lateinit var rvPoke: RecyclerView // private lateinit var temp : MutableList<String> var happyUrl = " " var captureUrl = " " var colorUrl = " " override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) rvPoke = findViewById(R.id.poke_list) pokeList = mutableListOf() // val button = findViewById<Button>(R.id.button) val happiness = findViewById<TextView>(R.id.outHappy) val captureRate = findViewById<TextView>(R.id.outCapture) val color = findViewById<TextView>(R.id.outColor) // val pokemon : EditText = findViewById(R.id.input) getPokeUrl(happiness, captureRate, color) Log.d("petImageURL", "pet image URL set") // getNextBerry(button, happiness, captureRate, color) } private fun getPokeUrl(happiness: TextView, captureRate : TextView, color : TextView){ val client = AsyncHttpClient() // val poke : String = pokemon.toString() client["https://pokeapi.co/api/v2/pokemon?offset=20&limit=10", object : JsonHttpResponseHandler() { override fun onSuccess(statusCode: Int, headers: Headers, json: JsonHttpResponseHandler.JSON) { val pokeImageArray = json.jsonObject.getJSONArray("results") Log.d("JSON WORKS", "$pokeImageArray") for (i in 0 until pokeImageArray.length()) { val c = pokeImageArray.getJSONObject(i) val name = c.getString("name") val happyText = "This is pokemon name: $name" happiness.text = happyText val url = c.getString("url") val urls = "This is pokemon url: $url" captureRate.text = urls // // if (c.getString("name") == "name"){ // // } else if (c.getString("url") == "url"){ // val url = c.getString("url") // val urls = "This is pokemon url: $url" // // } // captureRate.text = urls // temp.add(name) pokeList.add(pokeImageArray.getString(i)) } // happiness.text = temp val adapter = pokeAdapter(pokeList) rvPoke.adapter = adapter rvPoke.layoutManager = LinearLayoutManager(this@MainActivity) Log.d("Dog", "response successful") // happyUrl = json.jsonObject.getString("name") // // captureUrl = json.jsonObject.getString("capture_rate") // colorUrl = json.jsonObject.getString("color") } override fun onFailure( statusCode: Int, headers: Headers?, errorResponse: String, throwable: Throwable? ) { Log.d("Dog Error", errorResponse) } }] } // private fun getNextBerry(button: Button, happiness: TextView, captureRate : TextView, color : TextView){ // Log.d("nextBerry", "Hit getNextBerry()") // button.setOnClickListener { // getPokeUrl() // Log.d("Button", happyUrl) // //// val happyText = "This is base happiness: $happyUrl" // val happyText = "This is base happiness: HEYEYEY" //// val captureText = "This is capture rate: ${captureUrl}" //// val colorText = "This is color: ${colorUrl}" // // happiness.text = happyText //// captureRate.text = captureText //// color.text = colorText // } // } }
0
Kotlin
0
0
fd920da0423e30b419a8bcf4ef23ee369ee64c91
4,427
PokeMonAPI
Apache License 2.0
src/jvmMain/kotlin/org/jetbrains/kotlin/wrappers/realworld/db/DatabaseFactory.kt
karakum-team
439,934,401
true
{"Kotlin": 32271}
package org.jetbrains.kotlin.wrappers.realworld.db import org.flywaydb.core.Flyway import org.jetbrains.exposed.sql.Database import org.slf4j.LoggerFactory import javax.sql.DataSource class DatabaseFactory(pool: DataSource) { private val log = LoggerFactory.getLogger(this::class.java) init { log.info("Initialising database") Database.connect(pool) runFlyway(pool) } private fun runFlyway(datasource: DataSource) { val flyway = Flyway.configure() .dataSource(datasource) .locations("org/jetbrains/kotlin/wrappers/realworld/db") .load() try { flyway.info() flyway.migrate() } catch (exception: Exception) { log.error("Exception running flyway migration", exception) throw exception } log.info("Flyway migration has finished") } }
0
Kotlin
0
0
d680c81db6a5c0a2239f8f44601a40c2a765e445
903
kotlin-wrappers-realworld-example-app
MIT License
composeApp/src/commonMain/kotlin/ru/sportivityteam/vucmirea/assistant/presentation/screens/lesson/LessonStates.kt
SportivityTeam
753,183,017
false
{"Kotlin": 104865, "Swift": 532}
package ru.sportivityteam.vucmirea.assistant.presentation.screens.lesson import ru.sportivityteam.vucmirea.assistant.presentation.entity.LessonPresentation data class LessonViewState( val loading: Boolean = false, val groupNumber: String = "551", val lesson: LessonPresentation = LessonPresentation( "2323", audience = "Ауд. 101", lesson = "ВСП", employee = "Ренкавик В.А.", lessonTime = "09:00-10:30" ) ) sealed class LessonViewAction {} sealed class LessonViewEvent {}
0
Kotlin
0
2
0b3d1ea9f7be4a5df754469230bfed0fdc3de5f2
530
assistant-vuc-mirea
MIT License
Api/src/main/kotlin/net/binggl/mydms/features/records/api/DocumentController.kt
bihe
70,265,570
false
null
package net.binggl.mydms.features.records.api import net.binggl.mydms.features.filestore.FileService import net.binggl.mydms.features.filestore.model.FileItem import net.binggl.mydms.features.records.entity.DocumentEntity import net.binggl.mydms.features.records.entity.SenderEntity import net.binggl.mydms.features.records.entity.TagEntity import net.binggl.mydms.features.records.model.Document import net.binggl.mydms.features.records.model.OrderBy import net.binggl.mydms.features.records.model.PagedDocuments import net.binggl.mydms.features.records.model.SortOrder import net.binggl.mydms.features.records.repository.DocumentRepository import net.binggl.mydms.features.records.repository.SenderRepository import net.binggl.mydms.features.records.repository.TagRepository import net.binggl.mydms.features.upload.UploadConfig import net.binggl.mydms.features.upload.repository.UploadRepository import net.binggl.mydms.infrastructure.error.MydmsException import net.binggl.mydms.shared.api.BaseResource import net.binggl.mydms.shared.models.ActionResult import net.binggl.mydms.shared.models.SimpleResult import net.binggl.mydms.shared.util.toBase64 import org.apache.commons.io.FileUtils import org.apache.commons.io.FilenameUtils import org.apache.commons.lang3.RandomStringUtils import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.transaction.annotation.Transactional import org.springframework.web.bind.annotation.* import java.io.File import java.nio.file.FileSystems import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException import java.util.* import javax.validation.Valid import javax.validation.constraints.NotNull @RestController @RequestMapping("/api/v1/documents") class DocumentController( @Value("\${application.defaultLimit}") private val defaultLimitValue: Int, @Autowired private val uploadConfig: UploadConfig, @Autowired private val repository: DocumentRepository, @Autowired private val tagRepository: TagRepository, @Autowired private val senderRepository: SenderRepository, @Autowired private val uploadRepository: UploadRepository, @Autowired private val fileService: FileService): BaseResource() { @GetMapping(produces = ["application/json"]) @Transactional(readOnly = true) // transaction is needed for the related/lazily loaded collections fun getAll(): List<Document> { return this.repository.searchDocuments( title = Optional.empty(), sender = Optional.empty(), tag = Optional.empty(), dateFrom = Optional.empty(), dateUntil = Optional.empty(), skip = Optional.of(0), limit = Optional.empty(), order = *arrayOf( OrderBy("created", SortOrder.Descending), OrderBy("title", SortOrder.Ascending) ) ).documents } @GetMapping(value = ["/{id}"], produces = ["application/json"]) @Transactional(readOnly = true) fun getDocumentById(@PathVariable id: String): ResponseEntity<*> { val entity = this.repository.findById(id) if (entity.isPresent) { val document = entity.get() return ResponseEntity.ok( Document( id = document.id, title = document.title, created = document.created, alternativeId = document.alternativeId, tags = document.tags.map { it.name }, modified = document.modified, amount = document.amount, uploadFileToken = null, senders = document.senders.map { it.name }, previewLink = document.fileName.toBase64(), fileName = document.fileName) ) } return ResponseEntity .status(HttpStatus.NOT_FOUND) .contentType(MediaType.APPLICATION_JSON) .body(this.error("Could not find the document with id '$id'!")) } @GetMapping(value = ["/search"], produces = ["application/json"]) @Transactional(readOnly = true) fun searchDocuments(@RequestParam("title") title: Optional<String>, @RequestParam("tag") byTag: Optional<String>, @RequestParam("sender") bySender: Optional<String>, @RequestParam("from") fromDateString: Optional<String>, @RequestParam("to") untilDateString: Optional<String>, @RequestParam("limit") limit: Optional<Int>, @RequestParam("skip") skip: Optional<Int>): PagedDocuments { // set defaults val limitResults = if (limit.isPresent) limit.get() else defaultLimitValue val fromDate = if (fromDateString.isPresent) { this.parseDateTime(fromDateString.get()) } else { Optional.empty() } val untilDate = if (untilDateString.isPresent) { this.parseDateTime(untilDateString.get()) } else { Optional.empty() } val orderByDateDesc = OrderBy("created", SortOrder.Descending) val orderByName = OrderBy("title", SortOrder.Ascending) return this.repository.searchDocuments(title, byTag, bySender, fromDate, untilDate, Optional.of(limitResults), skip, orderByDateDesc, orderByName) } @DeleteMapping(value = ["/{id}"], produces = ["application/json"]) @Transactional() fun deleteDocument(@PathVariable id: String): ResponseEntity<*> { LOG.debug("Will attempt to delete document with id '$id'.") val document = this.repository.findById(id) return if (document.isPresent) { LOG.debug("Got document with id: $id - delete it!") this.repository.deleteById(id) LOG.info("Document with id '$id' was deleted.") ResponseEntity.ok(SimpleResult( message = "Document with id '$id' was deleted.", result = ActionResult.Deleted) ) } else { LOG.warn("Cannot delete unknown document with id '$id'") ResponseEntity .status(HttpStatus.NOT_FOUND) .contentType(MediaType.APPLICATION_JSON) .body(this.error("Could not delete document with id '$id'!")) } } @PostMapping(consumes = ["application/json"], produces = ["application/json"]) @Transactional() fun saveDocument(@RequestBody @NotNull @Valid documentPayload: Document): ResponseEntity<SimpleResult> { val tagList = this.processTags(documentPayload.tags) val senderList = this.processSenders(documentPayload.senders) val fileName = this.processUploadFile(documentPayload.uploadFileToken, documentPayload.fileName) var newDoc = true val document = if (StringUtils.isEmpty(documentPayload.id)) { LOG.debug("No id supplied - create a new document.") this.newDocumentInstance(documentPayload, fileName, tagList, senderList) } else { LOG.debug("Id available - lookup document with id '${documentPayload.id}'") val doc = this.repository.findById(documentPayload.id) if (doc.isPresent) { LOG.debug("Got document with id '${documentPayload.id}'") newDoc = false doc.get().copy(title = documentPayload.title, fileName = fileName, previewLink = fileName.toBase64(), amount = documentPayload.amount, modified = LocalDateTime.now(), tags = tagList, senders = senderList, senderList = senderList.joinToString(";") { it.name }, tagList = tagList.joinToString(";") { it.name }) } else { LOG.debug("No document for id '${documentPayload.id}' - create a new document.") this.newDocumentInstance(documentPayload, fileName, tagList, senderList) } } val saveDocument = this.repository.save(document) val result = if (newDoc) { SimpleResult(message = "Created new document '${saveDocument.title}' (${saveDocument.id})", result = ActionResult.Created) } else { SimpleResult(message = "Updated existing document '${saveDocument.title}' (${saveDocument.id})", result = ActionResult.Updated) } return ResponseEntity.ok(result) } private fun processUploadFile(uploadToken: String?, fileName: String): String { if (uploadToken == null || uploadToken == "-") return fileName val result = this.uploadRepository.findById(uploadToken) if (!result.isPresent) { throw MydmsException("Could not get an uploaded document with the given correlation token '$uploadToken'!") } LOG.debug("Read upload-item from store - id: '${result.get().id}'") val folderName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd")) val uploadFile = this.getFile(fileName, this.uploadConfig.uploadPath, uploadToken) val uploadFileContents = FileUtils.readFileToByteArray(uploadFile) LOG.debug("Got upload file '${uploadFile.name}' with payload size '${uploadFileContents.size}'!") val fileItem = FileItem(fileName = fileName, mimeType = result.get().mimeType, payload = uploadFileContents.toTypedArray(), folderName = folderName) if (!this.fileService.saveFile(fileItem)) { throw MydmsException("Could not save file in backend store '${fileItem.fileName}'") } val filePath = "/$folderName/${fileItem.fileName}" if (!uploadFile.delete()) { LOG.warn("Could not delete upload file on filesystem! $uploadToken") } this.uploadRepository.deleteById(result.get().id) return filePath } private fun getFile(fileName: String, uploadPath: String, uploadToken: String): File { val fileExtension = FilenameUtils.getExtension(fileName) val outputPath = FileSystems.getDefault().getPath(uploadPath, String.format("%s.%s", uploadToken, fileExtension)) return outputPath.toFile() } private fun processTags(tags: List<String>): Set<TagEntity> { return if (tags.isNotEmpty()) { tags.map { val result = this.tagRepository.findByNameContainingIgnoreCase(it) if (result.size == 1) { result[0] } else { this.tagRepository.save(TagEntity(name = it)) } }.toSet() } else { emptySet() } } private fun processSenders(senders: List<String>): Set<SenderEntity> { return if (senders.isNotEmpty()) { senders.map { val result = this.senderRepository.findByNameContainingIgnoreCase(it) if (result.isNotEmpty()) { result[0] } else { this.senderRepository.save(SenderEntity(name = it)) } }.toSet() } else { emptySet() } } private fun newDocumentInstance(documentPayload: Document, fileName: String, tagSet: Set<TagEntity>, senderSet: Set<SenderEntity>): DocumentEntity { return DocumentEntity(id = UUID.randomUUID().toString(), title = documentPayload.title, alternativeId = RandomStringUtils.random(8, true, true), fileName = fileName, previewLink = fileName.toBase64(), amount = documentPayload.amount, created = LocalDateTime.now(), senders = senderSet, tags = tagSet, modified = null, senderList = senderSet.joinToString(";") { it.name }, tagList = tagSet.joinToString(";") { it.name } ) } private fun parseDateTime(input: String): Optional<LocalDateTime> { return try { Optional.of(LocalDateTime.parse(input, fmt)) } catch(ex: DateTimeParseException) { LOG.warn("Supplied date format is invalid: $input - parse error: ${ex.message}") Optional.empty() } } private fun error(message: String): SimpleResult { return SimpleResult(message = message, result = ActionResult.Error) } companion object { private val fmt = DateTimeFormatter.ISO_DATE_TIME private val LOG = LoggerFactory.getLogger(DocumentController::class.java) } }
0
Kotlin
0
0
65dae1bfcac17c89f0189548aa24574183ae3e92
13,411
mydms-java
Apache License 2.0
frontend/analyzer/src/commonMain/kotlin/checker/CheckViolation.kt
aripiprazole
328,030,547
false
null
package org.plank.analyzer.checker import org.plank.analyzer.infer.Ty import org.plank.analyzer.infer.VarTy import org.plank.analyzer.resolver.Module import org.plank.syntax.element.GeneratedLoc import org.plank.syntax.element.Identifier import org.plank.syntax.element.Loc import org.plank.syntax.message.CompilerLogger import kotlin.reflect.KClass sealed class CheckViolation(val message: String, var loc: Loc) { fun render(logger: CompilerLogger) { logger.severe(message, loc) } fun withLocation(loc: Loc): CheckViolation { this.loc = loc return this } override fun toString(): String = message } class UnsupportedConstType(type: KClass<*>, loc: Loc = GeneratedLoc) : CheckViolation("Unsupported const type $type", loc) class TypeMismatch(expected: Ty, got: Ty, loc: Loc = GeneratedLoc) : CheckViolation("Type mismatch: expected $expected, got $got", loc) class TypeIsInfinite(name: VarTy, ty: Ty, loc: Loc = GeneratedLoc) : CheckViolation("Type $ty is infinite in $name", loc) class TypeIsNotCallable(ty: Ty, loc: Loc = GeneratedLoc) : CheckViolation("Type $ty is not callable", loc) class TypeIsNotStruct(ty: Ty, loc: Loc = GeneratedLoc) : CheckViolation("Type $ty is not a struct and can not be instantiated", loc) class TypeIsNotStructAndCanNotGet( name: Identifier, ty: Ty, loc: Loc = GeneratedLoc, ) : CheckViolation( "Can not get property `${name.text}` from type $ty because it is not a struct or a module", loc, ) class TypeIsNotPointer(ty: Ty, loc: Loc = GeneratedLoc) : CheckViolation("Type $ty is not a pointer and can not be dereferenced", loc) class TypeInfoCanNotBeDestructured(info: TyInfo, loc: Loc = GeneratedLoc) : CheckViolation("Type $info is not a enum member and can not be destructured", loc) class ScopeIsNotReturnable(scope: Scope, loc: Loc = GeneratedLoc) : CheckViolation("Can not return in a not function scope `${scope.name.text}`", loc) class Redeclaration(name: Identifier, loc: Loc = GeneratedLoc) : CheckViolation("Redeclaration of `${name.text}`", loc) class UnresolvedVariable( name: Identifier, module: Module? = null, loc: Loc = GeneratedLoc, ) : CheckViolation( when (module) { null -> "Unresolved variable `${name.text}`" else -> "Unresolved variable `${name.text}` in ${module.name.text}" }, loc, ) class UnresolvedType(ty: Ty, loc: Loc = GeneratedLoc) : CheckViolation("Unresolved type `$ty`", loc) class UnresolvedTypeAccess(name: Identifier, loc: Loc = GeneratedLoc) : CheckViolation("Unresolved type `${name.text}`", loc) class UnresolvedModule(name: Identifier, loc: Loc = GeneratedLoc) : CheckViolation("Unresolved module `${name.text}`", loc) class CanNotReassignImmutableVariable( name: Identifier, loc: Loc = GeneratedLoc, ) : CheckViolation("Can not reassign immutable variable `${name.text}`", loc) class CanNotReassignImmutableStructMember( name: Identifier, info: TyInfo, loc: Loc = GeneratedLoc, ) : CheckViolation("Can not reassign immutable property `${name.text}` of struct $info", loc) class UnresolvedStructMember( name: Identifier, info: TyInfo, loc: Loc = GeneratedLoc, ) : CheckViolation("Unresolved member `${name.text}` in struct `${info.name.text}`", loc) class UnresolvedEnumVariant( name: Identifier, loc: Loc = GeneratedLoc, ) : CheckViolation("Unresolved variant `${name.text}`", loc) class IncorrectArity(expected: Int, got: Int, loc: Loc = GeneratedLoc) : CheckViolation("Incorrect arity: expected $expected, got $got", loc) class IncorrectEnumArity( expected: Int, got: Int, name: Identifier, loc: Loc = GeneratedLoc, ) : CheckViolation( "Expecting $expected fields when matching `${name.text}`, got $got fields instead", loc )
3
null
1
56
df1e88540f19f6a3878b6395084c7508070ab41d
3,740
plank
MIT License
src/main/kotlin/homeworks/homework4/task1/HashFunction.kt
GirZ0n
210,118,779
false
null
package homeworks.homework4.task1 interface HashFunction<K> { fun calculateHash(element: K): Int }
0
Kotlin
0
0
06f1d0bac88a5aa3367336737c039b20f82dbb4f
104
SPBU-Homework-2
The Unlicense
dsl/src/test/kotlin/io/github/airflux/dsl/extension/JsPathOperatorsTest.kt
airflux
336,002,943
false
null
package io.github.airflux.dsl.extension import io.github.airflux.core.path.JsPath import io.github.airflux.core.path.PathElement import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.collections.shouldContainInOrder class JsPathOperatorsTest : FreeSpec() { init { "The JsPath type" - { "JsPath#Companion#div(String) function" - { val path = JsPath / "user" "should have elements in the order they were passed" { path.elements shouldContainInOrder listOf(PathElement.Key("user")) } } "JsPath#Companion#div(Int) function" - { val path = JsPath / 0 "should have elements in the order they were passed" { path.elements shouldContainInOrder listOf(PathElement.Idx(0)) } } "JsPath#div(String) function" - { val path = JsPath / "user" / "name" "should have elements in the order they were passed" { path.elements shouldContainInOrder listOf(PathElement.Key("user"), PathElement.Key("name")) } } "JsPath#div(Int) function" - { val path = JsPath / "phones" / 0 "should have elements in the order they were passed" { path.elements shouldContainInOrder listOf(PathElement.Key("phones"), PathElement.Idx(0)) } } } } }
0
Kotlin
3
3
52fd7de720789e7d3b493d12a03ecfcb626cbe9c
1,524
airflux
Apache License 2.0
app/src/main/java/com/miel3k/masteringcomposepaging3/presentation/beers/view/BeerItem.kt
miel3k
551,606,018
false
null
package com.miel3k.masteringcomposepaging3.presentation.beers.view import androidx.compose.foundation.layout.* import androidx.compose.material.Card import androidx.compose.material.FloatingActionButton import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.miel3k.masteringcomposepaging3.R import com.miel3k.masteringcomposepaging3.ui.theme.DarkOrange import com.miel3k.masteringcomposepaging3.ui.theme.DroverYellow import com.miel3k.masteringcomposepaging3.ui.theme.WhiteSmoke /** * Created by jmielczarek on 17/10/2022 */ @Composable fun BeerItem(name: String, description: String, imageUrl: String, onBeerTap: () -> Unit) { Box { Card( modifier = Modifier .height(160.dp) .padding(16.dp) .fillMaxWidth(), elevation = 4.dp, backgroundColor = DroverYellow ) { Row( modifier = Modifier .height(IntrinsicSize.Max) .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Card( modifier = Modifier .size(120.dp) .padding(8.dp), backgroundColor = WhiteSmoke ) { AsyncImage( modifier = Modifier.padding(8.dp), model = ImageRequest.Builder(LocalContext.current) .data(imageUrl) .crossfade(true) .build(), contentDescription = "", contentScale = ContentScale.Fit, ) } Column( Modifier .height(IntrinsicSize.Max) .padding(end = 48.dp) ) { Text( text = name, maxLines = 2, overflow = TextOverflow.Ellipsis ) Spacer(modifier = Modifier.height(4.dp)) Text( text = description, maxLines = 2, overflow = TextOverflow.Ellipsis ) } } } FloatingActionButton( modifier = Modifier.align(Alignment.CenterEnd), onClick = onBeerTap, backgroundColor = DarkOrange ) { Icon(painter = painterResource(id = R.drawable.ic_beer), contentDescription = "") } } }
0
Kotlin
0
0
e494e8add36b96f6a0d59840bd23517160acd390
3,102
mastering-compose-paging3
MIT License
boat-core/src/main/kotlin/xyz/srclab/common/collect/ListCollects.kt
srclab-projects
247,777,997
false
null
@file:JvmName("Collects") @file:JvmMultifileClass package xyz.srclab.common.collect import xyz.srclab.common.lang.asComparableComparator import kotlin.random.Random import kotlin.collections.binarySearch as binarySearchKt import kotlin.collections.dropLast as dropLastKt import kotlin.collections.dropLastWhile as dropLastWhileKt import kotlin.collections.elementAt as elementAtKt import kotlin.collections.elementAtOrElse as elementAtOrElseKt import kotlin.collections.elementAtOrNull as elementAtOrNullKt import kotlin.collections.findLast as findLastKt import kotlin.collections.first as firstKt import kotlin.collections.firstOrNull as firstOrNullKt import kotlin.collections.foldRight as foldRightKt import kotlin.collections.foldRightIndexed as foldRightIndexedKt import kotlin.collections.indexOf as indexOfKt import kotlin.collections.indexOfFirst as indexOfFirstKt import kotlin.collections.indexOfLast as indexOfLastKt import kotlin.collections.last as lastKt import kotlin.collections.lastIndexOf as lastIndexOfKt import kotlin.collections.lastOrNull as lastOrNullKt import kotlin.collections.reduceRight as reduceRightKt import kotlin.collections.reduceRightIndexed as reduceRightIndexedKt import kotlin.collections.reduceRightIndexedOrNull as reduceRightIndexedOrNullKt import kotlin.collections.reduceRightOrNull as reduceRightOrNullKt import kotlin.collections.removeAll as removeAllKt import kotlin.collections.removeFirst as removeFirstKt import kotlin.collections.removeFirstOrNull as removeFirstOrNullKt import kotlin.collections.removeLast as removeLastKt import kotlin.collections.removeLastOrNull as removeLastOrNullKt import kotlin.collections.retainAll as retainAllKt import kotlin.collections.reverse as reverseKt import kotlin.collections.shuffle as shuffleKt import kotlin.collections.slice as sliceKt import kotlin.collections.sortWith as sortWithKt import kotlin.collections.takeLast as takeLastKt import kotlin.collections.takeLastWhile as takeLastWhileKt fun <T> List<T>.first(): T { return this.firstKt() } fun <T> List<T>.firstOrNull(): T? { return this.firstOrNullKt() } fun <T> List<T>.last(): T { return this.lastKt() } inline fun <T> List<T>.last(predicate: (T) -> Boolean): T { return this.lastKt(predicate) } fun <T> List<T>.lastOrNull(): T? { return this.lastOrNullKt() } inline fun <T> List<T>.lastOrNull(predicate: (T) -> Boolean): T? { return this.lastOrNullKt(predicate) } fun <T> List<T>.elementAt(index: Int): T { return this.elementAtKt(index) } inline fun <T> List<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T { return this.elementAtOrElseKt(index, defaultValue) } fun <T> List<T>.elementAtOrNull(index: Int): T? { return this.elementAtOrNullKt(index) } inline fun <T> List<T>.findLast(predicate: (T) -> Boolean): T? { return this.findLastKt(predicate) } fun <T> List<T>.indexOf(element: T): Int { return this.indexOfKt(element) } inline fun <T> List<T>.indexOf(predicate: (T) -> Boolean): Int { return this.indexOfFirstKt(predicate) } fun <T> List<T>.lastIndexOf(element: T): Int { return this.lastIndexOfKt(element) } inline fun <T> List<T>.lastIndexOf(predicate: (T) -> Boolean): Int { return this.indexOfLastKt(predicate) } fun <T> List<T>.takeLast(n: Int): List<T> { return this.takeLastKt(n) } inline fun <T> List<T>.takeLastWhile(predicate: (T) -> Boolean): List<T> { return this.takeLastWhileKt(predicate) } fun <T> List<T>.dropLast(n: Int): List<T> { return this.dropLastKt(n) } inline fun <T> List<T>.dropLastWhile(predicate: (T) -> Boolean): List<T> { return this.dropLastWhileKt(predicate) } inline fun <S, T : S> List<T>.reduceRight(operation: (T, S) -> S): S { return this.reduceRightKt(operation) } inline fun <S, T : S> List<T>.reduceRightIndexed(operation: (Int, T, S) -> S): S { return this.reduceRightIndexedKt(operation) } inline fun <S, T : S> List<T>.reduceRightOrNull(operation: (T, S) -> S): S? { return this.reduceRightOrNullKt(operation) } inline fun <S, T : S> List<T>.reduceRightIndexedOrNull(operation: (Int, T, S) -> S): S? { return this.reduceRightIndexedOrNullKt(operation) } inline fun <T, R> List<T>.reduceRight(initial: R, operation: (T, R) -> R): R { return this.foldRightKt(initial, operation) } inline fun <T, R> List<T>.reduceRightIndexed(initial: R, operation: (Int, T, R) -> R): R { return this.foldRightIndexedKt(initial, operation) } fun <T> List<T>.slice(indices: IntArray): List<T> { return this.sliceKt(indices.asIterable()) } fun <T> List<T>.slice(indices: Iterable<Int>): List<T> { return this.sliceKt(indices) } fun <T> List<T>.slice(indices: IntRange): List<T> { return this.sliceKt(indices) } @JvmOverloads fun <T> List<T>.binarySearch(element: T, comparator: Comparator<in T> = asComparableComparator()): Int { return this.binarySearchKt(element, comparator) } fun <T> MutableList<T>.reverse() { this.reverseKt() } @JvmOverloads fun <T> MutableList<T>.sort(comparator: Comparator<in T> = asComparableComparator()) { this.sortWithKt(comparator) } fun <T> MutableList<T>.shuffle() { this.shuffleKt() } fun <T> MutableList<T>.shuffle(random: Random) { this.shuffleKt(random) } fun <T> MutableList<T>.removeAll(predicate: (T) -> Boolean): Boolean { return this.removeAllKt(predicate) } fun <T> MutableList<T>.removeFirst(): T { return this.removeFirstKt() } fun <T> MutableList<T>.removeFirstOrNull(): T? { return this.removeFirstOrNullKt() } fun <T> MutableList<T>.removeLast(): T { return this.removeLastKt() } fun <T> MutableList<T>.removeLastOrNull(): T? { return this.removeLastOrNullKt() } fun <T> MutableList<T>.retainAll(predicate: (T) -> Boolean): Boolean { return this.retainAllKt(predicate) }
0
Kotlin
0
4
192aee01efccc76dcaf18d6d34ebac9726302a83
5,806
boat
Apache License 2.0
app/src/main/java/org/ageage/eggplant/common/api/response/BookmarkStarResponse.kt
jageishi
175,018,359
false
null
package org.ageage.eggplant.common.api.response import com.google.gson.annotations.SerializedName data class BookmarkStarResponse( val entries: List<BookmarkStarEntry>, @SerializedName("can_comment") val canComment: String )
17
Kotlin
0
3
612f4d5d14863795ab4bd5acf52a34d00b6bb0ba
234
Eggplant
Apache License 2.0
src/main/java/cn/edu/kmust/flst/service/backstage/data/DataInfoService.kt
zbeboy
128,647,683
false
{"JavaScript": 1160910, "Java": 925800, "Kotlin": 263657, "HTML": 195302, "CSS": 141096}
package cn.edu.kmust.flst.service.backstage.data import cn.edu.kmust.flst.domain.flst.tables.pojos.DataInfo import cn.edu.kmust.flst.domain.flst.tables.records.DataInfoRecord import org.jooq.Result /** * Created by zbeboy 2018-04-16 . **/ interface DataInfoService { /** * 通过前缀查询 * * @param prefix 前缀 * @return 数据 */ fun findByPrefix(prefix: String): Result<DataInfoRecord> /** * 保存 * * @param dataInfo 数据 */ fun save(dataInfo: List<DataInfo>) }
2
JavaScript
0
0
895b865c6fec882a46f3b47f94e69bbda89724b3
512
FLST
MIT License
code/notificationbuilder/src/main/java/com/adobe/marketing/mobile/notificationbuilder/internal/util/MapData.kt
adobe
800,868,595
false
{"Kotlin": 513933, "Shell": 4574, "Makefile": 1559}
/* Copyright 2024 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.notificationbuilder.internal.util import android.os.Bundle import com.adobe.marketing.mobile.util.DataReader /** * Class responsible for extracting notification data from Remote Message Map. */ internal class MapData(private val data: Map<String, String>) : NotificationData { override fun getString(key: String): String? = DataReader.optString(data, key, null) override fun getInteger(key: String): Int? = DataReader.optString(data, key, null)?.toIntOrNull() override fun getBoolean(key: String): Boolean? = DataReader.optString(data, key, null)?.toBoolean() override fun getLong(key: String): Long? = DataReader.optString(data, key, null)?.toLongOrNull() override fun getBundle(): Bundle { val bundle = Bundle() for (key in data.keys) { bundle.putString(key, data[key]) } return bundle } }
2
Kotlin
9
0
063e3dead89a852be59407e793394ed542597455
1,527
aepsdk-ui-android
Apache License 2.0
app/src/main/java/com/mnemosyne/library/core/cache/Network.kt
cr1m5onk1ng
776,903,562
false
{"Kotlin": 5679}
package com.mnemosyne.library.core.cache import com.mnemosyne.library.core.domain.Resource import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.job import kotlinx.coroutines.launch import kotlin.coroutines.cancellation.CancellationException open class NetworkCacheAgent<T> private constructor( private val scope: CoroutineScope, private val policy: CachePolicy<T> ) : CacheAgent, CoroutineScope by scope { companion object { fun <T> register(scope: CoroutineScope, policy: CachePolicy<T>): NetworkCacheAgent<T> { return NetworkCacheAgent(scope, policy) } } open val resource: MutableStateFlow<Resource<T>> = MutableStateFlow(Resource.Loading(null)) private var commandsChannel: Channel<CacheCommand> = Channel(capacity = Channel.BUFFERED) init { scope.coroutineContext.job.invokeOnCompletion { commandsChannel.close() } launch { commandsChannel.consumeEach(::process) } } override fun ask(command: CacheCommand) { launch { commandsChannel.send(command) } } open fun process(command: CacheCommand) { when(command) { Get -> { launch { resource.emit(Resource.Loading(null)) resource.emit(Resource.Success(policy.get())) } } Fetch -> { launch { coroutineScope { val cached = policy.get() try { resource.update { Resource.Loading(cached) } val net = policy.fetch() launch(Dispatchers.IO) { policy.cache(net) } resource.update { Resource.Success(net) } } catch (t: Throwable) { if(t is CancellationException) throw t resource.update { Resource.Error(cached, t) } } } } } Refresh -> { launch { coroutineScope { val current = policy.get() resource.emit(Resource.Loading(current)) try { val data = policy.fetch() launch(Dispatchers.IO) { policy.cache(data) } resource.emit(Resource.Success(data)) } catch (t: Throwable) { if(t is CancellationException) throw t resource.emit(Resource.Error(current, t)) } } } } is Remove<*> -> { launch { resource.emit(Resource.Loading(null)) policy.remove?.invoke(command.key) resource.emit(Resource.Success(policy.get())) } } } } }
0
Kotlin
0
0
2c90defd9d5257dc5c141892886e0091b3023f77
3,469
mnemosyne
Apache License 2.0
base_mvvm/src/main/java/me/hy/jetpackmvvm/ext/util/ToastExt.kt
qwer2y
484,959,139
false
{"Kotlin": 379456, "Java": 119671}
package me.hy.jetpackmvvm.ext.util import android.graphics.Color import android.view.Gravity import com.blankj.utilcode.util.ToastUtils /** * <pre> * * author: Hy * time : 2022/04/26 * desc : * * </pre> */ fun shortToast(content:String,gravity: Int = Gravity.CENTER){ ToastUtils.make() .setBgColor(Color.parseColor("#FF000000")) .setTextColor(Color.parseColor("#FFFFFF")) .setGravity(gravity,0,100) .setDurationIsLong(false) .show(content) } fun longToast(content:String){ ToastUtils.make() .setBgColor(Color.parseColor("#FF000000")) .setTextColor(Color.parseColor("#FFFFFF")) .setGravity(Gravity.CENTER,0,100) .setDurationIsLong(true) .show(content) }
0
Kotlin
0
0
ba9952ab2a74879ed469639efc6d5b0849c0d5be
766
BaseApp
Apache License 2.0
app/src/main/java/org/rfcx/incidents/service/AirplaneModeReceiver.kt
rfcx
104,899,135
false
{"Kotlin": 1176262, "Java": 1049}
package org.rfcx.incidents.service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log class AirplaneModeReceiver(val callback: ((Boolean) -> Unit)?) : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Log.d("AirplaneModeReceiver", "${intent?.getBooleanExtra("state", false)}") callback?.invoke(intent?.getBooleanExtra("state", false) ?: false) } }
30
Kotlin
0
0
cbcb9402733a959104aff97f26d04244b73bc109
483
guardian-app-android
Apache License 2.0
pipeline/common/src/main/kotlin/nl/tudelft/hyperion/pipeline/connection/PipelinePushZMQ.kt
SERG-Delft
254,399,628
false
{"Gradle Kotlin DSL": 19, "Shell": 5, "Text": 2, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 31, "INI": 1, "Ruby": 5, "AsciiDoc": 1, "YAML": 42, "Dockerfile": 15, "Kotlin": 153, "SQL": 1, "Dotenv": 2, "XML": 4, "Java": 5, "SVG": 2}
package nl.tudelft.hyperion.pipeline.connection import org.zeromq.SocketType /** * ZMQ implementation of message push to successive pipeline plugin. */ class PipelinePushZMQ : ZMQConnection(SocketType.PUSH) { private val logger = mu.KotlinLogging.logger {} /** * Pushes given string on ZMQ socket blocking. * Does not throw. */ @Suppress("TooGenericExceptionCaught") fun push(msg: String) { try { socket.send(msg, zmq.ZMQ.ZMQ_DONTWAIT) } catch (ex: Exception) { logger.error(ex) { "Error pushing message to ZMQ pipeline" } } } }
0
Kotlin
1
13
a010d1b6e59592231a2ed29a6d11af38644f2834
617
hyperion
Apache License 2.0
embrace-android-core/src/main/kotlin/io/embrace/android/embracesdk/internal/session/orchestrator/SessionSpanAttrPopulator.kt
embrace-io
704,537,857
false
{"Kotlin": 2879745, "C": 189341, "Java": 162931, "C++": 13140, "CMake": 4261}
package io.embrace.android.embracesdk.internal.session.orchestrator import io.embrace.android.embracesdk.internal.payload.LifeEventType import io.embrace.android.embracesdk.internal.session.SessionZygote /** * Populates the attributes of a session span. */ interface SessionSpanAttrPopulator { /** * Populates session span attributes at the start of the session. */ fun populateSessionSpanStartAttrs(session: SessionZygote) /** * Populates session span attributes at the end of the session. */ fun populateSessionSpanEndAttrs(endType: LifeEventType?, crashId: String?, coldStart: Boolean) }
25
Kotlin
8
134
459e961f6b722fee3247520b3688a5c54723559b
633
embrace-android-sdk
Apache License 2.0
app/src/main/java/com/rynkbit/jku/stuka/MainActivity.kt
meik99
420,014,550
false
null
package com.rynkbit.jku.stuka import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.rynkbit.jku.stuka.ui.main.MainFragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) } }
0
Kotlin
1
0
5f6da662a7a4900388f756b33a7415df461e0010
353
StuKa
MIT License
app/src/main/java/com/github/qingmei2/opengl_demo/c_image_process/ImageProcessMainActivity.kt
qingmei2
389,633,594
false
{"Kotlin": 121582, "Java": 46901, "GLSL": 2366}
package com.github.qingmei2.opengl_demo.c_image_process import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.github.qingmei2.opengl_demo.R class ImageProcessMainActivity : AppCompatActivity() { companion object { fun launch(context: Context) { val intent = Intent(context, ImageProcessMainActivity::class.java) context.startActivity(intent) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_image_process_main) findViewById<View>(R.id.btn_01).setOnClickListener { ImageProcessDetailActivity.launch(this, ImageProcessDetailActivity.IMAGE_PROCESSOR_NONE) } findViewById<View>(R.id.btn_02).setOnClickListener { ImageProcessDetailActivity.launch(this, ImageProcessDetailActivity.IMAGE_PROCESSOR_VIEWPORT) } findViewById<View>(R.id.btn_03).setOnClickListener { ImageProcessDetailActivity.launch(this, ImageProcessDetailActivity.IMAGE_PROCESSOR_ROTATE) } findViewById<View>(R.id.btn_04).setOnClickListener { ImageProcessDetailActivity.launch(this, ImageProcessDetailActivity.IMAGE_PROCESSOR_ROTATE_MATRIX) } findViewById<View>(R.id.btn_05).setOnClickListener { ImageProcessDetailActivity.launch(this, ImageProcessDetailActivity.IMAGE_PROCESSOR_VIEWPORT_MATRIX) } findViewById<View>(R.id.btn_06).setOnClickListener { ImageProcessDetailActivity.launch(this, ImageProcessDetailActivity.IMAGE_PROCESSOR_3D) } } }
0
Kotlin
15
32
3bf1474ab254fb81d30a2617884380a1aca8ff70
1,741
OpenGL-demo
MIT License
libs/saksbehandling-common/src/main/kotlin/logging/LogUtils.kt
navikt
417,041,535
false
{"Kotlin": 5788367, "TypeScript": 1519740, "Handlebars": 21334, "Shell": 12214, "HTML": 1734, "Dockerfile": 676, "CSS": 598, "PLpgSQL": 556}
package no.nav.etterlatte.libs.common.logging import org.slf4j.Logger import org.slf4j.LoggerFactory import org.slf4j.MDC import java.util.UUID const val CORRELATION_ID: String = "x_correlation_id" fun <T> withLogContext( correlationId: String? = null, kv: Map<String, String> = emptyMap(), block: () -> T, ): T = innerLogContext(correlationId, kv, block) fun withLogContext( correlationId: String? = null, kv: Map<String, String> = emptyMap(), block: () -> Unit, ): Unit = innerLogContext(correlationId, kv, block) private fun <T> innerLogContext( correlationId: String?, kv: Map<String, String> = emptyMap(), block: () -> T, ): T { var exceptionThrown = false try { MDC.put(CORRELATION_ID, correlationId ?: generateCorrelationId()) kv.forEach { MDC.put(it.key, it.value) } return block() } catch (e: Exception) { exceptionThrown = true throw e } finally { if (!exceptionThrown) { MDC.remove(CORRELATION_ID) kv.forEach { MDC.remove(it.key) } } } } private fun generateCorrelationId() = UUID.randomUUID().toString() fun getCorrelationId(): String = MDC.get(CORRELATION_ID) ?: generateCorrelationId() fun sikkerLoggOppstart(applikasjonsnavn: String) { val sikkerLogg = sikkerlogger() sikkerLogg.info("SikkerLogg: $applikasjonsnavn oppstart") } fun sikkerlogger(): Logger = LoggerFactory.getLogger("sikkerLogg")
8
Kotlin
0
6
abd4600c70b4188d7d6272ea2d650421ffdfcfb6
1,513
pensjon-etterlatte-saksbehandling
MIT License
app/src/main/java/pl/polsl/workflow/manager/client/model/data/TaskManagerReportPost.kt
SzymonGajdzica
306,075,061
false
null
package pl.polsl.workflow.manager.client.model.data import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class TaskManagerReportPost( val description: String, val task: Task, ): Parcelable
0
Kotlin
0
0
93c99cc67c7af0bc55ca8fb03f077cdd363cb7e8
233
workflow-manager-client
MIT License
Problem7/src/Problem7.kt
theCroc
268,899,094
false
null
fun main(args: Array<String>) { fun make_sieve(src: Sequence<Int>, prime: Int) = src.filter { it % prime != 0 } var sieve = sequence { var x = 2 while (true) yield(x++) } for (i in 1..10001) { val prime = sieve.first() println("Prime number $i is $prime") sieve = make_sieve(sieve, prime) } }
0
Kotlin
0
0
4e5b1e1f8a65604a0a27cd3e4961519aafa42e38
352
Project-Euler
MIT License
src/test/kotlin/TestUtils.kt
loradd
449,893,412
false
{"Kotlin": 10953, "ANTLR": 2586, "Shell": 202}
import io.loradd.simple.SimpleLexer import io.loradd.simple.SimpleParser import org.antlr.v4.runtime.CharStreams import org.antlr.v4.runtime.CommonTokenStream // build lexer for resource fun <T : Any> lexer(context: T, resourceName: String) = SimpleLexer(CharStreams.fromStream(context.javaClass.getResourceAsStream("/${resourceName}.simple"))) // build parser for resource fun <T : Any> parser(context: T, resourceName: String) = SimpleParser(CommonTokenStream(lexer(context, resourceName))) // extract expected parse tree from resource fun <T : Any> expectedParseTree(context: T, resourceName: String): String = context.javaClass.getResourceAsStream("${resourceName}.tree")?.bufferedReader()?.readText()?.trimIndent() ?: "" // extract expected tokens from resource fun <T : Any> expectedTokens(context: T, resourceName: String): List<String> = context.javaClass.getResourceAsStream("${resourceName}.tokens")?.bufferedReader()?.readLines() ?: emptyList()
0
Kotlin
0
0
0961d39834668497a5fb21e988eec1dc5e434674
977
simple-lang
MIT License
app/src/main/kotlin/com/ceh9/portfolio/features/animations/di/AnimationsModule.kt
CeH9
202,865,791
false
null
package com.ceh9.portfolio.features.animations.di import com.ceh9.portfolio.features.animations.presentation.ui.motionLayoutDemo.MotionLayoutDemoViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module /** * Created by CeH9 on 23.09.2019 */ val animationsModule = module { viewModel { MotionLayoutDemoViewModel(get()) } }
0
Kotlin
0
0
d4efdcffbee64a02cdb82d73d4f707f322964c40
358
Portfolio
MIT License
src/main/kotlin/com/pkpk/join/utils/RequestUtil.kt
pikachu0621
610,385,334
false
{"Kotlin": 180580, "HTML": 1538}
package com.pkpk.join.utils import com.pkpk.join.utils.JsonUtil.retGson import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.util.MultiValueMap import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClient.ResponseSpec import org.springframework.web.util.UriComponentsBuilder /** * 支持同步 和 异步 * implementation("org.springframework.boot:spring-boot-starter-webflux") * gson 解析 json 兼容性好 * implementation("com.google.code.gson:gson:2.8.9") * * */ object RequestUtil { private var webClient: WebClient = WebClient.builder().build() @JvmStatic fun iniBaseDefault( defaultBaseUrl: String? = null, defaultHeaders: HttpHeaders? = null, defaultCookies: MultiValueMap<String, String>? = null ) { val builder = WebClient.builder() if (!defaultBaseUrl.isNullOrEmpty()) builder.baseUrl(defaultBaseUrl) if (!defaultHeaders.isNullOrEmpty()) builder.defaultHeaders { it.addAll(defaultHeaders) } if (!defaultCookies.isNullOrEmpty()) builder.defaultCookies { it.addAll(defaultCookies) } webClient = builder.build() } // 同步 post @JvmStatic private fun urlBasePost( requestsUrl: String, requestsContent: Any, requestsContentType: MediaType, requestsHeaders: HttpHeaders? = null ): ResponseSpec = webClient.post() .uri(requestsUrl) .contentType(requestsContentType) .headers { hs -> requestsHeaders?.let { hs.addAll(it) } } .bodyValue(requestsContent) .retrieve() // 同步 get @JvmStatic private fun urlBaseGet( requestsUrl: String, requestsContent: MultiValueMap<String, String>? = null, requestsHeaders: HttpHeaders? = null ): ResponseSpec = webClient.get() .uri(buildUrlString(requestsUrl, requestsContent)) .headers { hs -> requestsHeaders?.let { hs.addAll(it) } } .retrieve() // post json 类型提交 mono.block() @JvmStatic fun <T> String.urlPost( requestsContent: Any, responseType: Class<T>, requestsContentType: MediaType = MediaType.APPLICATION_JSON, requestsHeaders: HttpHeaders? = null ): ResponseEntity<T>? = urlBasePost(this, requestsContent, requestsContentType, requestsHeaders) .toEntity(responseType) .block() // 利用Gson兼容好 @JvmStatic inline fun <reified T> String.urlPost( requestsContent: Any, requestsContentType: MediaType = MediaType.APPLICATION_JSON, requestsHeaders: HttpHeaders? = null ): T? { val body = this.urlPost(requestsContent, String::class.java, requestsContentType, requestsHeaders)?.body ?: return null return retGson<T>(body) } // post formData 类型提交 @JvmStatic fun <T> String.urlPost( requestsContent: MultiValueMap<String, String>, responseType: Class<T>, requestsContentType: MediaType = MediaType.MULTIPART_FORM_DATA, requestsHeaders: HttpHeaders? = null ): ResponseEntity<T>? = urlBasePost(this, requestsContent, requestsContentType, requestsHeaders) .toEntity(responseType) .block() @JvmStatic inline fun <reified T> String.urlPost( requestsContent: MultiValueMap<String, String>, requestsContentType: MediaType = MediaType.MULTIPART_FORM_DATA, requestsHeaders: HttpHeaders? = null ): T? { val body = this.urlPost(requestsContent, String::class.java, requestsContentType, requestsHeaders)?.body ?: return null return retGson<T>(body) } // get 提交 @JvmStatic fun <T> String.urlGet( responseType: Class<T>, requestsContent: MultiValueMap<String, String>? = null, requestsHeaders: HttpHeaders? = null ): ResponseEntity<T>? = urlBaseGet(this, requestsContent, requestsHeaders) .toEntity(responseType) .block() @JvmStatic inline fun <reified T> String.urlGet( requestsContent: MultiValueMap<String, String>? = null, requestsHeaders: HttpHeaders? = null ): T? { val body = this.urlGet(String::class.java, requestsContent, requestsHeaders)?.body ?: return null return retGson<T>(body) } @JvmStatic inline fun <reified T> typeReference() = object : ParameterizedTypeReference<T>() {} @JvmStatic fun buildUrlString(baseUrl: String, map: MultiValueMap<String, String>?): String { map ?: return baseUrl val builder = UriComponentsBuilder.fromHttpUrl(baseUrl) map.forEach { (name: String, values: List<String>) -> builder.queryParam(name, values) } return builder.toUriString() } @JvmStatic fun httpHeaderForSystem(): HttpHeaders = HttpHeaders().apply { add("Accept", "*/*") //add("Accept-Encoding", "gzip, deflate, br") add("Connection", "keep-alive") } @JvmStatic fun httpHeaderForAndroid(): HttpHeaders = HttpHeaders().apply { addAll(httpHeaderForSystem()) add( HttpHeaders.USER_AGENT, "Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Mobile Safari/537.36" ) } @JvmStatic fun httpHeaderOkHttp(code: String = "3.12.13"): HttpHeaders = HttpHeaders().apply { addAll(httpHeaderForSystem()) add( HttpHeaders.USER_AGENT, "okhttp/$code" ) } @JvmStatic fun httpHeaderForWindows(): HttpHeaders = HttpHeaders().apply { addAll(httpHeaderForSystem()) add( HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" ) } @JvmStatic fun httpHeaderForIOS(): HttpHeaders = HttpHeaders().apply { addAll(httpHeaderForSystem()) add( HttpHeaders.USER_AGENT, "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1" ) } }
0
Kotlin
1
2
ba0083b43f8f082c740fb627045b66a11d05cac4
6,349
JoinSpring
Apache License 2.0
src/main/kotlin/com/pkpk/join/utils/RequestUtil.kt
pikachu0621
610,385,334
false
{"Kotlin": 180580, "HTML": 1538}
package com.pkpk.join.utils import com.pkpk.join.utils.JsonUtil.retGson import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.util.MultiValueMap import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClient.ResponseSpec import org.springframework.web.util.UriComponentsBuilder /** * 支持同步 和 异步 * implementation("org.springframework.boot:spring-boot-starter-webflux") * gson 解析 json 兼容性好 * implementation("com.google.code.gson:gson:2.8.9") * * */ object RequestUtil { private var webClient: WebClient = WebClient.builder().build() @JvmStatic fun iniBaseDefault( defaultBaseUrl: String? = null, defaultHeaders: HttpHeaders? = null, defaultCookies: MultiValueMap<String, String>? = null ) { val builder = WebClient.builder() if (!defaultBaseUrl.isNullOrEmpty()) builder.baseUrl(defaultBaseUrl) if (!defaultHeaders.isNullOrEmpty()) builder.defaultHeaders { it.addAll(defaultHeaders) } if (!defaultCookies.isNullOrEmpty()) builder.defaultCookies { it.addAll(defaultCookies) } webClient = builder.build() } // 同步 post @JvmStatic private fun urlBasePost( requestsUrl: String, requestsContent: Any, requestsContentType: MediaType, requestsHeaders: HttpHeaders? = null ): ResponseSpec = webClient.post() .uri(requestsUrl) .contentType(requestsContentType) .headers { hs -> requestsHeaders?.let { hs.addAll(it) } } .bodyValue(requestsContent) .retrieve() // 同步 get @JvmStatic private fun urlBaseGet( requestsUrl: String, requestsContent: MultiValueMap<String, String>? = null, requestsHeaders: HttpHeaders? = null ): ResponseSpec = webClient.get() .uri(buildUrlString(requestsUrl, requestsContent)) .headers { hs -> requestsHeaders?.let { hs.addAll(it) } } .retrieve() // post json 类型提交 mono.block() @JvmStatic fun <T> String.urlPost( requestsContent: Any, responseType: Class<T>, requestsContentType: MediaType = MediaType.APPLICATION_JSON, requestsHeaders: HttpHeaders? = null ): ResponseEntity<T>? = urlBasePost(this, requestsContent, requestsContentType, requestsHeaders) .toEntity(responseType) .block() // 利用Gson兼容好 @JvmStatic inline fun <reified T> String.urlPost( requestsContent: Any, requestsContentType: MediaType = MediaType.APPLICATION_JSON, requestsHeaders: HttpHeaders? = null ): T? { val body = this.urlPost(requestsContent, String::class.java, requestsContentType, requestsHeaders)?.body ?: return null return retGson<T>(body) } // post formData 类型提交 @JvmStatic fun <T> String.urlPost( requestsContent: MultiValueMap<String, String>, responseType: Class<T>, requestsContentType: MediaType = MediaType.MULTIPART_FORM_DATA, requestsHeaders: HttpHeaders? = null ): ResponseEntity<T>? = urlBasePost(this, requestsContent, requestsContentType, requestsHeaders) .toEntity(responseType) .block() @JvmStatic inline fun <reified T> String.urlPost( requestsContent: MultiValueMap<String, String>, requestsContentType: MediaType = MediaType.MULTIPART_FORM_DATA, requestsHeaders: HttpHeaders? = null ): T? { val body = this.urlPost(requestsContent, String::class.java, requestsContentType, requestsHeaders)?.body ?: return null return retGson<T>(body) } // get 提交 @JvmStatic fun <T> String.urlGet( responseType: Class<T>, requestsContent: MultiValueMap<String, String>? = null, requestsHeaders: HttpHeaders? = null ): ResponseEntity<T>? = urlBaseGet(this, requestsContent, requestsHeaders) .toEntity(responseType) .block() @JvmStatic inline fun <reified T> String.urlGet( requestsContent: MultiValueMap<String, String>? = null, requestsHeaders: HttpHeaders? = null ): T? { val body = this.urlGet(String::class.java, requestsContent, requestsHeaders)?.body ?: return null return retGson<T>(body) } @JvmStatic inline fun <reified T> typeReference() = object : ParameterizedTypeReference<T>() {} @JvmStatic fun buildUrlString(baseUrl: String, map: MultiValueMap<String, String>?): String { map ?: return baseUrl val builder = UriComponentsBuilder.fromHttpUrl(baseUrl) map.forEach { (name: String, values: List<String>) -> builder.queryParam(name, values) } return builder.toUriString() } @JvmStatic fun httpHeaderForSystem(): HttpHeaders = HttpHeaders().apply { add("Accept", "*/*") //add("Accept-Encoding", "gzip, deflate, br") add("Connection", "keep-alive") } @JvmStatic fun httpHeaderForAndroid(): HttpHeaders = HttpHeaders().apply { addAll(httpHeaderForSystem()) add( HttpHeaders.USER_AGENT, "Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Mobile Safari/537.36" ) } @JvmStatic fun httpHeaderOkHttp(code: String = "3.12.13"): HttpHeaders = HttpHeaders().apply { addAll(httpHeaderForSystem()) add( HttpHeaders.USER_AGENT, "okhttp/$code" ) } @JvmStatic fun httpHeaderForWindows(): HttpHeaders = HttpHeaders().apply { addAll(httpHeaderForSystem()) add( HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" ) } @JvmStatic fun httpHeaderForIOS(): HttpHeaders = HttpHeaders().apply { addAll(httpHeaderForSystem()) add( HttpHeaders.USER_AGENT, "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1" ) } }
0
Kotlin
1
2
ba0083b43f8f082c740fb627045b66a11d05cac4
6,349
JoinSpring
Apache License 2.0
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/expressions/IrDynamicOperatorExpression.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.ir.expressions import org.jetbrains.kotlin.ir.visitors.IrElementTransformer import org.jetbrains.kotlin.ir.visitors.IrElementVisitor abstract class IrDynamicOperatorExpression : IrDynamicExpression() { abstract val operator: IrDynamicOperator abstract var receiver: IrExpression abstract val arguments: MutableList<IrExpression> override fun <R, D> accept(visitor: IrElementVisitor<R, D>, data: D): R = visitor.visitDynamicOperatorExpression(this, data) override fun <D> acceptChildren(visitor: IrElementVisitor<Unit, D>, data: D) { receiver.accept(visitor, data) for (valueArgument in arguments) { valueArgument.accept(visitor, data) } } override fun <D> transformChildren(transformer: IrElementTransformer<D>, data: D) { receiver = receiver.transform(transformer, data) for (i in arguments.indices) { arguments[i] = arguments[i].transform(transformer, data) } } }
132
null
5074
40,992
57fe6721e3afb154571eb36812fd8ef7ec9d2026
1,224
kotlin
Apache License 2.0
XML/SportsApp/app/src/main/java/com/example/android/sports/MainActivity.kt
pherasymchuk
723,622,473
false
{"Kotlin": 481652}
/* * Copyright (c) 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 * * 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.sports import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updatePadding import androidx.navigation.ui.AppBarConfiguration import com.example.android.sports.databinding.ActivityMainBinding import com.example.android.sports.insetter.Insetter class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) Insetter.Base(binding.root).apply(top = true) Insetter.Base(binding.appBarLayout).apply(left = true, right = true) binding.toolbar.title = this.title } }
0
Kotlin
0
1
84b5ebf8c1cece5e6417c474f0070398ad8848f6
1,670
GoogleCodelabsApps
MIT License
aws-globalaccelerator-listener/src/main/kotlin/software/amazon/globalaccelerator/listener/HandlerCommons.kt
aws-cloudformation
244,498,522
false
{"Kotlin": 302084}
package software.amazon.globalaccelerator.listener import com.amazonaws.services.globalaccelerator.AWSGlobalAccelerator import com.amazonaws.services.globalaccelerator.model.Accelerator import com.amazonaws.services.globalaccelerator.model.AcceleratorNotFoundException import com.amazonaws.services.globalaccelerator.model.AcceleratorStatus import com.amazonaws.services.globalaccelerator.model.DescribeAcceleratorRequest import com.amazonaws.services.globalaccelerator.model.DescribeListenerRequest import com.amazonaws.services.globalaccelerator.model.Listener import com.amazonaws.services.globalaccelerator.model.ListenerNotFoundException import software.amazon.cloudformation.proxy.AmazonWebServicesClientProxy import software.amazon.cloudformation.proxy.Logger import software.amazon.cloudformation.proxy.ProgressEvent /** * Singleton class for common methods used by CRUD handlers */ object HandlerCommons { private const val CALLBACK_DELAY_IN_SECONDS = 1 const val NUMBER_OF_STATE_POLL_RETRIES = 60 / CALLBACK_DELAY_IN_SECONDS * 60 * 4 // 4 hours private const val TIMED_OUT_MESSAGE = "Timed out waiting for listener to be deployed." /** * Wait for accelerator to go in-sync (DEPLOYED) */ fun waitForSynchronizedStep(context: CallbackContext, model: ResourceModel, proxy: AmazonWebServicesClientProxy, agaClient: AWSGlobalAccelerator, logger: Logger, isDelete: Boolean = false): ProgressEvent<ResourceModel, CallbackContext?> { logger.debug("Waiting for accelerator with arn: [${model.acceleratorArn}] to be deployed. " + "Stabilization retries remaining ${context.stabilizationRetriesRemaining}") val newCallbackContext = context.copy(stabilizationRetriesRemaining = context.stabilizationRetriesRemaining - 1) if (newCallbackContext.stabilizationRetriesRemaining < 0) { throw RuntimeException(TIMED_OUT_MESSAGE) } val accelerator = getAccelerator(model.acceleratorArn, proxy, agaClient, logger) // Addresses race condition: accelerator associated with listener is deleted out-of-band. // Sequence diagram :: Delete Listener -> (accelerator deleted) -> waiting for accelerator to go-in-sync // Ignore AcceleratorNotFoundException exception. if (accelerator == null && isDelete) { return ProgressEvent.defaultSuccessHandler(null) } return if (accelerator!!.status == AcceleratorStatus.DEPLOYED.toString()) { logger.debug("Accelerator with arn: [${accelerator.acceleratorArn}] is deployed.") // Delete contract expects no model to be returned upon delete success var resourceModel: ResourceModel? = model if (isDelete) { resourceModel = null } ProgressEvent.defaultSuccessHandler(resourceModel) } else { ProgressEvent.defaultInProgressHandler(newCallbackContext, CALLBACK_DELAY_IN_SECONDS, model) } } /** * Get the accelerator with the specified ARN. * @param arn ARN of the accelerator * @return NULL if the accelerator does not exist */ fun getAccelerator(arn: String, proxy: AmazonWebServicesClientProxy, agaClient: AWSGlobalAccelerator, logger: Logger): Accelerator? { return try { val request = DescribeAcceleratorRequest().withAcceleratorArn(arn) proxy.injectCredentialsAndInvoke(request, agaClient::describeAccelerator).accelerator } catch (ex: AcceleratorNotFoundException) { logger.error("Accelerator with arn: [$arn] not found.") null } } /** Gets the listener with the specified ARN * @param arn ARN of the listener * @return NULL if listener does not exist */ fun getListener(arn: String, proxy: AmazonWebServicesClientProxy, agaClient: AWSGlobalAccelerator, logger: Logger): Listener? { return try { val request = DescribeListenerRequest().withListenerArn(arn) proxy.injectCredentialsAndInvoke(request, agaClient::describeListener).listener } catch (ex: ListenerNotFoundException) { logger.debug("Listener with arn: [$arn] not found.") null } } }
1
Kotlin
4
2
d2f0274115fa2c8499e28a55f4db19ed0e745d3d
4,464
aws-cloudformation-resource-providers-globalaccelerator
Apache License 2.0
features/featureFlags/src/main/java/com/bagadesh/featureflags/domain/Feature.kt
bagadesh
754,458,708
false
{"Kotlin": 300128}
package com.feature.core.domain /** * Created by bagadesh on 14/04/23. */ data class Feature( val name: String, val description: String, val enabled: Boolean, val variables: List<FeatureVariable> = emptyList() ) { val variableMap: Map<String, FeatureVariable> = variables.associateBy { it.name } } data class FeatureVariable( val name: String, val value: Any )
0
Kotlin
0
0
c37ada4e6382877485f6693b7f784a9200873884
392
MySamplesAndroid
Apache License 2.0
app/src/main/java/pl/temomuko/autostoprace/AsrApplication.kt
TeMoMuKo
49,103,797
false
null
package pl.temomuko.autostoprace import android.app.Application import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.IntentFilter import android.net.ConnectivityManager import android.os.Build import android.support.annotation.RequiresApi import com.crashlytics.android.Crashlytics import com.squareup.leakcanary.LeakCanary import io.fabric.sdk.android.Fabric import pl.temomuko.autostoprace.injection.component.ApplicationComponent import pl.temomuko.autostoprace.injection.component.DaggerApplicationComponent import pl.temomuko.autostoprace.injection.module.ApplicationModule import pl.temomuko.autostoprace.service.LocationSyncService import pl.temomuko.autostoprace.service.receiver.NetworkChangeReceiver import java.util.* import javax.inject.Inject class AsrApplication : Application() { @Inject lateinit var mServiceNetworkReceiver: LocationSyncService.NetworkChangeReceiver @Inject lateinit var mNetworkReceiver: NetworkChangeReceiver val applicationComponent: ApplicationComponent by lazy { DaggerApplicationComponent.builder() .applicationModule(ApplicationModule(this)) .build() } override fun onCreate() { super.onCreate() initFlavorConfig(this) if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis. // You should not init your app in this process. return } LeakCanary.install(this) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) registerNotificationChannels() applicationComponent.inject(this) Fabric.with(this, Crashlytics()) Locale.setDefault(Locale(Constants.DEFAULT_LOCALE)) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { registerReceiver( mServiceNetworkReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) ) registerReceiver( mNetworkReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) ) } } @RequiresApi(Build.VERSION_CODES.O) private fun registerNotificationChannels() { val generalChannel = NotificationChannel( Channels.GENERAL, getString(R.string.general_notification_channel_name), NotificationManager.IMPORTANCE_HIGH ) val notificationManager = getSystemService( Context.NOTIFICATION_SERVICE ) as NotificationManager notificationManager.createNotificationChannel(generalChannel) } companion object { @JvmStatic fun getApplicationComponent(context: Context): ApplicationComponent { return (context.applicationContext as AsrApplication).applicationComponent } } object Channels { const val GENERAL = "general" } }
2
null
1
2
1524b18324b56591d6ca50f5230d0d6c3a82e561
2,965
AutoStopRace-Android
Apache License 2.0
app/src/main/java/dev/konnov/databasesandroid/ui/theme/Theme.kt
konnovdev
483,974,667
false
null
package dev.konnov.databasesandroid.ui.theme import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable // TODO make a good looking theme and move it to a separate module @Composable fun DatabasesAndroidTheme( content: @Composable () -> Unit ) { MaterialTheme( content = content ) }
0
Kotlin
0
2
aa8e9646c39be83a9dc3f3a397176bdb497ed2b4
335
android_databases
MIT License
src/main/kotlin/me/underlow/tglog/messages/ContainerNameFilter.kt
underlow
760,457,314
false
{"Kotlin": 42275, "Dockerfile": 567}
package me.underlow.tglog.messages import ContainerNamesConfiguration import mu.KotlinLogging /** * Filters messages by container name * @param configuration configuration for container names * filtering rules are: * 1. if container name is in exclude list, message is excluded * 2. if include list is empty message is excluded * 3. if include list is not empty and container name is not in include list, message is excluded * 4. if include list is '*' then all containers (except excluded) are included * * @return true if message should be included, false if message should be excluded */ class ContainerNameFilter(private val configuration: ContainerNamesConfiguration) { private val includeAll = configuration.include == "*" private val include = configuration.include.split(",").filter { it.isNotBlank() }.map { it.lowercase().trim() }.toSet() private val exclude = configuration.exclude.split(",").filter { it.isNotBlank() }.map { it.lowercase().trim() }.toSet() fun filter(message: Message): Boolean { if (message.containerName.lowercase() in exclude) { logger.debug { "Container ${message.containerName} is excluded from processing" } return false } if (includeAll) { return true } if (message.containerName.lowercase() in include) { return true } logger.debug { "Container ${message.containerName} is not included in processing" } return false } } private val logger = KotlinLogging.logger { }
0
Kotlin
0
0
aede1051b175db18a06b0bd2df75b6b812df3a98
1,553
tglog
MIT License
cachex/src/main/java/com/rommansabbir/cachex/worker/CacheXWorkersImpl.kt
rommansabbir
234,885,071
false
null
package com.rommansabbir.cachex.worker import com.google.gson.Gson import com.rommansabbir.cachex.converter.CacheXDataConverter import com.rommansabbir.cachex.exceptions.CacheXListLimitException import com.rommansabbir.cachex.exceptions.CacheXNoDataException import com.rommansabbir.cachex.functional.Either import com.rommansabbir.cachex.security.CacheXEncryptionTool import com.rommansabbir.cachex.storage.CacheXStorage class CacheXWorkersImpl : CacheXWorkers { override suspend fun <T> cacheList( key: String, data: List<T>, xCacheXStorage: CacheXStorage ): Either<Exception, Boolean> { return try { if (data.size > 1000) { return Either.Left(CacheXListLimitException("Max list size limit is: 1000")) } xCacheXStorage.doCache( CacheXEncryptionTool.encrypt(CacheXDataConverter().toJson(data)), key ) println(Thread.currentThread()) Either.Right(true) } catch (e: Exception) { Either.Left(e) } } override suspend fun <T> getCacheList( key: String, clazz: Class<T>, xCacheXStorage: CacheXStorage ): Either<Exception, ArrayList<T>> { return try { val data = xCacheXStorage.getCache(key) if (data != null) { val result = CacheXDataConverter().fromJSONList<T>(CacheXEncryptionTool.decrypt(data)) if (clazz.canonicalName == String::class.java.canonicalName) { result.toArray() return Either.Right(result) } if (clazz.canonicalName == Number::class.java.canonicalName) { result.toArray() return Either.Right(result) } if (clazz.canonicalName == Int::class.java.canonicalName) { result.toArray() return Either.Right(result) } if (clazz.canonicalName == Double::class.java.canonicalName) { result.toArray() return Either.Right(result) } if (clazz.canonicalName == Float::class.java.canonicalName) { result.toArray() return Either.Right(result) } if (clazz.canonicalName == Long::class.java.canonicalName) { result.toArray() return Either.Right(result) } if (clazz.canonicalName == Boolean::class.java.canonicalName) { result.toArray() return Either.Right(result) } val tempDataList = arrayListOf<T>() result.forEach { tempDataList.add(Gson().fromJson(Gson().toJsonTree(it).asJsonObject, clazz)) } Either.Right(tempDataList) } else { Either.Left(CacheXNoDataException("No data found")) } } catch (e: Exception) { Either.Left(e) } } override suspend fun <T> cacheSingle( key: String, data: T, xStorage: CacheXStorage ): Either<Exception, Boolean> { return try { xStorage.doCache(CacheXEncryptionTool.encrypt(CacheXDataConverter().toJson(data)), key) Either.Right(true) } catch (e: Exception) { Either.Left(e) } } override suspend fun <T> getCacheSingle( key: String, clazz: Class<T>, xCacheXStorage: CacheXStorage ): Either<Exception, T> { return try { val data = xCacheXStorage.getCache(key) return if (data != null) { val result = CacheXDataConverter().fromJSONSingle(CacheXEncryptionTool.decrypt(data), clazz) Either.Right(result) } else { Either.Left(CacheXNoDataException("No data found")) } } catch (e: Exception) { Either.Left(e) } } }
0
Kotlin
2
25
52b92072d020dbe89552be539f362dc84e42d103
4,179
CacheX
Apache License 2.0
dataModule/src/main/java/com/aneonex/bitcoinchecker/datamodule/model/market/Biki.kt
aneonex
286,067,147
false
null
package com.aneonex.bitcoinchecker.datamodule.model.market import com.aneonex.bitcoinchecker.datamodule.model.CheckerInfo import com.aneonex.bitcoinchecker.datamodule.model.CurrencyPairInfo import com.aneonex.bitcoinchecker.datamodule.model.Market import com.aneonex.bitcoinchecker.datamodule.model.Ticker import com.aneonex.bitcoinchecker.datamodule.util.forEachJSONObject import org.json.JSONObject class Biki : Market(NAME, TTS_NAME, null) { companion object { private const val NAME = "BiKi" private const val TTS_NAME = NAME private const val URL = "https://openapi.biki.cc/open/api/get_ticker?symbol=%1\$s" private const val URL_CURRENCY_PAIRS = "https://openapi.biki.cc/open/api/common/symbols" } override fun getCurrencyPairsUrl(requestId: Int): String { return URL_CURRENCY_PAIRS } override fun parseCurrencyPairsFromJsonObject(requestId: Int, jsonObject: JSONObject, pairs: MutableList<CurrencyPairInfo>) { jsonObject.getJSONArray("data").forEachJSONObject { market-> pairs.add( CurrencyPairInfo( market.getString("base_coin"), market.getString("count_coin"), market.getString("symbol") )) } } override fun getUrl(requestId: Int, checkerInfo: CheckerInfo): String { return String.format(URL, checkerInfo.currencyPairId) } override fun parseTickerFromJsonObject(requestId: Int, jsonObject: JSONObject, ticker: Ticker, checkerInfo: CheckerInfo) { jsonObject.getJSONObject("data").apply { ticker.ask = getDouble("sell") ticker.bid = getDouble("buy") ticker.high = getDouble("high") ticker.low = getDouble("low") ticker.last = getDouble("last") ticker.vol = getDouble("vol") ticker.timestamp = getLong("time") } } }
20
Kotlin
14
41
ec6a6cfb98bbc8194eedb8c9ff9f73eaa679c328
1,915
BitcoinChecker
MIT License
commonkey/src/main/kotlin/com/william/helloword/commonkey/TypeAlias.kt
williamtan1989
619,193,723
false
null
package com.william.helloword.commonkey typealias LanguageId = String
0
Kotlin
0
0
d5e7a1d05a645ae94472d72c5e1d4f67e80a8de7
70
hello-word-android
Apache License 2.0
graph/graph-adapter-input-rest-spring-mvc/src/main/kotlin/eu/tib/orkg/prototype/statements/BundleRepresentationAdapter.kt
TIBHannover
197,416,205
false
null
package eu.tib.orkg.prototype.statements import eu.tib.orkg.prototype.statements.api.BundleRepresentation import eu.tib.orkg.prototype.statements.domain.model.Bundle interface BundleRepresentationAdapter : StatementRepresentationAdapter { fun Bundle.toBundleRepresentation(): BundleRepresentation = BundleRepresentation( rootId = [email protected], bundle = [email protected]().toList() ) }
0
Kotlin
2
5
e1f3332c445c6b3b5a8ac2621cb8562d84ae594d
500
orkg-backend
MIT License
src/main/kotlin/anissia/domain/agenda/core/ports/outbound/AgendaPollRepository.kt
anissia-net
319,510,882
false
{"Kotlin": 255675, "HTML": 5480, "HCL": 794}
package anissia.domain.agenda.core.ports.outbound import anissia.domain.agenda.core.AgendaPoll import org.springframework.data.jpa.repository.JpaRepository interface AgendaPollRepository : JpaRepository<AgendaPoll, Long> { //, QuerydslPredicateExecutor<AgendaPoll> { }
4
Kotlin
4
13
2ae6753685dc26aa5905d98e6088ffdda0c5cce3
273
anissia-core
Creative Commons Attribution 4.0 International
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/UserPilotTie.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.UserPilotTie: ImageVector get() { if (_userPilotTie != null) { return _userPilotTie!! } _userPilotTie = Builder(name = "UserPilotTie", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(5.207f, 5.619f) lineToRelative(0.793f, 0.396f) verticalLineToRelative(1.984f) curveToRelative(0.0f, 3.309f, 2.691f, 6.0f, 6.0f, 6.0f) reflectiveCurveToRelative(6.0f, -2.691f, 6.0f, -6.0f) verticalLineToRelative(-1.984f) lineToRelative(0.793f, -0.396f) curveToRelative(0.74f, -0.37f, 1.207f, -1.126f, 1.207f, -1.954f) curveToRelative(0.0f, -0.976f, -0.648f, -1.834f, -1.587f, -2.101f) lineTo(13.698f, 0.224f) curveToRelative(-0.557f, -0.139f, -1.128f, -0.209f, -1.698f, -0.209f) reflectiveCurveToRelative(-1.14f, 0.07f, -1.698f, 0.209f) lineToRelative(-4.715f, 1.34f) curveToRelative(-0.939f, 0.267f, -1.587f, 1.125f, -1.587f, 2.101f) curveToRelative(0.0f, 0.827f, 0.467f, 1.584f, 1.207f, 1.954f) close() moveTo(15.0f, 8.0f) curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f) reflectiveCurveToRelative(-3.0f, -1.346f, -3.0f, -3.0f) verticalLineToRelative(-0.199f) curveToRelative(0.833f, 0.123f, 1.818f, 0.214f, 3.0f, 0.214f) reflectiveCurveToRelative(2.167f, -0.091f, 3.0f, -0.214f) verticalLineToRelative(0.199f) close() moveTo(9.5f, 3.5f) curveToRelative(0.188f, -0.312f, 0.519f, -0.485f, 0.858f, -0.485f) curveToRelative(0.175f, 0.0f, 0.352f, 0.046f, 0.514f, 0.143f) lineToRelative(1.128f, 0.677f) lineToRelative(1.128f, -0.677f) curveToRelative(0.161f, -0.097f, 0.338f, -0.143f, 0.514f, -0.143f) curveToRelative(0.34f, 0.0f, 0.671f, 0.173f, 0.858f, 0.485f) curveToRelative(0.284f, 0.474f, 0.131f, 1.088f, -0.343f, 1.372f) lineToRelative(-1.643f, 0.985f) curveToRelative(-0.158f, 0.095f, -0.336f, 0.143f, -0.514f, 0.143f) reflectiveCurveToRelative(-0.356f, -0.047f, -0.514f, -0.143f) lineToRelative(-1.643f, -0.985f) curveToRelative(-0.474f, -0.284f, -0.627f, -0.898f, -0.343f, -1.372f) close() moveTo(19.712f, 23.985f) curveToRelative(-0.071f, 0.01f, -0.144f, 0.015f, -0.214f, 0.015f) curveToRelative(-0.734f, 0.0f, -1.376f, -0.54f, -1.483f, -1.288f) curveToRelative(-0.31f, -2.171f, -1.9f, -3.814f, -4.081f, -4.433f) lineToRelative(-1.434f, 1.721f) lineToRelative(1.397f, 2.794f) curveToRelative(0.277f, 0.554f, -0.126f, 1.206f, -0.746f, 1.206f) horizontalLineToRelative(-2.302f) curveToRelative(-0.62f, 0.0f, -1.023f, -0.652f, -0.746f, -1.206f) lineToRelative(1.397f, -2.794f) lineToRelative(-1.434f, -1.721f) curveToRelative(-2.181f, 0.619f, -3.771f, 2.262f, -4.081f, 4.433f) curveToRelative(-0.118f, 0.819f, -0.884f, 1.382f, -1.697f, 1.273f) curveToRelative(-0.82f, -0.117f, -1.391f, -0.877f, -1.273f, -1.697f) curveToRelative(0.613f, -4.291f, 4.309f, -7.288f, 8.985f, -7.288f) reflectiveCurveToRelative(8.372f, 2.997f, 8.985f, 7.288f) curveToRelative(0.117f, 0.82f, -0.453f, 1.58f, -1.273f, 1.697f) close() } } .build() return _userPilotTie!! } private var _userPilotTie: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,766
icons
MIT License
app/src/androidTest/java/com/lucianbc/receiptscan/presentation/scanner/OcrCompareTest.kt
lucianbc
183,749,890
false
null
package com.lucianbc.receiptscan.presentation.scanner import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import androidx.test.platform.app.InstrumentationRegistry import androidx.test.runner.AndroidJUnit4 import com.google.android.gms.tasks.Tasks import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.common.FirebaseVisionImage import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class OcrCompareTest { @Test fun runOcr() { val image = readImage() val recognizer = FirebaseVision.getInstance().onDeviceTextRecognizer val firebaseImage = FirebaseVisionImage.fromBitmap(image) val result = recognizer.processImage(firebaseImage).let { Tasks.await(it) } println(result) } private fun readImage(): Bitmap { val context = InstrumentationRegistry.getInstrumentation().context val imageStream = context.assets.open("receipt.jpg") return BitmapFactory.decodeStream(imageStream).rotate(90f) } private fun Bitmap.rotate(deg: Float): Bitmap { val matrix = Matrix() matrix.postRotate(deg) return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true) } }
13
null
1
2
05950c87f2eda6f53f886e340459aa13cdbdd621
1,287
ReceiptScan
Apache License 2.0
Android-Poi/app/src/main/java/com/example/myapplication/SensitiveDataConfirm.kt
RonaldColyar
334,067,254
false
null
package com.example.myapplication import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_sensitive_data_confirm.* class SensitiveDataConfirm : AppCompatActivity() { //pass data to result checker(located in mainhub activity) private fun check_type_and_pass(){ val data = Intent() if (intent.getStringExtra("type") == "person") { data.putExtra("code", SensitiveCodeInput.text.toString()) data.putExtra("id" , intent.getStringExtra("id")) } else{ data.putExtra("code", SensitiveCodeInput.text.toString()) } setResult(202,data) this.finish() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sensitive_data_confirm) CloseSensitiveActivity.setOnClickListener { this.finish() } ConfirmSensitiveDeletion.setOnClickListener { check_type_and_pass() } } }
0
Kotlin
0
2
6c41b33c7295a596d3ba37d70b1a5002c3b8b14d
1,100
POI-Android
MIT License
order-service/src/main/kotlin/dev/geovaneshimizu/order/domain/outbox/NewMessageValues.kt
geovaneshimizu
333,155,318
false
null
package dev.geovaneshimizu.order.domain.outbox data class NewMessageValues(val event: String, val payload: Any)
0
Kotlin
0
0
248fac519ff0b238350bcf1bef33727943d8b7d2
141
outbox-pattern
MIT License
solar/src/main/java/com/chiksmedina/solar/boldduotone/weather/SunFog.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.boldduotone.weather import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.boldduotone.WeatherGroup val WeatherGroup.SunFog: ImageVector get() { if (_sunFog != null) { return _sunFog!! } _sunFog = Builder( name = "SunFog", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd ) { moveTo(7.25f, 22.0f) curveTo(7.25f, 21.5858f, 7.5858f, 21.25f, 8.0f, 21.25f) horizontalLineTo(16.0f) curveTo(16.4142f, 21.25f, 16.75f, 21.5858f, 16.75f, 22.0f) curveTo(16.75f, 22.4142f, 16.4142f, 22.75f, 16.0f, 22.75f) horizontalLineTo(8.0f) curveTo(7.5858f, 22.75f, 7.25f, 22.4142f, 7.25f, 22.0f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd ) { moveTo(12.0f, 1.25f) curveTo(12.4142f, 1.25f, 12.75f, 1.5858f, 12.75f, 2.0f) verticalLineTo(3.0f) curveTo(12.75f, 3.4142f, 12.4142f, 3.75f, 12.0f, 3.75f) curveTo(11.5858f, 3.75f, 11.25f, 3.4142f, 11.25f, 3.0f) verticalLineTo(2.0f) curveTo(11.25f, 1.5858f, 11.5858f, 1.25f, 12.0f, 1.25f) close() moveTo(1.25f, 12.0f) curveTo(1.25f, 11.5858f, 1.5858f, 11.25f, 2.0f, 11.25f) horizontalLineTo(3.0f) curveTo(3.4142f, 11.25f, 3.75f, 11.5858f, 3.75f, 12.0f) curveTo(3.75f, 12.4142f, 3.4142f, 12.75f, 3.0f, 12.75f) horizontalLineTo(2.0f) curveTo(1.5858f, 12.75f, 1.25f, 12.4142f, 1.25f, 12.0f) close() moveTo(20.25f, 12.0f) curveTo(20.25f, 11.5858f, 20.5858f, 11.25f, 21.0f, 11.25f) horizontalLineTo(22.0f) curveTo(22.4142f, 11.25f, 22.75f, 11.5858f, 22.75f, 12.0f) curveTo(22.75f, 12.4142f, 22.4142f, 12.75f, 22.0f, 12.75f) horizontalLineTo(21.0f) curveTo(20.5858f, 12.75f, 20.25f, 12.4142f, 20.25f, 12.0f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd ) { moveTo(6.0827f, 15.25f) horizontalLineTo(2.0f) curveTo(1.5858f, 15.25f, 1.25f, 15.5858f, 1.25f, 16.0f) curveTo(1.25f, 16.4142f, 1.5858f, 16.75f, 2.0f, 16.75f) horizontalLineTo(22.0f) curveTo(22.4142f, 16.75f, 22.75f, 16.4142f, 22.75f, 16.0f) curveTo(22.75f, 15.5858f, 22.4142f, 15.25f, 22.0f, 15.25f) horizontalLineTo(17.9173f) horizontalLineTo(6.0827f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(4.25f, 19.0f) curveTo(4.25f, 18.5858f, 4.5858f, 18.25f, 5.0f, 18.25f) horizontalLineTo(19.0f) curveTo(19.4142f, 18.25f, 19.75f, 18.5858f, 19.75f, 19.0f) curveTo(19.75f, 19.4142f, 19.4142f, 19.75f, 19.0f, 19.75f) horizontalLineTo(5.0f) curveTo(4.5858f, 19.75f, 4.25f, 19.4142f, 4.25f, 19.0f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(4.3984f, 4.3984f) curveTo(4.6913f, 4.1055f, 5.1662f, 4.1055f, 5.459f, 4.3984f) lineTo(5.8519f, 4.7912f) curveTo(6.1448f, 5.0841f, 6.1448f, 5.559f, 5.8519f, 5.8519f) curveTo(5.559f, 6.1448f, 5.0841f, 6.1448f, 4.7912f, 5.8519f) lineTo(4.3984f, 5.459f) curveTo(4.1055f, 5.1662f, 4.1055f, 4.6913f, 4.3984f, 4.3984f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(19.6009f, 4.3986f) curveTo(19.8938f, 4.6915f, 19.8938f, 5.1664f, 19.6009f, 5.4593f) lineTo(19.2081f, 5.8521f) curveTo(18.9152f, 6.145f, 18.4403f, 6.145f, 18.1474f, 5.8521f) curveTo(17.8545f, 5.5592f, 17.8545f, 5.0844f, 18.1474f, 4.7915f) lineTo(18.5402f, 4.3986f) curveTo(18.8331f, 4.1058f, 19.308f, 4.1058f, 19.6009f, 4.3986f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(5.25f, 12.0f) curveTo(5.25f, 13.1778f, 5.5521f, 14.2858f, 6.0827f, 15.25f) horizontalLineTo(17.9173f) curveTo(18.4479f, 14.2858f, 18.75f, 13.1778f, 18.75f, 12.0f) curveTo(18.75f, 8.2721f, 15.7279f, 5.25f, 12.0f, 5.25f) curveTo(8.2721f, 5.25f, 5.25f, 8.2721f, 5.25f, 12.0f) close() } } .build() return _sunFog!! } private var _sunFog: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
7,080
SolarIconSetAndroid
MIT License
feature-news/src/main/java/com/paulrybitskyi/gamedge/feature/news/data/datastores/local/database/ArticlesDatabaseDataStore.kt
mars885
289,036,871
false
null
/* * Copyright 2021 <NAME>, <EMAIL> * * 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.paulrybitskyi.gamedge.feature.news.data.datastores.local.database import com.paulrybitskyi.gamedge.core.providers.DispatcherProvider import com.paulrybitskyi.gamedge.common.data.common.Pagination import com.paulrybitskyi.gamedge.database.articles.DatabaseArticle import com.paulrybitskyi.gamedge.database.articles.tables.ArticlesTable import com.paulrybitskyi.gamedge.feature.news.data.DataArticle import com.paulrybitskyi.gamedge.feature.news.data.datastores.local.ArticlesLocalDataStore import com.paulrybitskyi.hiltbinder.BindType import javax.inject.Inject import javax.inject.Singleton import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext @Singleton @BindType internal class ArticlesDatabaseDataStore @Inject constructor( private val articlesTable: ArticlesTable, private val dispatcherProvider: DispatcherProvider, private val dbArticleMapper: DbArticleMapper ) : ArticlesLocalDataStore { override suspend fun saveArticles(articles: List<DataArticle>) { articlesTable.saveArticles( withContext(dispatcherProvider.computation) { dbArticleMapper.mapToDatabaseArticles(articles) } ) } override fun observeArticles(pagination: Pagination): Flow<List<DataArticle>> { return articlesTable.observeArticles( offset = pagination.offset, limit = pagination.limit ) .toDataArticlesFlow() } private fun Flow<List<DatabaseArticle>>.toDataArticlesFlow(): Flow<List<DataArticle>> { return distinctUntilChanged() .map(dbArticleMapper::mapToDataArticles) .flowOn(dispatcherProvider.computation) } }
12
Kotlin
52
517
d79750f85fb7a924983178bd1843301cabc2d698
2,423
gamedge
Apache License 2.0
onehooklibrarykotlin/src/main/java/com/onehook/onhooklibrarykotlin/viewcontroller/controller/LinearRecyclerViewController.kt
oneHook
228,925,790
false
null
package com.onehook.onhooklibrarykotlin.viewcontroller.controller import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class DefaultViewHolder(val view: View) : RecyclerView.ViewHolder(view) abstract class SimpleAdapter : RecyclerView.Adapter<DefaultViewHolder>() { protected abstract fun onCreateView(parent: ViewGroup, viewType: Int): View protected abstract fun onBindView(view: View, position: Int) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefaultViewHolder { return DefaultViewHolder(onCreateView(parent, viewType)) } override fun onBindViewHolder(holder: DefaultViewHolder, position: Int) { onBindView(holder.view, position) } } open class LinearRecyclerViewController : ViewController() { val recyclerView: RecyclerView by lazy { RecyclerView(context) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val frameLayout = FrameLayout(container.context) frameLayout.addView(recyclerView.apply { layoutManager = LinearLayoutManager(context) }) return frameLayout } }
1
null
1
1
713c0bfb52b6afb6cf0b3b56acb4cd7679659744
1,321
oneHookLibraryKotlin
MIT License
AndroidInfoLib/src/main/java/com/udfsoft/androidinfo/lib/network/AndroidInfoApi.kt
LiteSoftware
550,715,360
false
{"Kotlin": 127152}
package com.udfsoft.androidinfo.lib.network import com.udfsoft.androidinfo.lib.network.entity.DeviceInformationNetwork import retrofit2.http.GET import retrofit2.http.Query interface AndroidInfoApi { @GET("GetDeviceInfo/") fun getDeviceInfo(@Query("id_menu") menuId: Int): retrofit2.Call<DeviceInformationNetwork> }
0
Kotlin
0
3
1c87c9c9f5e830a444ac6e6319f8eed50ddc5977
327
AndroidInfoLib
Apache License 2.0
AndroidInfoLib/src/main/java/com/udfsoft/androidinfo/lib/network/AndroidInfoApi.kt
LiteSoftware
550,715,360
false
{"Kotlin": 127152}
package com.udfsoft.androidinfo.lib.network import com.udfsoft.androidinfo.lib.network.entity.DeviceInformationNetwork import retrofit2.http.GET import retrofit2.http.Query interface AndroidInfoApi { @GET("GetDeviceInfo/") fun getDeviceInfo(@Query("id_menu") menuId: Int): retrofit2.Call<DeviceInformationNetwork> }
0
Kotlin
0
3
1c87c9c9f5e830a444ac6e6319f8eed50ddc5977
327
AndroidInfoLib
Apache License 2.0
app/src/main/java/com/vixiloc/vixgpt/presentation/navigations/MainNavigationHost.kt
vixiloc
665,395,128
false
{"Kotlin": 55107}
package com.vixiloc.vixgpt.presentation.navigations import androidx.compose.animation.AnimatedContentTransitionScope import androidx.compose.animation.core.tween import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.vixiloc.vixgpt.presentation.home.HomeScreen import com.vixiloc.vixgpt.presentation.settings.SettingsScreen @Composable fun MainNavigationHost(navhostController: NavHostController) { NavHost(navController = navhostController, startDestination = MainRoute.Home.name) { composable( route = MainRoute.Home.name, enterTransition = { slideIntoContainer( towards = AnimatedContentTransitionScope.SlideDirection.Companion.Down, animationSpec = tween(300) ) }, exitTransition = { slideOutOfContainer( towards = AnimatedContentTransitionScope.SlideDirection.Companion.Up, animationSpec = tween(300) ) }, ) { HomeScreen(navhostController = navhostController) } composable( route = MainRoute.Settings.name, enterTransition = { slideIntoContainer( towards = AnimatedContentTransitionScope.SlideDirection.Companion.Up, animationSpec = tween(300) ) }, exitTransition = { slideOutOfContainer( towards = AnimatedContentTransitionScope.SlideDirection.Companion.Down, animationSpec = tween(300) ) }, ) { SettingsScreen(navhostController = navhostController) } } }
0
Kotlin
0
2
4dc9cf37da862cf247e691bbfafbb4c67ca0dd83
1,884
vixgpt
Apache License 2.0
idea/tests/testData/multiModuleQuickFix/other/createClassFromUsageRef/header/a/common.kt
JetBrains
278,369,660
false
null
// "Create class 'ClassG'" "true" package a fun test() { a.b.ClassG<caret>() }
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
85
intellij-kotlin
Apache License 2.0
quizzlerd/android/app/src/main/kotlin/com/example/quizzlerd/MainActivity.kt
vijethph
372,726,856
false
{"Dart": 91074, "HTML": 4543, "Swift": 4040, "Kotlin": 1328, "Objective-C": 380}
package com.example.quizzlerd import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
1
b69d509828c82b92499033495fb60c8fa42f8e11
126
FlutterApps
MIT License
src/main/kotlin/com/onepeloton/locust4k/messages/LocustClient.kt
pelotoncycle
858,897,532
false
{"Kotlin": 61198, "Python": 380}
package com.onepeloton.locust4k.messages import io.github.oshai.kotlinlogging.KotlinLogging import org.zeromq.SocketType import org.zeromq.ZMQ import org.zeromq.ZMQ.Socket import zmq.ZMQ.ZMQ_DONTWAIT import java.io.Closeable class LocustClient( private val host: String, private val port: Int, private val nodeId: String, ) : Closeable { private val logger = KotlinLogging.logger {} private val zmqContext = ZMQ.context(1) // NOTE: dealer sockets are not thread-safe private var zmqSocket: Socket = zmqContext.socket(SocketType.DEALER) fun connect(reconnect: Boolean = false): Boolean { if (reconnect) { logger.debug { "Reconnecting" } zmqSocket.close() zmqSocket = zmqContext.socket(SocketType.DEALER) } else { logger.debug { "Connecting" } } zmqSocket.identity = nodeId.toByteArray() zmqSocket.tcpKeepAlive = 1 return try { zmqSocket.connect("tcp://$host:$port") } catch (e: Exception) { logger.error(e) { "Connection failed" } false } } fun sendMessageAsync(message: Message): Boolean { return zmqSocket.send(message.bytes, ZMQ_DONTWAIT) } // fun receiveMessageAsync(): Message? { // return zmqSocket.recv(ZMQ_DONTWAIT)?.let { bytes -> // Message(bytes) // } // } fun receiveMessageBlocking(): Message? { return zmqSocket.recv()?.let { bytes -> Message(bytes) } } override fun close() { logger.debug { "Closing connection" } zmqContext.use { _ -> zmqSocket.close() } } }
1
Kotlin
1
4
a607e736b547e9ca445d743fb1e3e411485d6dc3
1,694
locust4k
MIT License
livekit-android-sdk/src/main/java/io/livekit/android/dagger/CoroutinesModule.kt
livekit
339,892,560
false
null
package io.livekit.android.dagger import dagger.Module import dagger.Provides import kotlinx.coroutines.Dispatchers import javax.inject.Named @Module object CoroutinesModule { @Provides @Named(InjectionNames.DISPATCHER_DEFAULT) fun defaultDispatcher() = Dispatchers.Default @Provides @Named(InjectionNames.DISPATCHER_IO) fun ioDispatcher() = Dispatchers.IO @Provides @Named(InjectionNames.DISPATCHER_MAIN) fun mainDispatcher() = Dispatchers.Main @Provides @Named(InjectionNames.DISPATCHER_UNCONFINED) fun unconfinedDispatcher() = Dispatchers.Unconfined }
9
null
35
99
5b49711143729c497d77684f892ee5fa3ef5d900
607
client-sdk-android
Apache License 2.0
compiler/testData/codegen/bytecodeText/nullCheckOptimization/redundantSafeCall_1_4.kt
JetBrains
3,432,266
false
null
// !LANGUAGE: -SafeCallsAreAlwaysNullable // IGNORE_BACKEND_K2: JVM_IR // Status: Feature is always on in K2. See KT-62930 fun test(s: String) = s?.length // 0 IFNULL // 0 IFNONNULL // 0 intValue // 0 valueOf
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
211
kotlin
Apache License 2.0
app/src/main/java/baidu/com/testlibproject/test/ClassUnderTest.kt
weimuhua
45,332,286
false
null
package baidu.com.testlibproject.test import android.content.Context import baidu.com.testlibproject.R class ClassUnderTest(private val context: Context) { fun getHelloWorldString(): String { return context.getString(R.string.hello_world_string) } }
1
null
1
1
9cd5205c1e9375599b37d716f32c4a64dfd6f897
268
TestLibProject
Apache License 2.0
src/main/kotlin/gg/octave/bot/utils/extensions/CommandClientBuilder.kt
lucas178
270,852,455
false
null
/* * MIT License * * Copyright (c) 2020 Melms Media LLC * * 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 gg.octave.bot.utils.extensions import me.devoxin.flight.api.CommandClientBuilder import me.devoxin.flight.api.entities.Invite import me.devoxin.flight.internal.parsers.* fun CommandClientBuilder.registerAlmostAllParsers(): CommandClientBuilder { val booleanParser = BooleanParser() addCustomParser(Boolean::class.java, booleanParser) addCustomParser(java.lang.Boolean::class.java, booleanParser) val doubleParser = DoubleParser() addCustomParser(Double::class.java, doubleParser) addCustomParser(java.lang.Double::class.java, doubleParser) val floatParser = FloatParser() addCustomParser(Float::class.java, floatParser) addCustomParser(java.lang.Float::class.java, floatParser) val intParser = IntParser() addCustomParser(Int::class.java, intParser) addCustomParser(java.lang.Integer::class.java, intParser) val longParser = LongParser() addCustomParser(Long::class.java, longParser) addCustomParser(java.lang.Long::class.java, longParser) // JDA entities val inviteParser = InviteParser() addCustomParser(Invite::class.java, inviteParser) addCustomParser(net.dv8tion.jda.api.entities.Invite::class.java, inviteParser) //addCustomParser(MemberParser()) addCustomParser(UserParser()) addCustomParser(RoleParser()) addCustomParser(TextChannelParser()) addCustomParser(VoiceChannelParser()) // Custom entities addCustomParser(EmojiParser()) addCustomParser(StringParser()) addCustomParser(SnowflakeParser()) addCustomParser(UrlParser()) return this }
0
Kotlin
0
1
6cac8521ef42490fa8b80682d6b447d7b6ddcacd
2,725
Octave-development
MIT License