path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/pt/dbmg/mobiletaiga/rss/RssFeedListAdapter.kt
worm69
166,021,572
false
{"Gradle": 7, "YAML": 12, "Java Properties": 2, "Markdown": 6, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Proguard": 3, "Kotlin": 464, "XML": 78, "Java": 55, "JSON": 2, "GraphQL": 1, "Dockerfile": 1}
package pt.dbmg.mobiletaiga.rss import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import pt.dbmg.mobiletaiga.R /** *Created by E818 on 11/07/2019 */ class RssFeedListAdapter(private val mRssFeedModels: List<RssFeedModel>) : RecyclerView.Adapter<RssFeedListAdapter.FeedModelViewHolder>() { class FeedModelViewHolder( val rssFeedView: View) : RecyclerView.ViewHolder(rssFeedView) override fun onCreateViewHolder(parent: ViewGroup, type: Int): FeedModelViewHolder { val v = LayoutInflater.from(parent.context) .inflate(R.layout.item_rss_feed, parent, false) return FeedModelViewHolder(v) } override fun onBindViewHolder(holder: FeedModelViewHolder, position: Int) { val rssFeedModel = mRssFeedModels[position] (holder.rssFeedView.findViewById(R.id.titleText) as TextView).text = rssFeedModel.title (holder.rssFeedView.findViewById(R.id.descriptionText) as TextView).text = rssFeedModel.description (holder.rssFeedView.findViewById(R.id.linkText) as TextView).text = rssFeedModel.link } override fun getItemCount(): Int { return mRssFeedModels.size } }
0
Kotlin
0
4
8ec09bed018d57225b85e042865608952633c622
1,277
mobiletaiga
Apache License 2.0
app/src/main/java/com/personal/dailynews/ui/news/FilteredNewsListViewModel.kt
amalg989
224,334,979
false
null
package com.personal.dailynews.ui.news import android.util.Log import android.view.View import androidx.lifecycle.MutableLiveData import com.personal.dailynews.data.model.Response import com.personal.dailynews.ui.base.BaseViewModel import com.personal.dailynews.util.constants.NewsCategories import com.personal.dailynews.util.network.apis.NewsAPI import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import java.util.* import javax.inject.Inject class FilteredNewsListViewModel: BaseViewModel() { val TAG:String = "FilteredNewsList" @Inject lateinit var newsApi: NewsAPI private lateinit var subscription: Disposable val newsListAdapter: NewsListAdapter = NewsListAdapter() val loadingVisibility: MutableLiveData<Int> = MutableLiveData() init { loadFilteredHedlines(NewsCategories.BITCOIN) } fun loadFilteredHedlines(query: NewsCategories){ subscription = newsApi.getFilteredArticles(query.category) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { onRetrieveHeadlinesListStart() } .doOnTerminate { onRetrieveHeadlinesListFinish() } .subscribe( { result -> onRetrieveHeadlinesListSuccess(result) }, { error -> onRetrieveHeadlinesListError(error) } ) } override fun onCleared() { super.onCleared() subscription.dispose() } private fun onRetrieveHeadlinesListStart(){ loadingVisibility.value = View.VISIBLE } private fun onRetrieveHeadlinesListFinish(){ loadingVisibility.value = View.GONE } private fun onRetrieveHeadlinesListSuccess(response: Response){ Log.d(TAG, "onRetrieveHeadlinesListSuccess, $response") newsListAdapter.updateNewsList(response.articles) } private fun onRetrieveHeadlinesListError(error: Throwable?){ Log.d(TAG, "onRetrieveHeadlinesListError, $error") error?.printStackTrace() } }
0
Kotlin
0
0
0eb84e57c195026e7f405c60fcb15f80c43a9bc1
2,109
daily-news
MIT License
sample/src/main/java/com/pexels/sample/photo/PhotosActivity.kt
SanjayDevTech
452,577,381
false
{"Kotlin": 41004, "Shell": 51}
package com.pexels.sample.photo import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.pexels.sample.R import com.pexels.sample.databinding.ActivityPhotosBinding class PhotosActivity : AppCompatActivity() { private lateinit var binding: ActivityPhotosBinding private lateinit var navController: NavController companion object { @JvmStatic private val TAG = PhotosActivity::class.java.simpleName } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp() || super.onSupportNavigateUp() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPhotosBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment navController = navHostFragment.navController setupActionBarWithNavController( navController, AppBarConfiguration( setOf(R.id.curatedPhotos, R.id.searchPhotos), ) ) binding.bottomNavView.setupWithNavController(navController) } }
3
Kotlin
1
2
7a196b158459361111d0c4f05831ed04bceaff97
1,585
pexels-android
Apache License 2.0
app/src/main/kotlin/com/simplemobiletools/calendar/adapters/FilterEventTypeAdapter.kt
ectenshaw
89,411,513
false
{"Gradle": 3, "JSON": 2, "Markdown": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Java Properties": 1, "Proguard": 1, "XML": 93, "Kotlin": 72, "Java": 3}
package com.simplemobiletools.calendar.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.simplemobiletools.calendar.R import com.simplemobiletools.calendar.activities.SimpleActivity import com.simplemobiletools.calendar.extensions.config import com.simplemobiletools.calendar.models.EventType import com.simplemobiletools.commons.extensions.setBackgroundWithStroke import kotlinx.android.synthetic.main.filter_event_type_view.view.* import java.util.* class FilterEventTypeAdapter(val activity: SimpleActivity, val mItems: List<EventType>, mDisplayEventTypes: Set<String>) : RecyclerView.Adapter<FilterEventTypeAdapter.ViewHolder>() { val views = ArrayList<View>() companion object { var textColor = 0 lateinit var displayEventTypes: Set<String> lateinit var selectedItems: ArrayList<String> } init { textColor = activity.config.textColor displayEventTypes = mDisplayEventTypes selectedItems = ArrayList() displayEventTypes.mapTo(selectedItems, { it }) } fun getSelectedItemsSet(): HashSet<String> { val selectedItemsSet = HashSet<String>(selectedItems.size) selectedItems.mapTo(selectedItemsSet, { it }) return selectedItemsSet } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.filter_event_type_view, parent, false) return ViewHolder(activity, view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { views.add(holder.bindView(mItems[position])) } override fun getItemCount() = mItems.size class ViewHolder(val activity: SimpleActivity, view: View) : RecyclerView.ViewHolder(view) { fun bindView(eventType: EventType): View { val id = eventType.id.toString() itemView.apply { filter_event_type_checkbox.setColors(activity.config.textColor, activity.config.primaryColor, activity.config.backgroundColor) filter_event_type_checkbox.text = eventType.title filter_event_type_color.setBackgroundWithStroke(eventType.color, activity.config.backgroundColor) filter_event_type_holder.setOnClickListener { filter_event_type_checkbox.toggle() if (filter_event_type_checkbox.isChecked) { selectedItems.add(id) } else { selectedItems.remove(id) } } filter_event_type_checkbox.isChecked = displayEventTypes.contains(id) } return itemView } } }
0
Kotlin
0
2
f84659417f86f0a765ae4e9f4353ae76d2cd6480
2,823
MyTime
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/SelectAllTwoTone.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/SelectAllTwoTone") @file:JsNonModule package mui.icons.material @JsName("default") external val SelectAllTwoTone: SvgIconComponent
10
Kotlin
145
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
214
kotlin-wrappers
Apache License 2.0
packages/flutter_coast_audio_miniaudio/example/android/app/src/main/kotlin/com/example/flutter_coast_audio_miniaudio_example/MainActivity.kt
SKKbySSK
602,695,804
false
{"Dart": 434694, "C": 324287, "CMake": 48783, "Swift": 9294, "Ruby": 4886, "Kotlin": 2276, "Shell": 2081, "Objective-C": 38}
package com.example.flutter_coast_audio_miniaudio_example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
5
Dart
10
70
26123e4bc3e16a000a055cedfd24294032cf1bf9
154
coast_audio
MIT License
SKIE/kotlin-compiler/core/src/commonMain/kotlin/co/touchlab/skie/context/CommonSkieContext.kt
touchlab
685,579,240
false
null
package co.touchlab.skie.context import co.touchlab.skie.analytics.performance.SkiePerformanceAnalytics import co.touchlab.skie.configuration.GlobalConfiguration import co.touchlab.skie.configuration.SkieConfigurationFlag import co.touchlab.skie.configuration.provider.CompilerSkieConfigurationData import co.touchlab.skie.phases.SkiePhaseScheduler import co.touchlab.skie.plugin.analytics.AnalyticsCollector import co.touchlab.skie.util.CompilerShim import co.touchlab.skie.util.KirReporter import co.touchlab.skie.util.directory.FrameworkLayout import co.touchlab.skie.util.directory.SkieBuildDirectory import co.touchlab.skie.util.directory.SkieDirectories interface CommonSkieContext { val context: CommonSkieContext val skieConfigurationData: CompilerSkieConfigurationData val globalConfiguration: GlobalConfiguration val skieDirectories: SkieDirectories val framework: FrameworkLayout val analyticsCollector: AnalyticsCollector val skiePerformanceAnalyticsProducer: SkiePerformanceAnalytics.Producer val kirReporter: KirReporter val skiePhaseScheduler: SkiePhaseScheduler val compilerShim: CompilerShim val skieBuildDirectory: SkieBuildDirectory get() = skieDirectories.buildDirectory val SkieConfigurationFlag.isEnabled: Boolean get() = globalConfiguration.isFlagEnabled(this) val SkieConfigurationFlag.isDisabled: Boolean get() = this.isEnabled.not() fun SkieConfigurationFlag.enable() { globalConfiguration.enableFlag(this) } fun SkieConfigurationFlag.disable() { globalConfiguration.disableFlag(this) } }
9
null
8
735
b96044d4dec91e4b85c5b310226c6f56e3bfa2b5
1,640
SKIE
Apache License 2.0
compiler/testData/ir/irText/js/dynamic/dynamicArrayAssignment.kt
JetBrains
3,432,266
false
null
fun testArrayAssignment(d: dynamic) { d["KEY"] = 1 } fun testArrayAssignmentFake(d: dynamic) { d.set("KEY", 2) }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
122
kotlin
Apache License 2.0
app/src/main/java/com/app/moodtrack_android/di/GraphQLModule.kt
martinheitmann
431,879,047
false
{"Kotlin": 272822}
package com.app.moodtrack_android.di import com.apollographql.apollo.ApolloClient import com.app.moodtrack_android.BuildConfig import com.google.gson.Gson import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module object GraphQLModule { @Provides @Singleton fun provideApolloClient() : ApolloClient { return ApolloClient.builder() //.serverUrl("http://10.0.2.2:4000/graphql") .serverUrl(BuildConfig.SERVER_URL) .build() } @Provides @Singleton fun provideOkHttpClient() : OkHttpClient { return OkHttpClient() } @Provides @Singleton fun provideGson() : Gson { return Gson() } }
0
Kotlin
1
0
9b774c65c5e99e646c50370f17d97575b07ac46b
857
moodtrack-android
MIT License
app/bin/main/com/lamdapay/CryptoMandalam/domain/model/DaoProposal.kt
ankitprs
654,085,414
false
null
package com.lamdapay.CryptoMandalam.domain.model data class DaoProposal( val title: String, val daoName: String, val amountToRaise: String, val fundDescription: String, val solanaDaoAddressId: String )
0
Kotlin
0
1
f8ef823fe342aa6fab542661a598a01696e93a4b
223
CryptoMandalam
MIT License
app/bin/main/com/lamdapay/CryptoMandalam/domain/model/DaoProposal.kt
ankitprs
654,085,414
false
null
package com.lamdapay.CryptoMandalam.domain.model data class DaoProposal( val title: String, val daoName: String, val amountToRaise: String, val fundDescription: String, val solanaDaoAddressId: String )
0
Kotlin
0
1
f8ef823fe342aa6fab542661a598a01696e93a4b
223
CryptoMandalam
MIT License
samples/kofu-petclinic-jdbc/src/main/kotlin/org/springframework/samples/petclinic/vet/JdbcVetRepositoryImpl.kt
spring-projects-experimental
134,733,282
false
null
package org.springframework.samples.petclinic.vet import org.springframework.jdbc.core.JdbcTemplate import org.springframework.jdbc.core.RowMapper class JdbcVetRepositoryImpl(val jdbcTemplate: JdbcTemplate) : VetRepository { override fun findAll(): Collection<Vet> { val vets = jdbcTemplate.query("SELECT id, first_name, last_name FROM vets ORDER BY last_name,first_name") { rs, _ -> Vet( id = rs.getInt(1), firstName = rs.getString(2), lastName = rs.getString(3)) } val specialties = jdbcTemplate.query("SELECT id, name FROM specialties") { rs, _ -> Specialty( id = rs.getInt(1), name = rs.getString(2)) } return vets.map { vet -> val vetSpecialtiesIds = jdbcTemplate.query<Int>( "SELECT specialty_id FROM vet_specialties WHERE vet_id=?", RowMapper<Int> { rs, _ -> rs.getInt(1) }, vet.id) vet.copy(specialties = specialties.filter { it.id in vetSpecialtiesIds }.toSet()) } } }
39
null
139
1,673
c41806b1429dc31f75e2cb0f69ddd51a0bd8e9da
1,122
spring-fu
Apache License 2.0
app/src/main/java/com/fracta7/e_bookshelf/data/local/database/settings/SettingsEntity.kt
fracta7
532,576,663
false
{"Kotlin": 157376}
package com.fracta7.e_bookshelf.data.local.database.settings import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "settings") data class SettingsEntity( @PrimaryKey val uid: Int? = null, val darkTheme: Boolean? = true )
0
Kotlin
0
2
43e1b6fafa6fc7a55bccf83dfc3a9f4b781c77f7
257
e-bookshelf
MIT License
src/main/kotlin/com/sandrabot/sandra/managers/StatisticsManager.kt
sandrabot
121,549,855
false
{"Kotlin": 193123}
/* * Copyright 2017-2022 <NAME> and <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sandrabot.sandra.managers /** * This class keeps track of miscellaneous values and statistics. */ class StatisticsManager { // This doesn't have to be super accurate val startTime = System.currentTimeMillis() var requestCount = 0 private set var messageCount = 0 private set fun incrementRequestCount() { requestCount++ } fun incrementMessageCount() { messageCount++ } }
1
Kotlin
3
9
3bd44a1cee06eebf7e915edb3a57f35fe2b6a3d4
1,062
sandra
Apache License 2.0
src/nam/tran/command/Stereo.kt
NamTranDev
229,420,809
false
null
package nam.tran.command // Đài class Stereo constructor(val place : String){ fun on(){ System.out.println("$place stereo is on") } fun off(){ System.out.println("$place stereo is off") } fun setCD(){ System.out.println("$place stereo is set for CD input") } fun setVolumn(number : Int) { System.out.println("$place stereo volumn set to $number") } }
1
null
1
3
1222d4fadb460012819bd61841f59423eb6e8346
419
DesignPattern
Apache License 2.0
app/src/main/kotlin/jp/co/yumemi/android/code_check/core/datastore/CodeCheckAppPreferencesDatasource.kt
Ren-Toyokawa
743,060,467
false
{"Kotlin": 85898}
package jp.co.yumemi.android.code_check.core.datastore import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.longPreferencesKey import kotlinx.coroutines.flow.map import java.util.Date import javax.inject.Inject class CodeCheckAppPreferencesDatasource @Inject constructor( private val dataStore: DataStore<Preferences>, ) { companion object { private val LATEST_SEARCH_DATE = longPreferencesKey("latest_search_date") } suspend fun saveLastSearchDate(date: Date) { dataStore.edit { settings -> settings[LATEST_SEARCH_DATE] = date.time } } val lastSearchDate = dataStore.data.map { settings -> val latestSearchDateTime = settings[LATEST_SEARCH_DATE] if (latestSearchDateTime != null) { Date(latestSearchDateTime) } else { null } } }
0
Kotlin
0
0
b13163a7f18efe83f5089c63dc989e73f5f5be66
1,112
android-engineer-codecheck
Apache License 2.0
feature/customer/src/main/kotlin/com/niyaj/customer/components/CustomerRecentOrders.kt
skniyajali
644,752,474
false
{"Kotlin": 4922890, "Shell": 4104, "Batchfile": 1397, "Java": 232}
/* * Copyright 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.niyaj.customer.components import androidx.compose.animation.Crossfade import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.dp import androidx.compose.ui.util.trace import com.niyaj.common.utils.toPrettyDate import com.niyaj.common.utils.toRupee import com.niyaj.common.utils.toTime import com.niyaj.designsystem.icon.PoposIcons import com.niyaj.designsystem.theme.PoposRoomTheme import com.niyaj.designsystem.theme.SpaceMini import com.niyaj.designsystem.theme.SpaceSmall import com.niyaj.model.CustomerWiseOrder import com.niyaj.ui.components.IconWithText import com.niyaj.ui.components.ItemNotAvailableHalf import com.niyaj.ui.components.LoadingIndicatorHalf import com.niyaj.ui.components.StandardExpandable import com.niyaj.ui.components.TextWithCount import com.niyaj.ui.event.UiState import com.niyaj.ui.parameterProvider.CustomerWiseOrderPreviewParameter import com.niyaj.ui.utils.DevicePreviews @Composable internal fun CustomerRecentOrders( modifier: Modifier = Modifier, customerWiseOrders: UiState<List<CustomerWiseOrder>>, onExpanded: () -> Unit, doesExpanded: Boolean, onClickOrder: (Int) -> Unit, shape: Shape = RoundedCornerShape(4.dp), containerColor: Color = MaterialTheme.colorScheme.background, ) = trace("CustomerRecentOrders") { ElevatedCard( onClick = onExpanded, modifier = modifier .testTag("CustomerRecentOrders") .fillMaxWidth(), shape = shape, colors = CardDefaults.elevatedCardColors().copy( containerColor = containerColor, ), elevation = CardDefaults.elevatedCardElevation( defaultElevation = 2.dp, ), ) { StandardExpandable( modifier = Modifier .fillMaxWidth() .padding(SpaceSmall), expanded = doesExpanded, onExpandChanged = { onExpanded() }, title = { IconWithText( text = "Recent Orders", icon = PoposIcons.AllInbox, ) }, rowClickable = true, expand = { modifier: Modifier -> IconButton( modifier = modifier, onClick = onExpanded, ) { Icon( imageVector = PoposIcons.ArrowDown, contentDescription = "Expand More", tint = MaterialTheme.colorScheme.secondary, ) } }, content = { Crossfade( targetState = customerWiseOrders, label = "Recent Orders", ) { state -> when (state) { is UiState.Loading -> LoadingIndicatorHalf() is UiState.Empty -> { ItemNotAvailableHalf(text = "No orders made using this customer.") } is UiState.Success -> { Column { val groupedByDate = remember(state.data) { state.data.groupBy { it.updatedAt.toPrettyDate() } } groupedByDate.forEach { (date, orders) -> TextWithCount( modifier = Modifier .background(Color.Transparent), text = date, count = orders.size, ) orders.forEachIndexed { index, order -> Row( modifier = Modifier .fillMaxWidth() .clickable { onClickOrder(order.orderId) } .padding(SpaceSmall), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, ) { IconWithText( text = "${order.orderId}", icon = PoposIcons.Tag, isTitle = true, ) Text( text = order.customerAddress, textAlign = TextAlign.Start, ) Text( text = order.totalPrice.toRupee, textAlign = TextAlign.Start, fontWeight = FontWeight.SemiBold, ) Text( text = order.updatedAt.toTime, textAlign = TextAlign.End, ) } if (index != orders.size - 1) { Spacer(modifier = Modifier.height(SpaceMini)) HorizontalDivider(modifier = Modifier.fillMaxWidth()) Spacer(modifier = Modifier.height(SpaceMini)) } } } } } } } }, ) } } @DevicePreviews @Composable private fun CustomerRecentOrdersPreview( @PreviewParameter(CustomerWiseOrderPreviewParameter::class) customerWiseOrders: UiState<List<CustomerWiseOrder>>, modifier: Modifier = Modifier, ) { PoposRoomTheme { CustomerRecentOrders( modifier = modifier, customerWiseOrders = customerWiseOrders, onExpanded = {}, doesExpanded = true, onClickOrder = {}, ) } }
39
Kotlin
0
1
e6c13d3175e83ba4eac80426edf6942f46518f11
8,580
PoposRoom
Apache License 2.0
hard/kotlin/c0078_407_trapping-rain-water-ii/00_leetcode_0078.kt
drunkwater
127,843,545
false
null
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //407. Trapping Rain Water II //Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining. //Note: //Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000. //Example: //Given the following 3x6 height map: //[ // [1,4,3,1,3,2], // [3,2,1,3,2,4], // [2,3,3,2,3,1] //] //Return 4. //The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] before the rain. //After the rain, water is trapped between the blocks. The total volume of water trapped is 4. //class Solution { // fun trapRainWater(heightMap: Array<IntArray>): Int { // } //} // Time Is Money
1
null
1
1
8cc4a07763e71efbaedb523015f0c1eff2927f60
922
leetcode
Ruby License
library/src/main/java/kwasm/format/binary/instruction/MemoryInstruction.kt
jasonwyatt
226,777,898
false
null
/* * Copyright 2021 Google LLC * * 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 kwasm.format.binary.instruction import kwasm.ast.instruction.Instruction import kwasm.ast.instruction.MemArg import kwasm.ast.instruction.MemoryInstruction import kwasm.format.binary.BinaryParser import kwasm.format.binary.value.readUInt internal val MEMORY_OPCODE_RANGE = 0x28..0x40 /** * From * [the docs](https://webassembly.github.io/spec/core/binary/instructions.html#memory-instructions): * * Each variant of memory instruction is encoded with a different byte code. Loads and stores are * followed by the encoding of their `memarg` immediate. * * ``` * memarg ::= a:u32 o:u32 => {align a, offset o} * instr ::= 0x28 m:memarg => i32.load m * 0x29 m:memarg => i64.load m * 0x2A m:memarg => f32.load m * 0x2B m:memarg => f64.load m * 0x2C m:memarg => i32.load8_s m * 0x2D m:memarg => i32.load8_u m * 0x2E m:memarg => i32.load16_s m * 0x2F m:memarg => i32.load16_u m * 0x30 m:memarg => i64.load8_s m * 0x31 m:memarg => i64.load8_u m * 0x32 m:memarg => i64.load16_s m * 0x33 m:memarg => i64.load16_u m * 0x34 m:memarg => i64.load32_s m * 0x35 m:memarg => i64.load32_u m * 0x36 m:memarg => i32.store m * 0x37 m:memarg => i64.store m * 0x38 m:memarg => f32.store m * 0x39 m:memarg => f64.store m * 0x3A m:memarg => i32.store8 m * 0x3B m:memarg => i32.store16 m * 0x3C m:memarg => i64.store8 m * 0x3D m:memarg => i64.store16 m * 0x3E m:memarg => i64.store32 m * 0x3F 0x00 => memory.size * 0x40 0x00 => memory.grow * ``` * * **Note** * In future versions of WebAssembly, the additional zero bytes occurring in the encoding of the * `memory.size` and `memory.grow` instructions may be used to index additional memories. */ fun BinaryParser.readMemoryInstruction(opcode: Int): Instruction = when (opcode) { 0x3F -> { if (readByte() == 0x00.toByte()) MemoryInstruction.Size else throwException("Invalid index for memory.size", -1) } 0x40 -> { if (readByte() == 0x00.toByte()) MemoryInstruction.Grow else throwException("Invalid index for memory.grow", -1) } 0x28 -> MemoryInstruction.LoadInt.I32_LOAD.copy(arg = readMemoryArg()) 0x29 -> MemoryInstruction.LoadInt.I64_LOAD.copy(arg = readMemoryArg()) 0x2A -> MemoryInstruction.LoadFloat.F32_LOAD.copy(arg = readMemoryArg()) 0x2B -> MemoryInstruction.LoadFloat.F64_LOAD.copy(arg = readMemoryArg()) 0x2C -> MemoryInstruction.LoadInt.I32_LOAD8_S.copy(arg = readMemoryArg()) 0x2D -> MemoryInstruction.LoadInt.I32_LOAD8_U.copy(arg = readMemoryArg()) 0x2E -> MemoryInstruction.LoadInt.I32_LOAD16_S.copy(arg = readMemoryArg()) 0x2F -> MemoryInstruction.LoadInt.I32_LOAD16_U.copy(arg = readMemoryArg()) 0x30 -> MemoryInstruction.LoadInt.I64_LOAD8_S.copy(arg = readMemoryArg()) 0x31 -> MemoryInstruction.LoadInt.I64_LOAD8_U.copy(arg = readMemoryArg()) 0x32 -> MemoryInstruction.LoadInt.I64_LOAD16_S.copy(arg = readMemoryArg()) 0x33 -> MemoryInstruction.LoadInt.I64_LOAD16_U.copy(arg = readMemoryArg()) 0x34 -> MemoryInstruction.LoadInt.I64_LOAD32_S.copy(arg = readMemoryArg()) 0x35 -> MemoryInstruction.LoadInt.I64_LOAD32_U.copy(arg = readMemoryArg()) 0x36 -> MemoryInstruction.StoreInt.I32_STORE.copy(arg = readMemoryArg()) 0x37 -> MemoryInstruction.StoreInt.I64_STORE.copy(arg = readMemoryArg()) 0x38 -> MemoryInstruction.StoreFloat.F32_STORE.copy(arg = readMemoryArg()) 0x39 -> MemoryInstruction.StoreFloat.F64_STORE.copy(arg = readMemoryArg()) 0x3A -> MemoryInstruction.StoreInt.I32_STORE8.copy(arg = readMemoryArg()) 0x3B -> MemoryInstruction.StoreInt.I32_STORE16.copy(arg = readMemoryArg()) 0x3C -> MemoryInstruction.StoreInt.I64_STORE8.copy(arg = readMemoryArg()) 0x3D -> MemoryInstruction.StoreInt.I64_STORE16.copy(arg = readMemoryArg()) 0x3E -> MemoryInstruction.StoreInt.I64_STORE32.copy(arg = readMemoryArg()) else -> throwException("Invalid Memory Instruction Opcode", -1) } /** Reads a [MemArg] node from the binary stream. */ fun BinaryParser.readMemoryArg(): MemArg = MemArg(alignment = readUInt(), offset = readUInt())
4
WebAssembly
3
25
3c17988daaa8f37d654ee29428a37b330b3532ad
5,187
KWasm
Apache License 2.0
app/src/main/java/com/pingo/tmdb/app/detail/MovieDetailModule.kt
pingothedoer
195,129,975
false
{"Gradle": 3, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Proguard": 1, "Kotlin": 58, "XML": 29, "Java": 1}
package com.pingo.tmdb.app.detail import androidx.lifecycle.ViewModel import com.pingo.tmdb.shared.di.factory.ViewModelKey import com.pingo.tmdb.shared.di.scope.ActivityScope import com.pingo.tmdb.shared.di.scope.FragmentScope import dagger.Binds import dagger.Module import dagger.android.ContributesAndroidInjector import dagger.multibindings.IntoMap @Module abstract class MovieDetailModule { /** * Generates an AndroidInjector for the [MovieDetailFragment]. */ @FragmentScope @ContributesAndroidInjector internal abstract fun contributeMovieDetailFragment(): MovieDetailFragment /** * The ViewModels are created by Dagger in a map. Via the @ViewModelKey, we define that we * want to get a [MovieDetailViewModel] class. */ @Binds @IntoMap @ViewModelKey(MovieDetailViewModel::class) abstract fun bindMovieDetailViewModel(viewModel: MovieDetailViewModel): ViewModel }
0
Kotlin
0
0
de072aa6c4768612baf26014417bca2e5ea9261a
934
TheMovieCatalog
MIT License
app/src/main/java/com/project/googlemaps2020/models/User.kt
V9vek
295,136,982
false
null
package com.project.googlemaps2020.models data class User( val username: String = "", val email: String = "", val user_id: String = "", val profile_image: String = "" )
0
Kotlin
1
9
197d32f6299692d91818c150f5da97b87f3a43a5
185
Android-Chatroom
MIT License
src/main/kotlin/com/salakheev/shaderbuilderkt/builder/types/sampler/Sampler2DArray.kt
dananas
150,878,118
false
null
package com.salakheev.shaderbuilderkt.builder.types.sampler import com.salakheev.shaderbuilderkt.builder.ShaderBuilder import com.salakheev.shaderbuilderkt.builder.types.Variable import com.salakheev.shaderbuilderkt.builder.types.scalar.GLInt class Sampler2DArray(override val builder: ShaderBuilder) : Variable { override val typeName: String = "sampler2D" override var value: String? = null operator fun get(i: GLInt): Sampler2D { val result = Sampler2D(builder) result.value = "$value[${i.value}]" return result } }
0
Kotlin
6
37
7ba77ca59a1f5542314b42cf3f53f066ca442956
532
kotlin-glsl
MIT License
token-validation-core/src/main/kotlin/no/nav/security/token/support/core/configuration/ProxyAwareResourceRetriever.kt
navikt
124,397,000
false
{"Kotlin": 362723}
package no.nav.security.token.support.core.configuration import com.nimbusds.jose.util.DefaultResourceRetriever import java.io.IOException import java.net.HttpURLConnection import java.net.InetSocketAddress import java.net.Proxy import java.net.Proxy.NO_PROXY import java.net.Proxy.Type.DIRECT import java.net.Proxy.Type.HTTP import java.net.URI import java.net.URISyntaxException import java.net.URL import org.slf4j.Logger import org.slf4j.LoggerFactory open class ProxyAwareResourceRetriever(proxyUrl : URL?, private val usePlainTextForHttps : Boolean, connectTimeout : Int, readTimeout : Int, sizeLimit : Int) : DefaultResourceRetriever(connectTimeout, readTimeout, sizeLimit) { @JvmOverloads constructor(proxyUrl : URL? = null, usePlainTextForHttps : Boolean = false) : this(proxyUrl, usePlainTextForHttps, DEFAULT_HTTP_CONNECT_TIMEOUT, DEFAULT_HTTP_READ_TIMEOUT, DEFAULT_HTTP_SIZE_LIMIT) init { super.setProxy(proxyFrom(proxyUrl)) } fun urlWithPlainTextForHttps(url : URL) : URL { try { if (!url.toURI().scheme.equals("https")) { return url } val port = if (url.port > 0) url.port else 443 val newUrl = ("http://" + url.host + ":" + port + url.path + (if (url.query != null && url.query.isNotEmpty()) "?" + url.query else "")) LOG.debug("using plaintext connection for https url, new url is {}", newUrl) return URI.create(newUrl).toURL() } catch (e : URISyntaxException) { throw IOException(e) } } override fun openHTTPConnection(url : URL) : HttpURLConnection { val urlToOpen = if (usePlainTextForHttps) urlWithPlainTextForHttps(url) else url if (shouldProxy(url)) { LOG.trace("Connecting to {} via proxy {}", urlToOpen, proxy) return urlToOpen.openConnection(proxy) as HttpURLConnection } LOG.trace("Connecting to {} without proxy", urlToOpen) return urlToOpen.openConnection() as HttpURLConnection } fun shouldProxy(url : URL) = proxy.type() != DIRECT && !isNoProxy(url) private fun proxyFrom(uri : URL?) = uri?.let { Proxy(HTTP, InetSocketAddress(it.host, it.port)) } ?: NO_PROXY private fun isNoProxy(url: URL): Boolean { val noProxy = System.getenv("NO_PROXY") val isNoProxy = noProxy?.split(",") ?.any("$url"::contains) ?: false if (noProxy != null && isNoProxy) { LOG.trace("Not using proxy for {} since it is covered by the NO_PROXY setting {}", url, noProxy) } else { LOG.trace("Using proxy for {} since it is not covered by the NO_PROXY setting {}", url, noProxy) } return isNoProxy } companion object { private val LOG : Logger = LoggerFactory.getLogger(ProxyAwareResourceRetriever::class.java) const val DEFAULT_HTTP_CONNECT_TIMEOUT : Int = 21050 const val DEFAULT_HTTP_READ_TIMEOUT : Int = 30000 const val DEFAULT_HTTP_SIZE_LIMIT : Int = 50 * 1024 } }
8
Kotlin
7
15
653f53b9ab96eb8979b481051c89a889afc78bf9
3,076
token-support
MIT License
sdk/src/main/java/io/stipop/adapter/StickerDefaultAdapter.kt
stipop-development
372,351,610
false
null
package io.stipop.adapter import android.annotation.SuppressLint import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import io.stipop.models.SPSticker import io.stipop.models.Sticker import io.stipop.models.StickerPackage import io.stipop.adapter.viewholder.StickerThumbViewHolder internal class StickerDefaultAdapter( val delegate: OnStickerClickListener? = null, private val dataSet: ArrayList<SPSticker> = ArrayList() ) : RecyclerView.Adapter<StickerThumbViewHolder>() { interface OnStickerClickListener { fun onStickerClick(position: Int, spSticker: SPSticker) } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): StickerThumbViewHolder { return StickerThumbViewHolder.create(parent, delegate) } override fun onBindViewHolder(holder: StickerThumbViewHolder, position: Int) { holder.bind(dataSet[position]) } override fun getItemCount(): Int = dataSet.size @SuppressLint("NotifyDataSetChanged") fun clearData() { dataSet.clear() notifyDataSetChanged() } fun updateData(stickerPackage: StickerPackage) { val prevCount = itemCount dataSet.addAll(stickerPackage.stickers) notifyItemRangeInserted(prevCount, itemCount) } fun updateData(stickers: List<SPSticker>) { val prevCount = itemCount dataSet.addAll(stickers) notifyItemRangeInserted(prevCount, itemCount) } fun updateData(sticker: Sticker) { val prevCount = itemCount dataSet.add(sticker.toSPSticker()) notifyItemRangeInserted(prevCount, itemCount) } fun updateFavorite(updatedSticker: SPSticker): SPSticker? { var target: SPSticker? = null run loop@{ dataSet.forEachIndexed { index, spSticker -> if (spSticker.stickerId == updatedSticker.stickerId) { spSticker.favoriteYN = updatedSticker.favoriteYN dataSet[index] = spSticker notifyItemChanged(index) target = spSticker return@loop } } } return target } }
2
null
5
9
98ab3c8ebc153270d3265c9a08c884deb2126d9f
2,225
stipop-android-sdk
MIT License
map/src/test/kotlin/de/darkatra/bfme2/map/serialization/MapFileSerdeTest.kt
DarkAtra
325,887,805
false
null
package de.darkatra.bfme2.map.serialization import de.darkatra.bfme2.map.MapFile import org.apache.commons.io.IOUtils import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import java.io.InputStream @Disabled // WIP class MapFileSerdeTest { private val uncompressedMapPath = "/maps/bfme2-rotwk/Legendary War.txt" @Test fun `should calculate the correct map file size`() { val expectedMapFileSize = IOUtils.consume(getMapInputStream(uncompressedMapPath)) val map = MapFileReader().read(getMapInputStream(uncompressedMapPath)) val serializationContext = SerializationContext(true) val annotationProcessingContext = AnnotationProcessingContext(false) val serdeFactory = SerdeFactory(annotationProcessingContext, serializationContext) val mapFileSerde = serdeFactory.getSerde(MapFile::class) val actualMapFileSize = mapFileSerde.calculateByteCount(map) assertThat(actualMapFileSize).isEqualTo(expectedMapFileSize) } private fun getMapInputStream(name: String): InputStream { return MapFileReaderTest::class.java.getResourceAsStream(name)!! } }
3
Kotlin
0
2
b8c0b7dd8228753d6fcbf967a2258459a955f9c3
1,214
bfme2-modding-utils
MIT License
src/main/kotlin/com/creepersan/bingimage/lib/database/sqlite/SQLiteDatabaseOperator.kt
CreeperSan
289,059,421
false
null
package com.creepersan.bingimage.lib.database.sqlite import com.creepersan.bingimage.lib.database.bean.BingImageDatabaseBean import com.creepersan.bingimage.lib.database.factory.DatabaseOperator import com.creepersan.bingimage.lib.file.FileUtils import java.sql.Connection import java.sql.DriverManager import java.sql.ResultSet import java.util.ArrayList class SQLiteDatabaseOperator : DatabaseOperator() { init { Class.forName("org.sqlite.JDBC"); } fun getConnection(): Connection { return DriverManager.getConnection("jdbc:sqlite:${FileUtils.sqliteFolder.absolutePath}/bing_image.db") } /** * 初始化表 */ override fun initTable() { val connection = getConnection() val statement = connection.createStatement() statement.queryTimeout = 30 // 创建表 statement.executeUpdate("create table if not exists BingImage ( " + "_id int not null primary key unique , " + "year int not null , " + "month int not null , " + "day int not null , " + "copyright varchar(1024) not null , " + "author varchar(1024) not null , " + "path varchar(1024) not null , " + "title varchar(1024) not null , " + "location varchar(1024) not null , " + "json text character not null " + ")") connection.close() } /** * 插入或者更新必应壁纸 */ override fun insertOrUpdateBingImage(bingImage: BingImageDatabaseBean) { val connection = getConnection() // 更新或插入数据 val prepareStatement = connection.prepareStatement("replace into BingImage(_id, year, month, day, copyright, author, path, title, location, json) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") prepareStatement.setInt(1, bingImage._id) prepareStatement.setInt(2, bingImage.year) prepareStatement.setInt(3, bingImage.month) prepareStatement.setInt(4, bingImage.day) prepareStatement.setString(5, bingImage.copyright) prepareStatement.setString(6, bingImage.author) prepareStatement.setString(7, bingImage.path) prepareStatement.setString(8, bingImage.title) prepareStatement.setString(9, bingImage.location) prepareStatement.setString(10, bingImage.json) prepareStatement.execute() connection.close() } override fun removeBingImage(id: Int) { val connection = getConnection() // 更新或插入数据 val prepareStatement = connection.prepareStatement("delete from BingImage where _id = ?") prepareStatement.setInt(1, id) connection.close() } /** * 获取指定数量的必应图片 */ override fun getBingImage(count: Int, index: Int): List<BingImageDatabaseBean> { val connection = getConnection() val prepareStatement = connection.prepareStatement("select * from BingImage order by _id desc limit ? offset ?") prepareStatement.setInt(1, count) prepareStatement.setInt(2, index) val resultSet : ResultSet try { resultSet = prepareStatement.executeQuery() } catch (e: Exception) { return listOf() } val list = ArrayList<BingImageDatabaseBean>() while (resultSet.next()){ val bean = BingImageDatabaseBean( _id = resultSet.getInt("_id"), year = resultSet.getInt("year"), month = resultSet.getInt("month"), day = resultSet.getInt("day"), copyright = resultSet.getString("copyright"), author = resultSet.getString("author"), path = resultSet.getString("path"), title = resultSet.getString("title"), location = resultSet.getString("location"), json = resultSet.getString("json") ) list.add(bean) } connection.close() return list } /** * 返回所有图片的数量 */ override fun getBingImageCount(): Int { val connection = getConnection() val prepareStatement = connection.createStatement() val result = prepareStatement.executeQuery("select count(*) from BingImage") result.next() val row = result.getInt(1) connection.close() return row } /** * 返回随机数量的图片 */ override fun getBingImageRandom(count: Int): List<BingImageDatabaseBean> { val connection = getConnection() val prepareStatement = connection.prepareStatement("select * from BingImage order by random() limit ?") prepareStatement.setInt(1, count) val resultSet : ResultSet try { resultSet = prepareStatement.executeQuery() } catch (e: Exception) { return listOf() } val list = ArrayList<BingImageDatabaseBean>() while (resultSet.next()){ val bean = BingImageDatabaseBean( _id = resultSet.getInt("_id"), year = resultSet.getInt("year"), month = resultSet.getInt("month"), day = resultSet.getInt("day"), copyright = resultSet.getString("copyright"), author = resultSet.getString("author"), path = resultSet.getString("path"), title = resultSet.getString("title"), location = resultSet.getString("location"), json = resultSet.getString("json") ) list.add(bean) } connection.close() return list } }
0
Kotlin
0
0
ca7162477b5a041305e2830124380ae7c9dd97ad
5,743
bing-image-java
MIT License
src/main/kotlin/com/creepersan/bingimage/lib/database/sqlite/SQLiteDatabaseOperator.kt
CreeperSan
289,059,421
false
null
package com.creepersan.bingimage.lib.database.sqlite import com.creepersan.bingimage.lib.database.bean.BingImageDatabaseBean import com.creepersan.bingimage.lib.database.factory.DatabaseOperator import com.creepersan.bingimage.lib.file.FileUtils import java.sql.Connection import java.sql.DriverManager import java.sql.ResultSet import java.util.ArrayList class SQLiteDatabaseOperator : DatabaseOperator() { init { Class.forName("org.sqlite.JDBC"); } fun getConnection(): Connection { return DriverManager.getConnection("jdbc:sqlite:${FileUtils.sqliteFolder.absolutePath}/bing_image.db") } /** * 初始化表 */ override fun initTable() { val connection = getConnection() val statement = connection.createStatement() statement.queryTimeout = 30 // 创建表 statement.executeUpdate("create table if not exists BingImage ( " + "_id int not null primary key unique , " + "year int not null , " + "month int not null , " + "day int not null , " + "copyright varchar(1024) not null , " + "author varchar(1024) not null , " + "path varchar(1024) not null , " + "title varchar(1024) not null , " + "location varchar(1024) not null , " + "json text character not null " + ")") connection.close() } /** * 插入或者更新必应壁纸 */ override fun insertOrUpdateBingImage(bingImage: BingImageDatabaseBean) { val connection = getConnection() // 更新或插入数据 val prepareStatement = connection.prepareStatement("replace into BingImage(_id, year, month, day, copyright, author, path, title, location, json) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") prepareStatement.setInt(1, bingImage._id) prepareStatement.setInt(2, bingImage.year) prepareStatement.setInt(3, bingImage.month) prepareStatement.setInt(4, bingImage.day) prepareStatement.setString(5, bingImage.copyright) prepareStatement.setString(6, bingImage.author) prepareStatement.setString(7, bingImage.path) prepareStatement.setString(8, bingImage.title) prepareStatement.setString(9, bingImage.location) prepareStatement.setString(10, bingImage.json) prepareStatement.execute() connection.close() } override fun removeBingImage(id: Int) { val connection = getConnection() // 更新或插入数据 val prepareStatement = connection.prepareStatement("delete from BingImage where _id = ?") prepareStatement.setInt(1, id) connection.close() } /** * 获取指定数量的必应图片 */ override fun getBingImage(count: Int, index: Int): List<BingImageDatabaseBean> { val connection = getConnection() val prepareStatement = connection.prepareStatement("select * from BingImage order by _id desc limit ? offset ?") prepareStatement.setInt(1, count) prepareStatement.setInt(2, index) val resultSet : ResultSet try { resultSet = prepareStatement.executeQuery() } catch (e: Exception) { return listOf() } val list = ArrayList<BingImageDatabaseBean>() while (resultSet.next()){ val bean = BingImageDatabaseBean( _id = resultSet.getInt("_id"), year = resultSet.getInt("year"), month = resultSet.getInt("month"), day = resultSet.getInt("day"), copyright = resultSet.getString("copyright"), author = resultSet.getString("author"), path = resultSet.getString("path"), title = resultSet.getString("title"), location = resultSet.getString("location"), json = resultSet.getString("json") ) list.add(bean) } connection.close() return list } /** * 返回所有图片的数量 */ override fun getBingImageCount(): Int { val connection = getConnection() val prepareStatement = connection.createStatement() val result = prepareStatement.executeQuery("select count(*) from BingImage") result.next() val row = result.getInt(1) connection.close() return row } /** * 返回随机数量的图片 */ override fun getBingImageRandom(count: Int): List<BingImageDatabaseBean> { val connection = getConnection() val prepareStatement = connection.prepareStatement("select * from BingImage order by random() limit ?") prepareStatement.setInt(1, count) val resultSet : ResultSet try { resultSet = prepareStatement.executeQuery() } catch (e: Exception) { return listOf() } val list = ArrayList<BingImageDatabaseBean>() while (resultSet.next()){ val bean = BingImageDatabaseBean( _id = resultSet.getInt("_id"), year = resultSet.getInt("year"), month = resultSet.getInt("month"), day = resultSet.getInt("day"), copyright = resultSet.getString("copyright"), author = resultSet.getString("author"), path = resultSet.getString("path"), title = resultSet.getString("title"), location = resultSet.getString("location"), json = resultSet.getString("json") ) list.add(bean) } connection.close() return list } }
0
Kotlin
0
0
ca7162477b5a041305e2830124380ae7c9dd97ad
5,743
bing-image-java
MIT License
common/src/commonMain/kotlin/com.chrynan.video.common/repository/source/SearchItemRepositorySource.kt
chRyNaN
174,161,260
false
null
package com.chrynan.video.common.repository.source import com.chrynan.inject.Inject import com.chrynan.video.common.repository.SearchItemRepository class SearchItemRepositorySource @Inject constructor() : SearchItemRepository
0
Kotlin
0
8
63456dcfdd57dbee9ff02b2155b7e1ec5761db81
231
Video
Apache License 2.0
app/src/main/java/fi/kroon/vadret/di/modules/ContextModule.kt
marvinmosa
241,497,201
true
{"Kotlin": 871560}
package fi.kroon.vadret.di.modules import android.app.Application import android.content.Context import dagger.Module import dagger.Provides import fi.kroon.vadret.di.scope.CoreApplicationScope @Module class ContextModule(private val application: Application) { @Provides @CoreApplicationScope fun provideContext(): Context = application }
0
null
0
0
f8149920c34bb3bc5e3148785ce217e37e596fbe
354
android
Apache License 2.0
ktor-utils/src/io/ktor/util/Path.kt
Ekito
112,228,070
false
null
package io.ktor.util import java.io.* import java.nio.file.* /** * Finds an extension of the given Path * * Extension is a substring of a [Path.fileName] after last dot */ val Path.extension get() = fileName.toString().substringAfterLast(".") fun File.combineSafe(relativePath: String): File = combineSafe(Paths.get(relativePath)) fun File.combineSafe(relativePath: Path): File { val normalized = relativePath.normalizeAndRelativize() if (normalized.startsWith("..")) { throw InvalidPathException(relativePath.toString(), "Bad relative path") } return File(this, normalized.toString()) } fun Path.combineSafe(relativePath: Path): File { val normalized = relativePath.normalizeAndRelativize() if (normalized.startsWith("..")) { throw InvalidPathException(relativePath.toString(), "Bad relative path") } return resolve(normalized).toFile() } fun Path.normalizeAndRelativize(): Path = root?.relativize(this)?.normalize() ?: normalize()
0
null
0
1
6b0fadcc30d3942a9d0ae8f2758c267ab557f8d5
992
ktor
Apache License 2.0
app/src/main/java/com/omongole/fred/composenewsapp/utils/CoreUtility.kt
EngFred
719,675,736
false
{"Kotlin": 64656}
package com.omongole.fred.composenewsapp.utils import android.content.Context import android.content.Context.CONNECTIVITY_SERVICE import android.net.ConnectivityManager import android.net.NetworkCapabilities.TRANSPORT_CELLULAR import android.net.NetworkCapabilities.TRANSPORT_ETHERNET import android.net.NetworkCapabilities.TRANSPORT_WIFI object CoreUtility { fun isInternetConnected( context: Context ) : Boolean { val connectivityManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager val networkCapabilities = connectivityManager.activeNetwork ?: return false val actNw = connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false val result = when { actNw.hasTransport(TRANSPORT_WIFI) -> true actNw.hasTransport(TRANSPORT_CELLULAR) -> true actNw.hasTransport(TRANSPORT_ETHERNET) -> true else -> false } return result } }
0
Kotlin
0
0
06ca742f45b09936245463ad6a06b97235865e72
979
News-Flash
MIT License
app/src/main/java/ir/apptune/antispam/room/RoomDAO.kt
SirLordPouya
241,154,265
false
null
package ir.apptune.antispam.room import androidx.room.Dao import androidx.room.Query /** * The Data Access Object for Room * */ @Dao interface RoomDAO { @Query("SELECT area FROM phone_location WHERE _id = :number") suspend fun getAddress(number: String): String? }
0
Kotlin
1
9
fb620efe5ac319057f854ca91e810887d295feb6
278
AntiSpam
Apache License 2.0
composeApp/src/commonMain/kotlin/ui/screen/module/CourseSystem.kt
Awning-Studio
789,984,492
false
{"Kotlin": 389676, "Swift": 594}
package ui.screen.module import afterglow.composeapp.generated.resources.select import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.width import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Info import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import edu.system.course.Course import edu.system.course.Sort import store.DataStore import store.rememberRemote import ui.component.Icon import ui.component.LazyList import ui.component.NullableContent import ui.component.RouteTopAppBar import ui.component.Scaffold import ui.component.TabPager import ui.component.TextDialog import ui.navigation.Route import ui.stringResource import ui.theme.Dimension @OptIn(ExperimentalFoundationApi::class) @Composable private fun SharedCourseSystem() { val courseSystem = with(DataStore) { rememberRemote(eduSystem) { eduSystem?.enterCourseSystem() } } val pagerState = rememberPagerState { Sort.list.size } var textDialogVisible by remember { mutableStateOf(false) } val basic = remember { mutableStateListOf<Course>() } val optional = remember { mutableStateListOf<Course>() } val general = remember { mutableStateListOf<Course>() } val crossYear = remember { mutableStateListOf<Course>() } val crossMajor = remember { mutableStateListOf<Course>() } val major = remember { mutableStateListOf<Course>() } Scaffold( topBar = { RouteTopAppBar( Route.CourseSystem, actions = { IconButton(onClick = { textDialogVisible = true }) { Icon(Icons.Outlined.Info) } } ) } ) { TabPager( tabs = Sort.list, pagerState = pagerState, tabScrollable = true, tabContent = { Text(stringResource { it.name }) } ) { NullableContent(courseSystem == null) { when (Sort.list[it]) { Sort.Basic -> CourseList(basic) Sort.Optional -> CourseList(optional) Sort.General -> CourseList(general) Sort.CrossYear -> CourseList(crossYear) Sort.CrossMajor -> CourseList(crossMajor) Sort.Major -> CourseList(major) } } } } TextDialog( textDialogVisible, text = courseSystem?.run { "$name\n$startTime - $endTime" }, onDismiss = { textDialogVisible = false } ) } @Composable fun MobileCourseSystem() { SharedCourseSystem() } @Composable fun DesktopCourseSystem() { SharedCourseSystem() } @Composable fun CourseList(list: List<Course>) { LazyList(list) { _, item -> Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { Column(modifier = Modifier.weight(1f)) { Text(item.name) } Spacer(Modifier.width(Dimension.padding_2)) TextButton( onClick = {} ) { Text(stringResource { res.select }) } } } }
0
Kotlin
0
0
d0b01f346fbeaf45b13460511a52357d79d7187d
3,902
Afterglow-Multiplatform
Apache License 2.0
app/src/main/java/io/github/zwieback/familyfinance/business/operation/fragment/TransferOperationFragment.kt
zwieback
111,666,879
false
null
package io.github.zwieback.familyfinance.business.operation.fragment import io.github.zwieback.familyfinance.business.operation.adapter.TransferOperationAdapter import io.github.zwieback.familyfinance.business.operation.filter.TransferOperationFilter import io.github.zwieback.familyfinance.business.operation.filter.TransferOperationFilter.Companion.TRANSFER_OPERATION_FILTER class TransferOperationFragment : OperationFragment<TransferOperationFilter>() { override val filterName: String get() = TRANSFER_OPERATION_FILTER override fun createEntityAdapter(): TransferOperationAdapter { val filter = extractFilter() return TransferOperationAdapter(requireContext(), clickListener, data, filter) } companion object { fun newInstance(filter: TransferOperationFilter) = TransferOperationFragment().apply { arguments = createArguments(TRANSFER_OPERATION_FILTER, filter) } } }
0
Kotlin
0
0
a640c6ce73ca195f2ee5e41ed71fbf6169d9bb3e
949
FamilyFinance
Apache License 2.0
backend/core/src/main/kotlin/de/trzpiot/example/core/port/driven/GetUserListWithFollowStatusPort.kt
czarnecki
198,445,064
false
{"Text": 1, "Markdown": 3, "YAML": 1, "Ignore List": 2, "Gradle": 3, "INI": 4, "Java Properties": 1, "XML": 12, "Java": 3, "Dart": 20, "OpenStep Property List": 2, "Objective-C": 3, "JSON": 2, "Gradle Kotlin DSL": 7, "Shell": 1, "Batchfile": 1, "Kotlin": 65, "GraphQL": 1}
package de.trzpiot.example.core.port.driven import de.trzpiot.example.core.domain.AuthenticatedUser import de.trzpiot.example.core.domain.UserListItem interface GetUserListWithFollowStatusPort { fun getUserListWithFollowStatus(user: AuthenticatedUser): List<UserListItem> }
0
Kotlin
0
0
ce5f365bbe9235692ac0dc96aef97d5592c08609
279
full-stack-example
MIT License
app/src/main/java/com/dinhlam/sharebox/view/ShareBoxShareItemBottomActionView.kt
dinhlamvn
532,200,939
false
null
package com.dinhlam.sharebox.view import android.content.Context import android.util.AttributeSet import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.constraintlayout.widget.ConstraintLayout import com.dinhlam.sharebox.R import com.dinhlam.sharebox.databinding.ViewShareItemBottomActionBinding import com.dinhlam.sharebox.extensions.setDrawableCompat import com.dinhlam.sharebox.imageloader.ImageLoader class ShareBoxShareItemBottomActionView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : ConstraintLayout(context, attrs, defStyle) { private val binding: ViewShareItemBottomActionBinding = inflate(context, R.layout.view_share_item_bottom_action, this).run { ViewShareItemBottomActionBinding.bind(this) } fun setVoteIcon(@DrawableRes icon: Int) { binding.textVote.setDrawableCompat(start = icon) } fun setCommentIcon(@DrawableRes icon: Int) { binding.textComment.setDrawableCompat(start = icon) } fun setShareIcon(@DrawableRes icon: Int) { ImageLoader.instance.load(context, icon, binding.buttonShare) } fun setBookmarkIcon(@DrawableRes icon: Int) { ImageLoader.instance.load(context, icon, binding.buttonBookmark) } fun setVoteTextColor(@ColorInt color: Int) { binding.textVote.setTextColor(color) } fun setCommentTextColor(@ColorInt color: Int) { binding.textComment.setTextColor(color) } fun setOnLikeClickListener(listener: OnClickListener?) { binding.buttonVote.setOnClickListener(listener) } fun setOnCommentClickListener(listener: OnClickListener?) { binding.buttonComment.setOnClickListener(listener) } fun setOnShareClickListener(listener: OnClickListener?) { binding.buttonShare.setOnClickListener(listener) } fun setOnBookmarkClickListener(listener: OnClickListener?) { binding.buttonBookmark.setOnClickListener(listener) } fun setVoteNumber(number: Int) { binding.textVote.text = resources.getString(R.string.up_vote, number) } fun setCommentNumber(number: Int) { binding.textComment.text = resources.getString(R.string.comment, number) } fun release() { binding.textComment.text = null binding.textVote.text = null } }
0
Kotlin
0
0
20e11187f2ca4ba5dc89102d030251358cd2aa40
2,388
sharebox
MIT License
arms/src/main/java/com/jess/arms/utils/LogUtils.kt
petma
192,675,016
true
{"Kotlin": 331292}
/* * Copyright 2017 JessYan * * 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.jess.arms.utils import android.text.TextUtils import android.util.Log /** * ================================================ * 日志工具类 * * * Created by JessYan on 2015/11/23. * [Contact me](mailto:<EMAIL>) * [Follow me](https://github.com/JessYanCoding) * ================================================ */ class LogUtils private constructor() { init { throw IllegalStateException("you can't instantiate me!") } companion object { private val DEFAULT_TAG = "MVPArms" var isLog = true fun debugInfo(tag: String, msg: String) { if (!isLog || TextUtils.isEmpty(msg)) return Log.d(tag, msg) } fun debugInfo(msg: String) { debugInfo(DEFAULT_TAG, msg) } fun warnInfo(tag: String, msg: String) { if (!isLog || TextUtils.isEmpty(msg)) return Log.w(tag, msg) } fun warnInfo(msg: String) { warnInfo(DEFAULT_TAG, msg) } /** * 这里使用自己分节的方式来输出足够长度的 message * * @param tag 标签 * @param msg 日志内容 */ fun debugLongInfo(tag: String, msg: String) { var msg = msg if (!isLog || TextUtils.isEmpty(msg)) return msg = msg.trim { it <= ' ' } var index = 0 val maxLength = 3500 var sub: String while (index < msg.length) { if (msg.length <= index + maxLength) { sub = msg.substring(index) } else { sub = msg.substring(index, index + maxLength) } index += maxLength Log.d(tag, sub.trim { it <= ' ' }) } } fun debugLongInfo(msg: String) { debugLongInfo(DEFAULT_TAG, msg) } } }
0
Kotlin
0
0
64ac1d9e092ef637f67b57a7effac7e0a6d029f9
2,462
MVPArms
Apache License 2.0
fragment/src/main/java/com/angcyo/activity/BaseAppCompatActivity.kt
angcyo
229,037,615
false
null
package com.angcyo.activity import android.app.Activity import android.content.Intent import android.content.res.Configuration import android.os.Binder import android.os.Bundle import android.os.Process import android.view.KeyEvent import android.view.MotionEvent import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import com.angcyo.DslAHelper import com.angcyo.base.* import com.angcyo.dslTargetIntentHandle import com.angcyo.fragment.R import com.angcyo.library.L import com.angcyo.library.Screen import com.angcyo.library.ex.isDebug import com.angcyo.library.ex.simpleHash import com.angcyo.library.utils.resultString import com.angcyo.widget.DslViewHolder /** * [Activity] 基类 * Email:[email protected] * @author angcyo * @date 2019/12/19 * Copyright (c) 2019 ShenZhen O&M Cloud Co., Ltd. All rights reserved. */ abstract class BaseAppCompatActivity : AppCompatActivity() { lateinit var baseDslViewHolder: DslViewHolder /**别名*/ val _vh: DslViewHolder get() = baseDslViewHolder /**布局*/ var activityLayoutId = R.layout.lib_activity_main_layout //<editor-fold desc="基础方法处理"> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) logActivityInfo() baseDslViewHolder = DslViewHolder(window.decorView) onCreateAfter(savedInstanceState) intent?.let { onHandleIntent(it) } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) setIntent(intent) intent?.let { onHandleIntent(it, true) } } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) onShowDebugInfoView(hasFocus) } override fun onStart() { super.onStart() } override fun onStop() { super.onStop() } override fun onPause() { super.onPause() } override fun onResume() { super.onResume() /*val config = resources.configuration val appConfig = app().resources.configuration L.w("config↓\nact:$config\napp:$appConfig")*/ Screen.init(this) } override fun onPostResume() { super.onPostResume() Screen.init(this) } override fun onConfigurationChanged(newConfig: Configuration) { val oldConfig = resources.configuration super.onConfigurationChanged(newConfig) L.w("onConfigurationChanged↓\nold:$oldConfig\nnew:$newConfig") if (isDebug()) { onShowDebugInfoView() } Screen.init(this) } open fun onShowDebugInfoView(show: Boolean = true) { showDebugInfoView(show) } /**布局设置之后触发*/ open fun onCreateAfter(savedInstanceState: Bundle?) { enableLayoutFullScreen() with(activityLayoutId) { if (this > 0) { setContentView(this) } } } /** * @param fromNew [onNewIntent] * */ open fun onHandleIntent(intent: Intent, fromNew: Boolean = false) { handleTargetIntent(intent) if (L.debug) { // val am: ActivityManager = // getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager // // val appTasks = am.appTasks // val runningTasks = am.getRunningTasks(Int.MAX_VALUE) L.i( "${this.simpleHash()} new:$fromNew $intent pid:${Process.myPid()} uid:${Process.myUid()} call:${ packageManager.getNameForUid( Binder.getCallingUid() ) }" ) } } /**检查是否有目标[Intent]需要启动*/ open fun handleTargetIntent(intent: Intent) { dslTargetIntentHandle(intent) } //</editor-fold desc="基础方法处理"> //<editor-fold desc="事件拦截"> override fun onTouchEvent(event: MotionEvent?): Boolean { return super.onTouchEvent(event) } /**拦截界面所有Touch事件*/ var interceptTouchEvent: Boolean = false override fun dispatchTouchEvent(ev: MotionEvent): Boolean { if (ev.actionMasked == MotionEvent.ACTION_CANCEL) { interceptTouchEvent = false } if (interceptTouchEvent) { return true } //L.d("${ev.actionIndex} ${ev.action.actionToString()} ${ev.rawX},${ev.rawY} ${ev.eventTime}") return super.dispatchTouchEvent(ev) } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { L.d("onKeyDown:$keyCode ${KeyEvent.keyCodeToString(keyCode)}") return super.onKeyDown(keyCode, event) } //</editor-fold desc="事件拦截"> //<editor-fold desc="默认回调"> /**回退检查*/ override fun onBackPressed() { if (checkBackPressedDispatcher()) { dslFHelper { if (back()) { onBackPressedInner() } } } } /**整整的关闭界面*/ open fun onBackPressedInner() { if (DslAHelper.isMainActivity(this)) { super.onBackPressed() } else { dslAHelper { //finishToActivity finish() } } } /**系统默认的[onActivityResult]触发, 需要在[Fragment]里面调用特用方法启动[Activity]才会触发*/ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) L.d( this.simpleHash(), " requestCode:$requestCode", " resultCode:${resultCode.resultString()}", " data$data" ) supportFragmentManager.getAllValidityFragment().lastOrNull()?.run { onActivityResult(requestCode, resultCode, data) } } //</editor-fold desc="默认回调"> //<editor-fold desc="高级扩展"> /**快速观察[LiveData]*/ fun <T> LiveData<T>.observe( autoClear: Boolean = false, action: (data: T?) -> Unit ): Observer<T> { val result: Observer<T> observe(this@BaseAppCompatActivity, Observer<T> { action(it) if (it != null && autoClear && this is MutableLiveData) { postValue(null) } }.apply { result = this }) return result } /**快速观察[LiveData]一次, 确保不收到null数据*/ fun <T> LiveData<T>.observeOnce(action: (data: T?) -> Unit): Observer<T> { var result: Observer<T>? = null observe(this@BaseAppCompatActivity, Observer<T> { if (it is List<*>) { if (it.isNotEmpty()) { removeObserver(result!!) } } else if (it != null) { removeObserver(result!!) } action(it) }.apply { result = this }) return result!! } //</editor-fold> }
0
Kotlin
4
1
d36e194a268a40c63c23c6a3088661a4fd0e02aa
6,912
UICore
MIT License
app/src/main/java/dev/swapi/client/infrastructure/ResponseExt.kt
FlxB2
707,994,622
false
{"Kotlin": 52364, "Java": 176}
package dev.swapi.client.infrastructure import retrofit2.Response
0
Kotlin
0
0
417bb473f63bd76407105b99e53b1632f6d1bcfd
68
AndroidStarWarsSample
Apache License 2.0
nugu-core/src/main/java/com/skt/nugu/sdk/core/utils/DequeSingleThreadExecutor.kt
jhbang2042002
273,185,841
true
{"Gradle": 9, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 1, "Kotlin": 249, "Proguard": 5, "Java": 5, "XML": 57, "JSON": 11, "Protocol Buffer": 3}
/** * Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.skt.nugu.sdk.core.utils import java.util.Comparator import java.util.concurrent.Future import java.util.concurrent.PriorityBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit private fun getRunnablePriority(runnable: Runnable): Int { return if (runnable is PriorityRunnable) { runnable.getPriority() } else { 0 } } private interface PriorityRunnable : Runnable { fun getPriority(): Int } class DequeSingleThreadExecutor : ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, PriorityBlockingQueue(11, object : Comparator<Runnable> { override fun compare(o1: Runnable, o2: Runnable): Int = getRunnablePriority(o1) - getRunnablePriority(o2) }) ) { fun submitFirst(runnable: () -> Unit): Future<*> { return submit(object: PriorityRunnable { override fun getPriority(): Int = 100 override fun run() { runnable.invoke() } }) } }
0
null
10
0
270766578338c6c5ab95863207f8bff1fbeab230
1,643
nugu-android
Apache License 2.0
shared/src/commonMain/kotlin/com/martianlab/recipes/entities/Category.kt
topinambur
322,031,089
false
null
package com.martianlab.recipes.entities import kotlinx.serialization.Serializable @Serializable data class Category( var id : Long = 0, val title : String, val imageUrl : String?, val sort : Int, val total : Int )
1
null
1
6
515e7d3324290dc51075c780ed43c16064c6f8ad
236
Recipes-Flutter-KMM
Apache License 2.0
kotest-core/src/commonMain/kotlin/io/kotest/core/spec/style/FreeSpecDsl.kt
ilaborie
247,462,184
true
{"Kotlin": 2220570, "HTML": 423, "Java": 153}
package io.kotest.core.spec.style import io.kotest.core.Tag import io.kotest.core.extensions.TestCaseExtension import io.kotest.core.spec.SpecDsl import io.kotest.core.test.TestContext import io.kotest.core.test.TestType import io.kotest.core.test.deriveTestConfig import kotlin.time.Duration import kotlin.time.ExperimentalTime interface FreeSpecDsl : SpecDsl { infix operator fun String.minus(test: suspend FreeSpecScope.() -> Unit) = addTest(this, { FreeSpecScope(this, this@FreeSpecDsl).test() }, defaultConfig(), TestType.Container) infix operator fun String.invoke(test: suspend TestContext.() -> Unit) = addTest(this, test, defaultConfig(), TestType.Test) @UseExperimental(ExperimentalTime::class) fun String.config( enabled: Boolean? = null, timeout: Duration? = null, tags: Set<Tag>? = null, extensions: List<TestCaseExtension>? = null, test: suspend TestContext.() -> Unit ) { val config = defaultConfig().deriveTestConfig(enabled, tags, extensions, timeout) addTest(this, test, config, TestType.Test) } } class FreeSpecScope(val context: TestContext, private val dsl: FreeSpecDsl) { suspend infix operator fun String.minus(test: suspend FreeSpecScope.() -> Unit) = context.registerTestCase(this, { FreeSpecScope(this, dsl).test() }, dsl.defaultConfig(), TestType.Container) suspend infix operator fun String.invoke(test: suspend TestContext.() -> Unit) = context.registerTestCase(this, test, dsl.defaultConfig(), TestType.Test) @UseExperimental(ExperimentalTime::class) suspend fun String.config( enabled: Boolean? = null, timeout: Duration? = null, tags: Set<Tag>? = null, extensions: List<TestCaseExtension>? = null, test: suspend FreeSpecScope.() -> Unit ) { val config = dsl.defaultConfig().deriveTestConfig(enabled, tags, extensions, timeout) context.registerTestCase(this, { FreeSpecScope(this, dsl).test() }, config, TestType.Test) } }
1
Kotlin
0
0
f14814a8d8d3ade611b8b004219ba6b3dd9cf979
2,007
kotlintest
Apache License 2.0
commands/src/main/kotlin/dev/gianmarcodavid/telegram/holiday/Holiday.kt
gpunto
775,683,245
false
{"Kotlin": 37951}
package dev.gianmarcodavid.telegram.holiday import java.time.LocalDate data class Holiday( val date: LocalDate, val name: String, val global: Boolean, val counties: List<String> )
4
Kotlin
0
0
c9761b858bca8f9e2d738321e785f213837e66a9
198
utility-bot
Apache License 2.0
app/src/main/java/io/ubyte/tldr/search/Search.kt
bentarve
446,247,450
false
{"Kotlin": 48173}
package io.ubyte.tldr.search import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.LocalTextStyle import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Clear import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp import io.ubyte.tldr.R import io.ubyte.tldr.compose.Pages import io.ubyte.tldr.compose.Toolbar @Composable fun Search( viewModel: SearchViewModel, openPageDetails: (Long) -> Unit ) { Column(Modifier.padding(horizontal = 8.dp)) { Toolbar { SearchField(viewModel) } when (val uiState = viewModel.uiState.collectAsState().value) { is SearchViewState.NoResult -> { Text(text = stringResource(R.string.no_result)) } is SearchViewState.SearchResult -> { Pages( modifier = Modifier.padding(horizontal = 8.dp), pages = uiState.pages, openPageDetails = openPageDetails ) } } } } @Composable private fun SearchField(viewModel: SearchViewModel) { val focusRequester = remember { FocusRequester() } var textFieldValue by rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue()) } Row(verticalAlignment = Alignment.CenterVertically) { BasicTextField( value = textFieldValue, onValueChange = { textFieldValue = it }, modifier = Modifier .fillMaxWidth() .weight(1f) .focusRequester(focusRequester), textStyle = LocalTextStyle.current.copy(MaterialTheme.colors.onBackground), cursorBrush = SolidColor(Color.Red), singleLine = true, decorationBox = { innerTextField -> Box { if (textFieldValue.text.isEmpty()) Text(stringResource(R.string.search_field)) innerTextField() } } ) ClearTextButton(textFieldValue.text) { textFieldValue = TextFieldValue() } } LaunchedEffect(Unit) { focusRequester.requestFocus() } LaunchedEffect(textFieldValue) { viewModel.querySearch(textFieldValue.text) } } @Composable private fun ClearTextButton(text: String, onClick: () -> Unit) { if (text.isNotEmpty()) { IconButton(onClick = { onClick() }) { Icon( imageVector = Icons.Rounded.Clear, contentDescription = stringResource(R.string.clear) ) } } }
0
Kotlin
0
1
eff6f017567f4649c35cd883a42fa9b9acdb3b0f
3,702
tldr
Apache License 2.0
app-backend/src/main/kotlin/Application.kt
Heapy
40,936,978
false
{"Kotlin": 3311624, "TypeScript": 19032, "Less": 5146, "HTML": 4493, "JavaScript": 2299, "CSS": 2174, "Dockerfile": 243}
@file:JvmName("Application") import di.bean import usecases.github.GithubModule import usecases.kug.KugModule import usecases.links.LinksModule import usecases.ping.PingModule import usecases.signup.JwtModule import usecases.signup.LoginModule import usecases.signup.RegisterModule import utils.close import utils.logger import java.lang.management.ManagementFactory import java.lang.management.RuntimeMXBean import kotlin.time.Duration.Companion.milliseconds suspend fun main() { ApplicationFactory().use { it.run() } } open class ApplicationFactory : AutoCloseable { open val httpClientModule by lazy { HttpClientModule() } open val yamlModule by lazy { YamlModule() } open val configModule by lazy { ConfigModule() } open val jdbcModule by lazy { JdbcModule( configModule = configModule, ) } open val lifecycleModule by lazy { LifecycleModule() } open val jwtModule by lazy { JwtModule( configModule = configModule, ) } open val jooqModule by lazy { JooqModule( jdbcModule = jdbcModule, ) } open val flywayModule by lazy { FlywayModule( jdbcModule = jdbcModule, ) } open val loginModule by lazy { LoginModule( jooqModule = jooqModule, jwtModule = jwtModule, ) } open val registerModule by lazy { RegisterModule( jooqModule = jooqModule, ) } open val kugModule by lazy { KugModule( httpClientModule = httpClientModule, yamlModule = yamlModule, jooqModule = jooqModule, ) } open val githubModule by lazy { GithubModule( configModule = configModule, httpClientModule = httpClientModule, ) } open val pingModule by lazy { PingModule() } open val linksModule by lazy { LinksModule() } open val metricsModule by lazy { MetricsModule() } open val serverModule by lazy { ServerModule( githubModule = githubModule, pingModule = pingModule, loginModule = loginModule, registerModule = registerModule, linksModule = linksModule, kugModule = kugModule, jwtModule = jwtModule, metricsModule = metricsModule, lifecycleModule = lifecycleModule, configModule = configModule, ) } open suspend fun run() { val gracefulShutdown = lifecycleModule.gracefulShutdown.get lifecycleModule.shutdownHandler.get.registerHook() flywayModule.flyway.get.migrate() serverModule.ktorServer.get.start(wait = false) log.get.info("Server started in {}", runtimeMXBean.get.uptime.milliseconds) gracefulShutdown.waitForShutdown() } open val runtimeMXBean by bean<RuntimeMXBean> { ManagementFactory.getRuntimeMXBean() } open val log by bean { logger<ApplicationFactory>() } override fun close() { jdbcModule.close {} httpClientModule.close {} } }
21
Kotlin
1220
11,018
2f4cfa75180e759d91fe238cc3f638beec9286e2
3,253
awesome-kotlin
Apache License 2.0
app/src/main/java/com/example/quitter/Badge.kt
Johnricharde
799,963,883
false
{"Kotlin": 30384}
package com.example.quitter data class Badge( val id: Int, val title: String, val milestoneMillis: Long )
0
Kotlin
0
0
40ceead662e9bb9e7d3b6a1643828b6f84995e08
119
Quitter
The Unlicense
src/main/kotlin/org/semonte/intellij/swagger/traversal/path/swagger/ParameterDefinitionsInRootPathResolver.kt
semonte
692,733,249
false
{"Kotlin": 511953, "Java": 219922, "HTML": 5081}
package org.semonte.intellij.swagger.traversal.path.swagger import com.intellij.psi.PsiElement class ParameterDefinitionsInRootPathResolver : PathResolver { override fun childOfParameterDefinition(psiElement: PsiElement): Boolean { return hasPath(psiElement, "$.*") } override fun isParameter(psiElement: PsiElement): Boolean { return hasPath(psiElement, "$") } }
0
Kotlin
0
0
52f4741b177b1fbc71c4fe8e5d00ef2d572d2154
400
openapi-plugin
MIT License
src/main/kotlin/com/github/lucasls/jooqkotlin/StringFields.kt
lucasls
272,223,406
false
null
package com.github.lucasls.jooqkotlin import org.jooq.Condition import org.jooq.Field // TODO add Javadoc and tests infix fun Field<String>.equalIgnoreCase(value: String): Condition = this.equalIgnoreCase(value) infix fun Field<String>.equalIgnoreCase(value: Field<String>): Condition = this.equalIgnoreCase(value) fun Field<String>.equal(value: String, ignoreCase: Boolean = false): Condition = if (ignoreCase) equalIgnoreCase(value) else equal(value) fun Field<String>.equal(value: Field<String>, ignoreCase: Boolean = false): Condition = if (ignoreCase) equalIgnoreCase(value) else equal(value) fun Field<String>.eq(value: String, ignoreCase: Boolean = false): Condition = if (ignoreCase) equalIgnoreCase(value) else equal(value) fun Field<String>.eq(value: Field<String>, ignoreCase: Boolean = false): Condition = if (ignoreCase) equalIgnoreCase(value) else equal(value) fun Field<String>.notEqual(value: String, ignoreCase: Boolean = false): Condition = if (ignoreCase) notEqualIgnoreCase(value) else notEqual(value) fun Field<String>.notEqual(value: Field<String>, ignoreCase: Boolean = false): Condition = if (ignoreCase) notEqualIgnoreCase(value) else notEqual(value) fun Field<String>.ne(value: String, ignoreCase: Boolean = false): Condition = if (ignoreCase) notEqualIgnoreCase(value) else notEqual(value) fun Field<String>.ne(value: Field<String>, ignoreCase: Boolean = false): Condition = if (ignoreCase) notEqualIgnoreCase(value) else notEqual(value)
2
Kotlin
0
0
fe2a0446ce83760819b94917434ab0db5bbf3d0a
1,507
jooq-kotlin
Apache License 2.0
features/dd-sdk-android-session-replay/src/main/kotlin/com/datadog/android/sessionreplay/utils/ViewBoundsResolver.kt
DataDog
219,536,756
false
{"Kotlin": 7825445, "Java": 236752, "C": 79303, "Shell": 63027, "C++": 32351, "Python": 5556, "CMake": 2000}
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.sessionreplay.utils import android.view.View /** * A utility interface to extract a [View]'s bounds relative to the device's screen, and scaled according to * the screen's density. * This interface is meant for internal usage, please use it carefully. */ fun interface ViewBoundsResolver { /** * Resolves the View bounds in device space, and normalizes them based on the screen density. * These dimensions are then normalized according with the current device screen density. * Example: if a device has a DPI = 2, the value of the dimension or position is divided by * 2 to get a normalized value. * @param view the [View] * @param pixelsDensity the current device screen density * @return the computed view bounds */ // TODO RUM-3667 return an array of primitives here instead of creating an object. // This method is being called too often every time we take a screen snapshot // and we might want to avoid creating too many instances. fun resolveViewGlobalBounds(view: View, pixelsDensity: Float): GlobalBounds }
52
Kotlin
57
138
ddf2286c158ada4e6bdaa1799a5f9103dc3331e2
1,361
dd-sdk-android
Apache License 2.0
app/src/main/java/com/example/loginreqres/ui/theme/Font.kt
marlonpya
815,310,093
false
{"Kotlin": 57405}
package com.example.loginreqres.ui.theme import androidx.compose.ui.unit.sp val fontRegular = 16.sp
0
Kotlin
0
0
c09b9ab68b4cf365145d5cd6d497b8babd1dd1d6
102
Login-Reqres
Apache License 2.0
src/main/kotlin/no/nav/hjelpemidler/delbestilling/kafka/KafkaService.kt
navikt
638,489,446
false
{"Kotlin": 113641, "Dockerfile": 224}
package no.nav.hjelpemidler.delbestilling.kafka import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.databind.json.JsonMapper import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.kotlin.jacksonMapperBuilder import mu.KotlinLogging import no.nav.hjelpemidler.delbestilling.Config.kafkaProducerProperties import org.apache.kafka.clients.producer.KafkaProducer import org.apache.kafka.clients.producer.Producer import org.apache.kafka.clients.producer.ProducerConfig import org.apache.kafka.clients.producer.ProducerRecord import org.apache.kafka.common.serialization.StringSerializer import java.time.LocalDateTime import java.util.Properties import java.util.UUID import java.util.concurrent.TimeUnit private val log = KotlinLogging.logger {} class KafkaService( properties: Properties = kafkaProducerProperties, private val producer: Producer<String, String> = createProducer(properties), ) { init { Runtime.getRuntime().addShutdownHook(Thread(::shutdownHook)) } fun hendelseOpprettet( measurement: String, fields: Map<String, Any>, tags: Map<String, String>, ) { publish( measurement, jsonMapper.writeValueAsString( mapOf( "eventId" to UUID.randomUUID(), "eventName" to "hm-bigquery-sink-hendelse", "schemaId" to "hendelse_v2", "payload" to mapOf( "opprettet" to LocalDateTime.now(), "navn" to measurement, "kilde" to "hm-delbestilling-api", "data" to fields.mapValues { it.value.toString() } .plus(tags) .filterKeys { it != "counter" } ) ) ) ) } fun publish(key: String, eventName: String, value: Any) { val event = jsonMapper.valueToTree<ObjectNode>(value) .put("eventName", eventName) .put("eventId", UUID.randomUUID().toString()) val eventJson = jsonMapper.writeValueAsString(event) publish(key, eventJson) } private fun publish(key: String, event: String) { producer.send(ProducerRecord("teamdigihot.hm-soknadsbehandling-v1", key, event)).get(5, TimeUnit.SECONDS) } private fun shutdownHook() { log.info("received shutdown signal, stopping app") producer.close() } } private val jsonMapper: JsonMapper = jacksonMapperBuilder() .addModule(JavaTimeModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .build() private fun createProducer(properties: Properties): Producer<String, String> { properties[ProducerConfig.ACKS_CONFIG] = "all" properties[ProducerConfig.LINGER_MS_CONFIG] = "0" properties[ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION] = "1" return KafkaProducer(properties, StringSerializer(), StringSerializer()) }
1
Kotlin
0
0
388f2902146c0fc9d986a38eff76eb6febdb4d0c
3,112
hm-delbestilling-api
MIT License
DaftarBukuProject/app/src/main/java/com/example/daftarbukuproject/DataBuku.kt
ANDI-NURUL-INAYA
428,888,134
false
{"PHP": 85390, "Blade": 18394, "Kotlin": 7550, "Shell": 899}
package com.example.daftarbukuproject object DataBuku { private val judulbuku = arrayOf( "Mariposa", "<NAME>", "Dilan", "Milea", "Koala Kumal", "Pulang", "<NAME>", "Jingga dan Senja", "Sebuah Usaha Melupakan", "Sebuah Seni Untuk Bersikap Bodo Amat") private val bukuImages = intArrayOf( R.drawable.mariposa, R.drawable.geez_ann, R.drawable.dilan, R.drawable.milea, R.drawable.koala_kumal, R.drawable.pulang, R.drawable.mantappujiwa, R.drawable.jingga_senja, R.drawable.boy_candra, R.drawable.mark_manson) val listData:ArrayList<Buku> get() { val list = arrayListOf<Buku>() for (position in judulbuku.indices){ val buku = Buku() buku.judul = judulbuku[position] buku.gambar = bukuImages[position] list.add(buku) } return list } }
0
PHP
0
0
6b770fbe5171191df190f8a56ddb4a7a02f92740
995
pertemuan6-kakas
MIT License
compiler/testData/codegen/box/reflection/lambdaClasses/reflectOnDefaultWithMfvcArgument.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// LAMBDAS: CLASS // !OPT_IN: kotlin.reflect.jvm.ExperimentalReflectionOnLambdas // TARGET_BACKEND: JVM_IR // WITH_REFLECT // LANGUAGE: +ValueClasses import kotlin.reflect.jvm.reflect @JvmInline value class C(val x1: UInt, val x2: Int) fun C.f(x: (String) -> Unit = { OK: String -> }) = x.reflect()?.parameters?.singleOrNull()?.name fun box(): String = C(0U, 1).f() ?: "null"
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
380
kotlin
Apache License 2.0
extensions/retrofit/src/main/java/com/extensions/retrofit/components/handlerProviders/CallHandlerProvider.kt
VitaliyDoskoch
263,280,184
false
null
package com.extensions.retrofit.components.handlerProviders import io.reactivex.Single import retrofit2.Response interface CallHandlerProvider { fun <R : Response<*>> provideHandler(): (Single<R>) -> Single<R> }
0
Kotlin
0
0
9de9670b1b24934a39122b58517d026569cea1d3
219
Movies
MIT License
app/src/main/java/com/example/noterssaver/presentation/MainActivity.kt
Shahidzbi4213
613,411,095
false
null
package com.example.noterssaver.presentation import android.os.Bundle import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.example.noterssaver.presentation.authentication.AuthenticationViewModel import com.example.noterssaver.presentation.authentication.utils.AuthState import com.example.noterssaver.presentation.setting.SettingViewModel import com.example.noterssaver.presentation.setting.component.currentAppTheme import com.example.noterssaver.presentation.util.theme.ReplyTheme import com.example.noterssaver.presentation.view.component.NotesApp import org.koin.androidx.viewmodel.ext.android.viewModel class MainActivity : AppCompatActivity() { private val authViewModel by viewModel<AuthenticationViewModel>() private val settingViewModel by viewModel<SettingViewModel>() private val mainViewModel by viewModels<MainViewModel>() private var appLockState = false private var startState = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar?.hide() setContent { ReplyTheme(dynamicColor = false, darkTheme = currentAppTheme()) { val authenticationState by authViewModel.authenticationState.collectAsStateWithLifecycle() LaunchedEffect(key1 = Unit) { settingViewModel.appLockState.collect { appLockState = it } } if (!startState) { if (appLockState) { authViewModel.startAuthentication(this@MainActivity) when (authenticationState) { AuthState.Authenticated -> NotesApp(mainViewModel.isScrollUp) AuthState.Authenticating -> Unit AuthState.AuthenticationFailed -> finishAffinity() } } else NotesApp(mainViewModel.isScrollUp) } } } } }
0
Kotlin
1
1
9c4ee6cc7569f1228df61f55e7bb01851280b88e
2,273
NotesSaver
MIT License
kronos-core/src/test/kotlin/com/kotlinorm/utils/database/OracleSupportTest.kt
Kronos-orm
810,144,705
false
{"Kotlin": 888333}
package com.kotlinorm.utils.database class OracleSupportTest { }
4
Kotlin
3
16
6ca17aacfb1ee3c3a1b20baac0811450a59fb237
65
Kronos-orm
Apache License 2.0
src/main/kotlin/com/jcs/suadeome/professionals/PhoneNumber.kt
jcsantosbr
79,963,964
false
null
package com.jcs.suadeome.professionals import com.jcs.suadeome.generators.EntityType import com.jcs.suadeome.types.EntityConstructionFailed data class PhoneNumber(private val _number: String) { val number = _number.replace("\\s+".toRegex(), "") init { if (number.isBlank() || !isNumeric(number)) { throw EntityConstructionFailed(EntityType.PHONE_NUMBER, number) } } private fun isNumeric(n: String): Boolean { return n.matches("^\\d+$".toRegex()) } }
5
Kotlin
0
0
bf41f5775126fed2900da3f1185d57506b8c9358
515
suadeome-backendjvm
MIT License
app/src/main/java/com/example/mvpproject/views/home/HomePresenter.kt
apirahman55
249,498,055
false
{"Kotlin": 17388}
package com.example.mvpproject.views.home import androidx.navigation.NavController import androidx.navigation.Navigation import com.example.mvpproject.R import com.example.mvpproject.utils.SharedPreferenceManager import kotlinx.android.synthetic.main.fragment_home.* class HomePresenter(private val view: HomeFragment) : HomeView.Presenter { lateinit var navController: NavController lateinit var sharedPreferenceManager: SharedPreferenceManager init { view.view?.let { navController = Navigation.findNavController(it) } sharedPreferenceManager = SharedPreferenceManager(view.context) } override fun initialize() { if(!sharedPreferenceManager.preferenceManager .getString(SharedPreferenceManager.TOKEN, "") .isNullOrEmpty()) { view.welcome?.text = "You has been logged" view.buttonAction?.text = "Logout" view.buttonAction?.setOnClickListener { sharedPreferenceManager.editor .remove(SharedPreferenceManager.TOKEN) .apply() sharedPreferenceManager.editor .commit() navController.navigate(R.id.action_homeFragment_to_loginFragment) } } else { view.buttonAction?.setOnClickListener { navController.navigate(R.id.action_homeFragment_to_loginFragment) } } } }
0
Kotlin
2
2
5c375de4070e63a851678ec0843da0f6f2a2b382
1,479
Simple-Example-MVP-Navigation-Arch-Components-and-Retrofit
MIT License
plugins/parcelize/parcelize-compiler/testData/box/mppAdditionalAnnotations.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// TARGET_BACKEND: JVM_IR // LANGUAGE: +MultiPlatformProjects // WITH_STDLIB // Metadata compilations do not see through the expect/actuals and therefore, // there are parcelize errors in metadata compilations. // IGNORE_FIR_DIAGNOSTICS_DIFF // MODULE: m1-common // FILE: common.kt package test expect interface MyParcelable annotation class TriggerParcelize @Target(AnnotationTarget.PROPERTY) @Retention(AnnotationRetention.SOURCE) expect annotation class MyIgnore() expect interface MyParceler<T> @Retention(AnnotationRetention.SOURCE) @Repeatable @Target(AnnotationTarget.CLASS, AnnotationTarget.PROPERTY) expect annotation class MyTypeParceler<T, P : MyParceler<in T>>() expect object SpecialStringParceler : MyParceler<String> @TriggerParcelize data class User( val i: Int, @MyTypeParceler<String, SpecialStringParceler> val s: String, @MyIgnore val name: String = "test", ) : MyParcelable // MODULE: m2-jvm()()(m1-common) // FILE: android.kt @file:JvmName("TestKt") package test import kotlinx.parcelize.* actual typealias MyParcelable = android.os.Parcelable actual typealias MyIgnore = IgnoredOnParcel actual typealias MyParceler<T> = Parceler<T> actual typealias MyTypeParceler<T, P> = TypeParceler<T, P> actual object SpecialStringParceler : Parceler<String> { override fun String.write(parcel: android.os.Parcel, flags: Int) { parcel.writeString(this) } override fun create(parcel: android.os.Parcel): String { return "HELLO " + parcel.readString() } } fun box() = parcelTest { parcel -> val user = User(1, "John", "John") user.writeToParcel(parcel, 0) val bytes = parcel.marshall() parcel.unmarshall(bytes, 0, bytes.size) parcel.setDataPosition(0) val user2 = parcelableCreator<User>().createFromParcel(parcel) assert(user.i == user2.i) assert(user.name != user2.name) assert(user2.s == "HELLO John") }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,911
kotlin
Apache License 2.0
app/src/main/java/com/example/firstcode/MyIntentService.kt
ericwangjp
372,783,066
false
null
package com.example.firstcode import android.app.IntentService import android.content.Intent import android.content.Context import android.util.Log // TODO: Rename actions, choose action names that describe tasks that this // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS private const val ACTION_FOO = "com.example.firstcode.action.FOO" private const val ACTION_BAZ = "com.example.firstcode.action.BAZ" // TODO: Rename parameters private const val EXTRA_PARAM1 = "com.example.firstcode.extra.PARAM1" private const val EXTRA_PARAM2 = "com.example.firstcode.extra.PARAM2" private const val TAG = "MyIntentService" /** * An [IntentService] subclass for handling asynchronous task requests in * a service on a separate handler thread. * TODO: Customize class - update intent actions, extra parameters and static * helper methods. */ class MyIntentService : IntentService("MyIntentService") { override fun onHandleIntent(intent: Intent?) { Log.e(TAG, "onHandleIntent: -->${Thread.currentThread().name}") when (intent?.action) { ACTION_FOO -> { val param1 = intent.getStringExtra(EXTRA_PARAM1) val param2 = intent.getStringExtra(EXTRA_PARAM2) handleActionFoo(param1, param2) } ACTION_BAZ -> { val param1 = intent.getStringExtra(EXTRA_PARAM1) val param2 = intent.getStringExtra(EXTRA_PARAM2) handleActionBaz(param1, param2) } } } /** * Handle action Foo in the provided background thread with the provided * parameters. */ private fun handleActionFoo(param1: String?, param2: String?) { Log.e(TAG, "handleActionFoo: $param1 - $param2") } /** * Handle action Baz in the provided background thread with the provided * parameters. */ private fun handleActionBaz(param1: String?, param2: String?) { Log.e(TAG, "handleActionBaz: $param1 - $param2") } override fun onDestroy() { super.onDestroy() Log.e(TAG, "onDestroy: -->") } companion object { /** * Starts this service to perform action Foo with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ // TODO: Customize helper method @JvmStatic fun startActionFoo(context: Context, param1: String, param2: String) { val intent = Intent(context, MyIntentService::class.java).apply { action = ACTION_FOO putExtra(EXTRA_PARAM1, param1) putExtra(EXTRA_PARAM2, param2) } context.startService(intent) } /** * Starts this service to perform action Baz with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ // TODO: Customize helper method @JvmStatic fun startActionBaz(context: Context, param1: String, param2: String) { val intent = Intent(context, MyIntentService::class.java).apply { action = ACTION_BAZ putExtra(EXTRA_PARAM1, param1) putExtra(EXTRA_PARAM2, param2) } context.startService(intent) } } }
0
Kotlin
0
1
b4d874480835cba6a9fa3c8166fc931787aa7be4
3,423
FirstCode
Apache License 2.0
player/src/main/java/com/kafka/player/playback/RealPlayback.kt
vipulyaara
170,554,386
false
null
//package com.kafka.player.playback // //import android.app.Notification //import android.app.NotificationChannel //import android.app.NotificationManager //import android.content.Context //import android.os.Build //import android.os.Handler //import androidx.core.net.toUri //import com.google.android.exoplayer2.C //import com.google.android.exoplayer2.ExoPlaybackException //import com.google.android.exoplayer2.Player.EventListener //import com.google.android.exoplayer2.SimpleExoPlayer //import com.google.android.exoplayer2.Timeline //import com.google.android.exoplayer2.database.ExoDatabaseProvider //import com.google.android.exoplayer2.source.ConcatenatingMediaSource //import com.google.android.exoplayer2.source.MediaSource //import com.google.android.exoplayer2.source.MediaSourceEventListener //import com.google.android.exoplayer2.source.ProgressiveMediaSource //import com.google.android.exoplayer2.ui.PlayerNotificationManager //import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory //import com.google.android.exoplayer2.upstream.DefaultHttpDataSource //import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory //import com.google.android.exoplayer2.upstream.cache.NoOpCacheEvictor //import com.google.android.exoplayer2.upstream.cache.SimpleCache //import com.google.android.exoplayer2.util.Util //import com.kafka.data.CustomScope //import com.kafka.player.playback.model.MediaItem //import dagger.hilt.android.qualifiers.ApplicationContext //import kotlinx.coroutines.CoroutineScope //import kotlinx.coroutines.Dispatchers //import kotlinx.coroutines.Job //import kotlinx.coroutines.launch //import timber.log.Timber //import java.io.File //import javax.inject.Inject //import javax.inject.Singleton //import kotlin.math.pow // //@Singleton //class RealPlayback @Inject constructor( // @ApplicationContext private val context: Context //) : PlayerContract, EventListener, // PlayerNotificationManager.NotificationListener, CoroutineScope by CustomScope() { // // private val player: SimpleExoPlayer by lazy { // SimpleExoPlayer.Builder(context) // .setUseLazyPreparation(true) // .build() // .apply { // addListener(this@RealPlayback) // } // } // // // private val playerNotificationManager: PlayerNotificationManager by lazy { // createNotificationChannel() // // PlayerNotificationManager( // context, // CHANNEL_ID, // NOTIFICATION_ID, // descriptionAdapter, // this // ).apply { // setColorized(true) // // } // } // // private val background = CoroutineScope(Dispatchers.IO + Job()) // // val currentMediaItem: MediaItem? // get() = player.currentTag as? MediaItem // // override suspend fun initPlayer() { // playerNotificationManager.setPlayer(player) // player.setHandleAudioBecomingNoisy(true) // player.setWakeMode(C.WAKE_MODE_NETWORK) // if (ExoPlayerCache.simpleCache(context).cacheSpace > 6.0.pow(6.0)) { // Timber.d("The cache is too long starting to evict") // background.launch { ExoPlayerCache.simpleCache(context).release() } // } // } // // private fun createNotificationChannel() { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // val importance = NotificationManager.IMPORTANCE_LOW // val notificationChannel = // NotificationChannel(CHANNEL_ID, NOTIFICATION_CHANEL_NAME, importance) // notificationChannel.enableVibration(true) // notificationChannel.vibrationPattern = longArrayOf(0L) // val notificationManager = // context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager // notificationManager?.createNotificationChannel(notificationChannel) // } // } // // private var concatenatedSource = ConcatenatingMediaSource() // // // override suspend fun addToQueue( // mediaItem: MediaItem, // playWhenReady: Boolean, // clearOldPlayList: Boolean // ) = addToQueue(listOf(mediaItem), playWhenReady, clearOldPlayList) // // override suspend fun addToQueue( // mediaItems: List<MediaItem>, // playWhenReady: Boolean, // clearOldPlayList: Boolean // ) { // if (clearOldPlayList) { // concatenatedSource.clear() // } // player.playWhenReady = playWhenReady // addItems(*mediaItems.toTypedArray()) // } // // private fun addItems(vararg mediaItems: MediaItem) { // if (!player.isPlaying) // player.prepare(concatenatedSource) // // mediaItems.forEach { // concatenatedSource.addMediaSource(getDataSourceFromTrack(it)) // } // } // // /** // * Prepare uri and data source to be able to execute // * @param mediaItem Track // * @return MediaSource // */ // private fun getDataSourceFromTrack(mediaItem: MediaItem): MediaSource { // // Produces DataSource instances through which media data is loaded // // val httpDataSourceFactory = DefaultHttpDataSourceFactory( // Util.getUserAgent(context, context.applicationInfo.name), // null /* listener */, // DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS, // DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS, // true /* allowCrossProtocolRedirects */ // ) // // val dataSourceFactory = DefaultDataSourceFactory( // context, // null, // httpDataSourceFactory // ) // // val mediaSource = // ProgressiveMediaSource.Factory(/*CacheDataSourceFactory(ExoPlayerCache.simpleCache(context), */ // dataSourceFactory/*)*/ // ).setTag(mediaItem).createMediaSource(mediaItem.playbackUrl.toUri()) // // /*** // * Check conditions to allow user listen audios // */ // mediaSource.addEventListener(Handler(), object : MediaSourceEventListener { // override fun onLoadStarted( // windowIndex: Int, // mediaPeriodId: MediaSource.MediaPeriodId?, // loadEventInfo: MediaSourceEventListener.LoadEventInfo?, // mediaLoadData: MediaSourceEventListener.MediaLoadData? // ) { // /*** // * Check preconditions to playback audio // */ // try { // background.launch { //// val hasError = callback?.checkPreconditions(mediaItem) //// hasError?.let { //// callback?.preconditionsPlaybackFailed(it) //// } // } // } catch (e: Exception) { // Timber.e(e) // } // } // }) // // return mediaSource // } // // // override fun onTimelineChanged(timeline: Timeline, reason: Int) { // Timber.d("onTimelineChanged") // } // // override fun onLoadingChanged(isLoading: Boolean) { // Timber.d("onLoadingChanged:$isLoading") //// callback?.onLoadingChange(isLoading) // } // // override fun onPlayerError(error: ExoPlaybackException) { // Timber.e(error, "onPlayerError") // } // // override fun onNotificationPosted( // notificationId: Int, // notification: Notification, // ongoing: Boolean // ) { //// callback?.onNotificationChanged(notificationId, notification, ongoing) // } // // override suspend fun isPlaying(): Boolean = player.isPlaying // override suspend fun next() = player.next() // override suspend fun hasNext(): Boolean = player.hasNext() // override suspend fun clear() = concatenatedSource.clear() // override suspend fun isEmpty(): Boolean = concatenatedSource.size == 0 // // override suspend fun release() { // playerNotificationManager.setPlayer(null) // player.release() // } // // object ExoPlayerCache { // private var cache: SimpleCache? = null // fun simpleCache(context: Context): SimpleCache { // if (cache == null) { // // val directory = File(context.cacheDir, "media") // if (!directory.exists()) // directory.mkdir() // // cache = SimpleCache( // directory, // NoOpCacheEvictor(), // ExoDatabaseProvider(context) // ) // // Timber.d("Initializing cache exoplayer") // } // return cache!! // } // } // // companion object { // private const val CHANNEL_ID = "1001" // private const val NOTIFICATION_CHANEL_NAME = "Notifications" // const val NOTIFICATION_ID = 1001 // } //}
0
Kotlin
4
18
71a639047c246aa62c33fa472ab70100da25f727
8,969
Kafka
Apache License 2.0
idea/idea-completion/testData/basic/java/importAliases/ExtensionValSmart.kt
JakeWharton
99,388,807
true
null
import java.io.File import kotlin.io.extension as ext fun foo(file: File): String { return file.ex<caret> } // COMPLETION_TYPE: SMART // EXIST: { lookupString: "ext", itemText: "ext", tailText: " for File (kotlin.io.extension)" }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
236
kotlin
Apache License 2.0
src/main/kotlin/eu/hnesoft/gameservice/Response.kt
hnesoft
664,231,257
false
null
package eu.hnesoft.gameservice data class Response(var usersChoice: Symbol?, var randomChoice: Symbol?, var resultMessage: String?)
0
Kotlin
0
0
ce167a6ad364013af1c5beaa09f184edb7fbdacc
132
gameservice
MIT License
src/jvmMain/kotlin/org/paicoin/rpcclient/AsyncPaicoinRpcClient.kt
paicoin
310,283,184
false
null
/* * PaiCoin-RPC-Client-Kotlin License * * Copyright (c) 2021, JinHua.IO. All rights reserved. * * 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 org.paicoin.rpcclient import com.googlecode.jsonrpc4j.JsonRpcMethod import java.math.BigDecimal import java.util.concurrent.CompletableFuture interface AsyncPaicoinRpcClient { @JsonRpcMethod("abandontransaction") fun abandonTransaction(transactionId: String): CompletableFuture<Void> @JsonRpcMethod("abortrescan") fun abortRescan(): CompletableFuture<Void> @JsonRpcMethod("addmultisigaddress") fun addMultiSigAddress(required: Int? = null, keys: List<String>): CompletableFuture<String> @JsonRpcMethod("addnode") fun addNode(address: String, operation: NodeListOperation): CompletableFuture<Void> @JsonRpcMethod("backupwallet") fun backupWallet(destination: String): CompletableFuture<Void> @JsonRpcMethod("clearbanned") fun clearBanned(): CompletableFuture<Void> @JsonRpcMethod("createmultisig") fun createMultiSig(required: Int, keys: List<String>): CompletableFuture<MultiSigAddress> @JsonRpcMethod("createrawtransaction") fun createRawTransaction( inputs: List<OutPoint>, outputs: Map<String, BigDecimal>, lockTime: Int? = null, replaceable: Boolean? = null ): CompletableFuture<String> @JsonRpcMethod("decoderawtransaction") fun decodeRawTransaction(transactionId: String): CompletableFuture<Transaction> @JsonRpcMethod("decodescript") fun decodeScript(scriptHex: String): CompletableFuture<DecodedScript> @JsonRpcMethod("disconnectnode") fun disconnectNode(nodeAddress: String? = null, nodeId: Int? = null): CompletableFuture<Void> @JsonRpcMethod("dumpprivkey") fun dumpPrivateKey(address: String): CompletableFuture<String> @JsonRpcMethod("dumpwallet") fun dumpWallet(filename: String): CompletableFuture<Map<*, *>> @JsonRpcMethod("encryptwallet") fun encryptWallet(passphrase: String): CompletableFuture<Void> @JsonRpcMethod("generate") fun generate(numberOfBlocks: Int, maxTries: Int? = null): CompletableFuture<List<String>> @JsonRpcMethod("getaddednodeinfo") fun getAddedNodeInfo(): CompletableFuture<List<AddedNodeInfo>> @JsonRpcMethod("getbalance") fun getBalance( account: String = "*", minconf: Int = 1, includeWatchOnly: Boolean = false): CompletableFuture<BigDecimal> @JsonRpcMethod("getbestblockhash") fun getBestBlockhash(): CompletableFuture<String> @JsonRpcMethod("getblock") fun getBlockData(blockHash: String, verbosity: Int = 0): CompletableFuture<String> @JsonRpcMethod("getblock") fun getBlock(blockHash: String, verbosity: Int = 1): CompletableFuture<BlockInfo> @JsonRpcMethod("getblock") fun getBlockWithTransactions(blockHash: String, verbosity: Int = 2): CompletableFuture<BlockInfoWithTransactions> @JsonRpcMethod("getblockchaininfo") fun getBlockchainInfo(): CompletableFuture<BlockChainInfo> @JsonRpcMethod("getblockcount") fun getBlockCount(): CompletableFuture<Int> @JsonRpcMethod("getblockhash") fun getBlockHash(height: Int): CompletableFuture<String> @JsonRpcMethod("getblockheader") fun getBlockHeader(blockHash: String, verbose: Boolean? = false): CompletableFuture<Any> @JsonRpcMethod("getblocktemplate") fun getBlockTemplate(blockTemplateRequest: BlockTemplateRequest? = null): CompletableFuture<Void> @JsonRpcMethod("getchaintips") fun getChainTips(): CompletableFuture<List<ChainTip>> @JsonRpcMethod("getchaintxstats") fun getChainTransactionStats( blockWindowSize: Int? = null, blockHashEnd: String? = null ): CompletableFuture<ChainTransactionStats> @JsonRpcMethod("getconnectioncount") fun getConnectionCount(): CompletableFuture<Int> @JsonRpcMethod("getdifficulty") fun getDifficulty(): CompletableFuture<BigDecimal> @JsonRpcMethod("getmemoryinfo") fun getMemoryInfo(): CompletableFuture<Any> @JsonRpcMethod("getmempoolancestors") fun getMempoolAncestors(transactionId: String): CompletableFuture<Any> @JsonRpcMethod("getmempooldescendants") fun getMempoolDescendants(): CompletableFuture<Any> @JsonRpcMethod("getmempoolentry") fun getMempoolEntry(transactionId: String): CompletableFuture<Map<*, *>> @JsonRpcMethod("getmempoolinfo") fun getMempoolInfo(): CompletableFuture<MemPoolInfo> @JsonRpcMethod("getmininginfo") fun getMiningInfo(): CompletableFuture<MiningInfo> @JsonRpcMethod("getnettotals") fun getNetworkTotals(): CompletableFuture<NetworkTotals> @JsonRpcMethod("getnetworkhashps") fun getNetworkHashesPerSeconds(lastBlocks: Int, height: Int): CompletableFuture<Long> @JsonRpcMethod("getnetworkinfo") fun getNetworkInfo(): CompletableFuture<NetworkInfo> @JsonRpcMethod("getnewaddress") fun getNewAddress(): CompletableFuture<String> @JsonRpcMethod("getpeerinfo") fun getPeerInfo(): CompletableFuture<List<PeerInfo>> @JsonRpcMethod("getrawchangeaddress") fun getRawChangeAddress(): CompletableFuture<String> @JsonRpcMethod("getrawmempool") fun getRawMemPool(verbose: Boolean = false): CompletableFuture<List<Map<*, *>>> @JsonRpcMethod("getrawtransaction") fun getRawTransaction(transactionId: String, verbosity: Int = 1): CompletableFuture<Transaction> @JsonRpcMethod("getreceivedbyaddress") fun getReceivedByAddress(address: String, minConfirmations: Int = 1): CompletableFuture<BigDecimal> @JsonRpcMethod("gettransaction") fun getWalletTransaction(transactionId: String): CompletableFuture<Map<*, *>> @JsonRpcMethod("gettxout") fun getUnspentTransactionOutputInfo(transactionId: String, index: Int): CompletableFuture<Map<*, *>> @JsonRpcMethod("gettxoutsetinfo") fun getUnspentTransactionOutputSetInfo(): CompletableFuture<UtxoSet> @JsonRpcMethod("getwalletinfo") fun getWalletInfo(): CompletableFuture<Map<*, *>> @JsonRpcMethod("importaddress") fun importAddress( scriptOrAddress: String, label: String? = null, rescan: Boolean? = null, includePayToScriptHash: Boolean? = null ): CompletableFuture<Void> @JsonRpcMethod("importprivkey") fun importPrivateKey( privateKey: String, label: String? = null, rescan: Boolean? = null ): CompletableFuture<Void> @JsonRpcMethod("importpubkey") fun importPublicKey( publicKey: String, label: String? = null, rescan: Boolean? = null ): CompletableFuture<Void> @JsonRpcMethod("importwallet") fun importWallet(walletFile: String): CompletableFuture<Void> @JsonRpcMethod("keypoolrefill") fun keypoolRefill(newSize: Int = 100): CompletableFuture<Void> @JsonRpcMethod("listaddressgroupings") fun listAddressGroupings(): CompletableFuture<List<*>> @JsonRpcMethod("listbanned") fun listBanned(): CompletableFuture<List<String>> @JsonRpcMethod("listlockunspent") fun listLockUnspent(): CompletableFuture<List<Map<*, *>>> @JsonRpcMethod("listreceivedbyaddress") fun listReceivedByAddress( minConfirmations: Int? = null, includeEmpty: Boolean? = null, includeWatchOnly: Boolean? = null ): CompletableFuture<List<Map<*, *>>> @JsonRpcMethod("listsinceblock") fun listSinceBlock( blockHash: String? = null, targetConfirmations: Int? = null, includeWatchOnly: Boolean? = null, includeRemoved: Boolean? = null ): CompletableFuture<Map<*, *>> @JsonRpcMethod("listtransactions") fun listTransactions( account: String? = null, count: Int? = null, skip: Int? = null, includeWatchOnly: Boolean? = null ): CompletableFuture<List<Map<*, *>>> @JsonRpcMethod("listunspent") fun listUnspent( minConfirmations: Int? = null, maxConfirmations: Int? = null, addresses: List<String>? = null, includeUnsafe: Boolean? = null, queryOptions: QueryOptions? = null ): CompletableFuture<List<QueryResult>> @JsonRpcMethod("listwallets") fun listWallets(): CompletableFuture<List<String>> @JsonRpcMethod("lockunspent") fun lockUnspent(unlock: Boolean, unspentOutputs: List<OutPoint>): CompletableFuture<Boolean> fun ping(): CompletableFuture<Void> @JsonRpcMethod("preciousblock") fun preciousBlock(block: String): CompletableFuture<Void> @JsonRpcMethod("prioritisetransaction") fun prioritiseTransaction(transactionId: String, dummy: Int, feeDeltaSatoshis: Int): CompletableFuture<Void> @JsonRpcMethod("pruneblockchain") fun pruneBlockchain(blockHeightOrUnixTimestamp: Long): CompletableFuture<Void> @JsonRpcMethod("removeprunedfunds") fun removePrunedFunds(transactionId: String): CompletableFuture<Void> @JsonRpcMethod("sendmany") fun sendMany(account: String, addressAmounts: Map<String, BigDecimal>, comment: String? = null, subtractFee: Boolean = false, replaceable: Boolean = false, minConfirmations: Int? = null, feeEstimateMode: FeeEstimateMode? = null ): CompletableFuture<Void> @JsonRpcMethod("sendrawtransaction") fun sendRawTransaction(transaction: String): CompletableFuture<String> @JsonRpcMethod("sendtoaddress") fun sendToAddress( address: String, amount: BigDecimal, comment: String? = null, commentTo: String? = null, subtractFee: Boolean? = null, replaceable: Boolean? = null, minConfirmations: Int? = null, feeEstimateMode: FeeEstimateMode? = null): CompletableFuture<String> @JsonRpcMethod("setban") fun setBan( address: String, operation: NodeListOperation, seconds: Int ): CompletableFuture<Void> @JsonRpcMethod("settxfee") fun setTransactionFee(fee: Double): CompletableFuture<Void> @JsonRpcMethod("estimatesmartfee") fun estimateSmartFee(confTarget: Int, feeEstimateMode: FeeEstimateMode? = FeeEstimateMode.CONSERVATIVE): CompletableFuture<EstimateSmartFee> @JsonRpcMethod("signmessage") fun signMessage( address: String, message: String ): CompletableFuture<Void> @JsonRpcMethod("signmessagewithprivkey") fun signMessageWithPrivateKey( privateKey: String, message: String ): CompletableFuture<Void> @JsonRpcMethod("signrawtransaction") fun signRawTransaction(transactionId: String): CompletableFuture<Void> @JsonRpcMethod("submitblock") fun submitBlock(blockData: String): CompletableFuture<Void> fun uptime(): CompletableFuture<Int> @JsonRpcMethod("validateaddress") fun validateAddress(address: String): CompletableFuture<Void> @JsonRpcMethod("verifychain") fun verifyChain(): CompletableFuture<Boolean> @JsonRpcMethod("verifymessage") fun verifyMessage( address: String, signature: String, message: String ): CompletableFuture<Void> @JsonRpcMethod("searchrawtransactions") fun searchRawSerialisedTransactions( address: String, verbose: Int? = 0, skip: Int? = null, count: Int? = null, vInExtra: Int? = null, reverse: Boolean? = null): CompletableFuture<List<String>> @JsonRpcMethod("searchrawtransactions") fun searchRawVerboseTransactions( address: String, verbose: Int? = 1, skip: Int? = null, count: Int? = null, vInExtra: Int? = null, reverse: Boolean? = null): CompletableFuture<List<SearchedTransactionResult>> /** * btcd-specific extension methods */ @JsonRpcMethod("authenticate") fun btcdAuthenticate(username: String, password: String): CompletableFuture<Void> @JsonRpcMethod("generate") fun btcdGenerate(numberOfBlocks: Int): CompletableFuture<List<String>> @JsonRpcMethod("getblock") fun btcdGetBlockWithTransactions(blockHash: String, verbose: Boolean = true, verboseTx: Boolean = true): CompletableFuture<BlockInfoWithTransactions> }
0
Kotlin
0
1
340beb1945a697005b255078f955debe2e7a4c09
13,531
paicoin-rpc-client
Apache License 2.0
sample/src/main/java/io/rekast/sdk/sample/ui/components/accountdetails/AccountStatusComponent.kt
re-kast
603,236,053
false
{"Kotlin": 100585}
/* * Copyright 2023, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rekast.sdk.sample.ui.components.accountdetails import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Divider import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.MutableLiveData import io.rekast.sdk.model.api.AccountHolderStatus import io.rekast.sdk.sample.R @Composable fun AccountStatusComponent( modifier: Modifier = Modifier, accountHolderStatus: MutableLiveData<AccountHolderStatus?> ) { Column( modifier = modifier.fillMaxWidth() ) { Column(modifier = modifier.padding(end = 20.dp)) { Text( text = stringResource(id = R.string.account_status_title), style = TextStyle( fontSize = 18.sp ), color = colorResource(id = R.color.black), fontWeight = FontWeight.Bold ) Divider(modifier = modifier.padding(top = 10.dp, bottom = 10.dp)) } Row(horizontalArrangement = Arrangement.SpaceEvenly) { Column(modifier = modifier.padding(end = 20.dp)) { Text( text = stringResource(id = R.string.status), color = colorResource(id = R.color.black), fontWeight = FontWeight.Bold ) } Column(modifier = modifier.padding(end = 10.dp)) { accountHolderStatus.value?.result?.let { result -> var text = stringResource(id = R.string.in_Active) if (result) { text = stringResource(id = R.string.active) } Text( text = text, color = colorResource( id = R.color.black ) ) } } } } }
3
Kotlin
0
1
ba1eb0da943ce8f0010d0a8015658843ee3aab2d
3,030
android-mtn-momo-api-sdk
Apache License 2.0
app/src/main/java/com/mertgundoganx/moviesapp/data/model/MoviesResponse.kt
mertgundoganx
453,163,283
false
{"Kotlin": 14280}
package com.mertgundoganx.moviesapp.data.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class MoviesResponse( @SerializedName("results") val results: List<Movie> ) : Parcelable
0
Kotlin
0
0
3e6b2619e686dc2a032a59ee78c9d544f61d73cf
275
MoviesApp
Apache License 2.0
kotlin-antd/antd-samples/src/main/kotlin/samples/autocomplete/Options.kt
LuoKevin
341,311,901
true
{"Kotlin": 1549697, "HTML": 1503}
package samples.autocomplete import antd.autocomplete.* import antd.select.* import kotlinext.js.* import react.* import styled.* interface OptionsCompleteState : RState { var result: Array<String> } class OptionsComplete : RComponent<RProps, OptionsCompleteState>() { private val handleSearch = fun(value: String) { val newResult = if (value.isEmpty() || value.contains("@")) { emptyArray() } else { arrayOf("gmail.com", "163.com", "qq.com") .map { domain -> "$value@$domain" }.toTypedArray() } setState { result = newResult } } override fun OptionsCompleteState.init() { result = emptyArray() } override fun RBuilder.render() { val children = state.result.map { email -> buildElement { option { attrs.key = email +email } } }.toTypedArray() autoComplete { attrs { style = js { width = 200 } onSearch = handleSearch placeholder = "input here" } childList.add(children) } } } fun RBuilder.optionsComplete() = child(OptionsComplete::class) {} fun RBuilder.options() { styledDiv { css { +AutoCompleteStyles.options } optionsComplete() } }
0
null
0
0
9f57507607c3dd5d5452f3cbeb966b6db3d60c76
1,410
kotlin-js-wrappers
Apache License 2.0
app/src/androidTest/java/com/levibostian/tellerexample/rule/TellerInitRule.kt
levibostian
132,034,933
false
null
package com.levibostian.tellerexample.rule import android.content.Context import androidx.test.platform.app.InstrumentationRegistry import com.levibostian.teller.Teller import org.junit.rules.ExternalResource class TellerInitRule: ExternalResource() { override fun before() { InstrumentationRegistry.getInstrumentation().targetContext.applicationContext.let { application -> val sharedPrefs = application.getSharedPreferences("teller-testing", Context.MODE_PRIVATE) Teller.initTesting(sharedPrefs) Teller.shared.clear() } } }
24
Kotlin
2
14
90f3e7dc105fba1ad80bb3b9373f8de60c325f65
590
Teller-Android
MIT License
mbprotokit/src/main/java/com/daimler/mbprotokit/dto/service/ServiceActivationStatusUpdate.kt
Daimler
199,815,262
false
null
package com.daimler.mbprotokit.dto.service data class ServiceActivationStatusUpdate( val sequenceNumber: Int, val finOrVin: String, val updates: List<ServiceUpdate> )
1
null
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
180
MBSDK-Mobile-Android
MIT License
Problems/Function generator/src/Task.kt
redstrike
281,227,598
false
null
fun identity(n: Int): Int = n fun half(n: Int): Int = n / 2 fun zero(n: Int): Int = 0 fun generate(funcName: String): (Int) -> Int = when (funcName) { "identity" -> ::identity "half" -> ::half else -> ::zero }
0
HTML
0
0
b02ef280def789f03fbf0941f745b64356a93b85
222
flashcards
MIT License
src/test/kotlin/GetOptTests.kt
hankadler
273,062,583
false
{"Kotlin": 11946}
import com.hankadler.io.GetOpt fun main() { var argv: Array<String> var shortOpts: String var longOpts: List<String> shortOpts = "rfi:" testParseShortOpts(shortOpts) // Good longOpts = listOf("long", "long-opt=", "ll") testParseLongOpts(longOpts) // Bad longOpts = listOf("long ", "0long", "a", "long-", "--", "long-option-=") for (opt in longOpts) { testParseLongOpts(listOf(opt)) } // Case 01 shortOpts = "hrfi:Hw:" longOpts = listOf("help", "recursive", "force", "input=", "human-readable", "with-value=") argv = arrayOf("-r", "--force", "-ipepe.txt", "papo", "-H", "-w", "some list", "arg1", "arg2") testGetOpt(argv, shortOpts, longOpts) // Case 02 shortOpts = "h:ri:" longOpts = listOf("help", "recursive", "input=", "with-value=") argv = arrayOf("-r", "-ipepe.txt", "papo", "arg1", "arg2") testGetOpt(argv, shortOpts, longOpts) // Case 03 shortOpts = "hi:" longOpts = listOf("help", "input=", "with-value=") arrayOf("-r", "-ipepe.txt", "papo", "arg1", "arg2") testGetOpt(argv, shortOpts, longOpts) } fun testGetOpt(argv: Array<String>, shortOpts: String, longOpts: List<String>) { println("\n--- Test: getOpt() ---") println("INPUT") println(" argv: ${argv.toList()}") println(" shortOpts: $shortOpts") println(" longOpts: $longOpts") val (opts, args) = GetOpt.getOpt(argv, shortOpts, longOpts) println("OUTPUT") println(" opts: $opts") println(" args: ${args.toList()}") } fun testParseShortOpts(shortOpts: String) { println("\n--- Test: parseShortOpts() ---") println("INPUT") println(" shortOpts: $shortOpts") println("OUTPUT") println(" " + GetOpt.parseShortOpts(shortOpts)) } fun testParseLongOpts(longOpts: List<String>): Boolean { println("\n--- Test: areLongOptsValid() ---") println("INPUT") println(" longOpts: $longOpts") println("OUTPUT") return try { println(" " + GetOpt.parseLongOpts(longOpts)) true } catch (e: Exception) { println(" " + e.message) false } }
0
Kotlin
0
0
9c41f0a5ea6d63e15feb6aa76785d0cf3620709e
2,161
kt-getopt
MIT License
fileboxlib/src/main/java/com/lyrebirdstudio/fileboxlib/security/CryptoImpl.kt
lyrebirdstudio
238,207,373
false
null
package com.lyrebirdstudio.fileboxlib.security import android.content.Context import com.facebook.crypto.Entity import com.lyrebirdstudio.fileboxlib.core.CryptoType import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import java.io.* internal class CryptoImpl(context: Context) : Crypto { private val appContext: Context = context.applicationContext private val crypto = ConcealInitializer.initialize(appContext) override fun encrypt(originFile: File, destinationFile: File): Flowable<CryptoProcess> { return Flowable.create( { it.onNext(CryptoProcess.processing(0)) try { val fileOutputStream = BufferedOutputStream(FileOutputStream(destinationFile)) val cryptoOutputStream = crypto.getCipherOutputStream(fileOutputStream, Entity.create("entity_id")) val inputFileStream = FileInputStream(originFile) val available = inputFileStream.available() val buf = ByteArray(1024) var read: Int = inputFileStream.read(buf) var totalRead = read while (read > 0) { cryptoOutputStream.write(buf, 0, read) read = inputFileStream.read(buf) totalRead += read val percent = totalRead * 100 / available it.onNext(CryptoProcess.processing(percent)) } cryptoOutputStream.close() it.onNext(CryptoProcess.complete(destinationFile)) it.onComplete() } catch (e: Exception) { it.onNext(CryptoProcess.error(destinationFile, e)) it.onComplete() } }, BackpressureStrategy.BUFFER ) } override fun decrypt(originFile: File, destinationFile: File): Flowable<CryptoProcess> { return Flowable.create({ it.onNext(CryptoProcess.processing(0)) try { val fileOutputStream = FileOutputStream(destinationFile) val fileInputStream = FileInputStream(originFile) val fileCryptoInputStream = crypto.getCipherInputStream(fileInputStream, Entity.create("entity_id")) val available = fileCryptoInputStream.available() val buffer = ByteArray(1024) var read: Int = fileCryptoInputStream.read(buffer) var totalRead = read while (read != -1) { fileOutputStream.write(buffer, 0, read) read = fileCryptoInputStream.read(buffer) totalRead += read val percent = totalRead * 100 / available it.onNext(CryptoProcess.processing(percent)) } fileCryptoInputStream.close() it.onNext(CryptoProcess.complete(destinationFile)) it.onComplete() } catch (e: Exception) { it.onNext(CryptoProcess.error(destinationFile, e)) it.onComplete() } }, BackpressureStrategy.BUFFER) } override fun toEncryptedStream(outputStream: OutputStream): OutputStream { return crypto.getCipherOutputStream(outputStream, Entity.create("entity_id")) } override fun toDecryptedStream(inputStream: InputStream): InputStream { return crypto.getCipherInputStream(inputStream, Entity.create("entity_id")) } override fun isInitialized(): Boolean { return ConcealInitializer.isInitialized() } override fun getCryptoType(): CryptoType { return CryptoType.CONCEAL } }
3
Kotlin
24
312
0cfaa0d0b05ed5d25d87eed88de224f630ba91e6
3,849
filebox
Apache License 2.0
app/src/main/java/org/rfcx/companion/view/detail/image/AddImageRepository.kt
rfcx
244,311,338
false
{"Kotlin": 736787}
package org.rfcx.companion.view.detail.image import org.rfcx.companion.entity.DeploymentImage import org.rfcx.companion.repo.local.LocalDataHelper import org.rfcx.companion.view.deployment.Image class AddImageRepository( private val localDataHelper: LocalDataHelper ) { fun getImages(deploymentId: Int): List<DeploymentImage> { return localDataHelper.getDeploymentImageLocalDb().getImageByDeploymentId(deploymentId) } fun saveImages(images: List<Image>, deploymentId: Int) { return localDataHelper.getDeploymentImageLocalDb().insertImage(deploymentId, images) } }
15
Kotlin
0
0
850c7a16e7936d1ce072d59e17dbc2a470200b3d
604
companion-android
Apache License 2.0
lib/src/main/java/com/robertlevonyan/components/picker/contracts/FilePickerContract.kt
robertlevonyan
125,543,555
false
null
package com.robertlevonyan.compose.picker.contracts import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import androidx.activity.result.contract.ActivityResultContract internal class FilePickerContract : ActivityResultContract<Unit, List<Uri>>() { override fun createIntent(context: Context, input: Unit): Intent = Intent(Intent.ACTION_GET_CONTENT).setType("*/*").putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) override fun parseResult(resultCode: Int, intent: Intent?): List<Uri> = if (resultCode != Activity.RESULT_OK || intent == null) { emptyList() } else { val uris = mutableListOf<Uri>() intent.data ?.let { uris.add(it) } ?: intent.clipData?.let { clipData -> for (i in 0 until clipData.itemCount) { uris.add(clipData.getItemAt(i).uri) } } uris } }
0
Kotlin
30
132
550aa1c23494330a4dc15c5c2589155a37bae45e
902
MediaPicker
Apache License 2.0
tracer-webmvc/src/main/kotlin/malibu/tracer/webmvc/TracerWebMvcConfigurer.kt
adrenalinee
640,443,973
false
null
package malibu.tracer.webmvc interface TracerWebMvcConfigurer { fun configureTracerWebflux(context: TracerWebMvcContextApplyer) }
0
Kotlin
0
0
2e8b3a7f2cfcea2d7641fb0df3b8a769be646a8a
135
tracer
Apache License 2.0
feature-account-api/src/main/java/io/novafoundation/nova/feature_account_api/presenatation/account/add/ImportAccountPayload.kt
novasamatech
415,834,480
false
{"Kotlin": 7667438, "Java": 14723, "JavaScript": 425}
package com.dfinn.wallet.feature_account_api.presenatation.account.add import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize class ImportAccountPayload( val type: SecretType, val addAccountPayload: AddAccountPayload, ) : Parcelable
13
Kotlin
6
9
dea9f1144c1cbba1d876a9bb753f8541da38ebe0
268
nova-wallet-android
Apache License 2.0
json/tests/test/com/jetbrains/jsonSchema/intentions/AddOptionalPropertiesIntentionTest.kt
mallowigi
674,965,631
true
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.jsonSchema.intentions import com.intellij.codeInsight.intention.impl.ShowIntentionActionsHandler import com.intellij.json.JsonTestCase import com.jetbrains.jsonSchema.JsonSchemaHighlightingTestBase.registerJsonSchema import com.jetbrains.jsonSchema.impl.fixes.AddOptionalPropertiesIntention import org.intellij.lang.annotations.Language import org.junit.Assert class AddOptionalPropertiesIntentionTest : JsonTestCase() { private fun doTest(@Language("JSON") before: String, @Language("JSON") after: String) { registerJsonSchema( myFixture, """ { "properties": { "a": { "type": "object", "properties": { "b" : { "type": "object", "properties": { "c": { "type": "string" }, "d": { "type": "integer" } } } } }, "e": { "type": "object" } } } """.trimIndent(), "json" ) { true } myFixture.configureByText("test.json", before) val intention = myFixture.getAvailableIntention(AddOptionalPropertiesIntention().text)!! ShowIntentionActionsHandler.chooseActionAndInvoke(myFixture.file, myFixture.editor, intention, intention.text) myFixture.checkResult(after) } fun `test insert properties in empty object`() { doTest( """ {<caret>} """.trimIndent(), """ { "a": {}, "e": {} } """.trimIndent() ) } fun `test insert properties in non-empty object`() { doTest( """ { "a": {}, <caret> } """.trimIndent(), """ { "a": {}, "e": {} } """.trimIndent() ) } fun `test insert properties in deep object`() { doTest( """ { "a": { "b": { <caret> } } } """.trimIndent(), """ { "a": { "b": { "c": "", "d": 0 } } } """.trimIndent() ) } fun `test intention unavailable if all properties are present`() { registerJsonSchema(myFixture, """ { "properties": { "a" : {} } } """.trimIndent(), "json") { true } myFixture.configureByText("test.json", """ { "a": 123 <caret> } """.trimIndent()) Assert.assertNull(myFixture.getAvailableIntention (AddOptionalPropertiesIntention().text)) } }
0
null
0
0
fc993c389f66042dad1e71451b6c6eb0bc03e4c2
2,879
intellij-community
Apache License 2.0
src/main/kotlin/no/nav/klage/oppgave/api/view/History.kt
navikt
297,650,936
false
null
package no.nav.klage.oppgave.api.view import no.nav.klage.kodeverk.FlowState import java.time.LocalDate import java.time.LocalDateTime data class TildelingEvent( val saksbehandler: String?, val fradelingReasonId: String?, val hjemmelIdList: List<String>?, ) data class MedunderskriverEvent( val medunderskriver: String?, //nullable b/c possible missing history initially val flow: FlowState? ) data class RolEvent( val rol: String?, val flow: FlowState ) data class SattPaaVentEvent( val from: LocalDate, val to: LocalDate, val reason: String ) data class FeilregistrertEvent( val reason: String ) data class KlagerEvent( val part: Part, ) data class FullmektigEvent( val part: Part?, ) data class FerdigstiltEvent( val avsluttetAvSaksbehandler: LocalDateTime, ) data class Part( val id: String, val name: String, val type: BehandlingDetaljerView.IdType ) interface WithPrevious<T>: BaseEvent<T> { val previous: BaseEvent<T> } data class HistoryEventWithPrevious<T>( override val type: HistoryEventType, override val timestamp: LocalDateTime, override val actor: String?, override val event: T?, override val previous: BaseEvent<T> ): WithPrevious<T> interface BaseEvent<T> { val type: HistoryEventType val timestamp: LocalDateTime val actor: String? val event: T? } data class HistoryEvent<T>( override val type: HistoryEventType, override val timestamp: LocalDateTime, override val actor: String?, override val event: T? ): BaseEvent<T> data class HistoryResponse( val tildeling: List<WithPrevious<TildelingEvent>>, val medunderskriver: List<WithPrevious<MedunderskriverEvent>>, val rol: List<WithPrevious<RolEvent>>, val klager: List<WithPrevious<KlagerEvent>>, val fullmektig: List<WithPrevious<FullmektigEvent>>, val sattPaaVent: List<WithPrevious<SattPaaVentEvent>>, val ferdigstilt: List<WithPrevious<FerdigstiltEvent>>, val feilregistrert: List<WithPrevious<FeilregistrertEvent>> ) enum class HistoryEventType { TILDELING, MEDUNDERSKRIVER, ROL, KLAGER, FULLMEKTIG, SATT_PAA_VENT, FERDIGSTILT, FEILREGISTRERT, }
3
null
4
1
de0724ab0e62c0ed93a1406044ddc880ef46d80e
2,226
kabal-api
MIT License
app/src/main/java/com/rodrigodominguez/mixanimationsmotionlayout/verticalstackcards/VerticalStackCardsDemoActivity.kt
rodrigomartind
265,013,640
false
null
package com.rodrigodominguez.mixanimationsmotionlayout.verticalstackcards import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.constraintlayout.motion.widget.MotionLayout import androidx.constraintlayout.motion.widget.TransitionAdapter import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.rodrigodominguez.mixanimationsmotionlayout.R import kotlinx.android.synthetic.main.activity_vertical_stack_cards_demo.* class VerticalStackCardsDemoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_vertical_stack_cards_demo) val viewModel = ViewModelProviders .of(this) .get(VerticalStackCardViewModel::class.java) viewModel .modelStream .observe(this, Observer { bindCard(it) }) verticalMotionLayout.setTransitionListener(object : TransitionAdapter() { override fun onTransitionCompleted(motionLayout: MotionLayout?, currentId: Int) { motionLayout?.post { when (currentId) { R.id.end -> { verticalMotionLayout.progress = 0f verticalMotionLayout.progress = 0f viewModel.swipe() } } } } }) } private fun bindCard(it: VerticalCardModel) { cardDetail.setCardBackgroundColor(it.detailCard.backgroundColor) cardTop.setCardBackgroundColor(it.cardTop.backgroundColor) cardMiddle.setCardBackgroundColor(it.cardMiddle.backgroundColor) cardBottom.setCardBackgroundColor(it.cardBottom.backgroundColor) cardEnd.setCardBackgroundColor(it.cardEnd.backgroundColor) cardTransparent.setCardBackgroundColor(it.cardTransparent.backgroundColor) } }
1
Kotlin
63
610
17e3d8ad36a3b9806c828bd03cc71eb37af789dc
2,017
MixAnimationsMotionLayout
Apache License 2.0
app/src/main/java/com/macs/revitalize/presentation/settings/innerFragments/FragmentSettingsAbout.kt
Raghu0203
634,680,689
false
null
package com.macs.revitalize.presentation.settings.innerFragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.macs.revitalize.R import com.macs.revitalize.databinding.FragmentSettingsAboutBinding class FragmentSettingsAbout : Fragment() { private var _binding: FragmentSettingsAboutBinding?= null private val binding: FragmentSettingsAboutBinding get() = _binding!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment _binding = FragmentSettingsAboutBinding.inflate(inflater, container, false) binding.settingsAboutGoBack.setOnClickListener{ this.findNavController().navigate(FragmentSettingsAboutDirections.actionFragmentSettingsAboutToSettingsFragment()) } return binding.root } }
0
Kotlin
0
0
b777a9092bf754fbcb3900036b3908733fc95e42
1,167
Revitalize
Creative Commons Zero v1.0 Universal
app/src/main/java/com/padcmyanmar/miforum/Data/HealthCareInfoVO.kt
LinBoBoAung
140,725,686
false
{"Kotlin": 18810}
package com.padcmyanmar.miforum.Data import com.google.gson.annotations.SerializedName class HealthCareInfoVO(@SerializedName("id") var healthCareId: Int = 0, @SerializedName("title") var title: String = "", @SerializedName("image") var image: String = "", @SerializedName("author") var author: AuthorVO? = null, @SerializedName("short-description") var shortDescription: String = "", @SerializedName("published-date") var publishedDate: String = "", @SerializedName("complete-url") var completeUrl: String = "", @SerializedName("info-type") var infoType: String = "")
0
Kotlin
0
0
a802e3009be31c95ba4c68bb3d150b936bff80be
921
MiForum
MIT License
app/src/main/java/com/padcmyanmar/miforum/Data/HealthCareInfoVO.kt
LinBoBoAung
140,725,686
false
{"Kotlin": 18810}
package com.padcmyanmar.miforum.Data import com.google.gson.annotations.SerializedName class HealthCareInfoVO(@SerializedName("id") var healthCareId: Int = 0, @SerializedName("title") var title: String = "", @SerializedName("image") var image: String = "", @SerializedName("author") var author: AuthorVO? = null, @SerializedName("short-description") var shortDescription: String = "", @SerializedName("published-date") var publishedDate: String = "", @SerializedName("complete-url") var completeUrl: String = "", @SerializedName("info-type") var infoType: String = "")
0
Kotlin
0
0
a802e3009be31c95ba4c68bb3d150b936bff80be
921
MiForum
MIT License
App/src/main/kotlin/com/simiacryptus/skyenet/AppServer.kt
SimiaCryptus
740,211,936
false
{"Kotlin": 20319}
package com.simiacryptus.skyenet import com.simiacryptus.skyenet.apps.coding.AwsCodingApp import com.simiacryptus.skyenet.apps.coding.BashCodingApp import com.simiacryptus.skyenet.webui.application.ApplicationDirectory import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider import software.amazon.awssdk.regions.Region import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest open class AppServer( localName: String, publicName: String, port: Int ) : ApplicationDirectory( localName = localName, publicName = publicName, port = port ) { companion object { @JvmStatic fun main(args: Array<String>) { AppServer(localName = "localhost", "localhost", 37600)._main(args) } } // private val sparkConf = SparkConf().setMaster("local[*]").setAppName("Spark Coding Assistant") override val childWebApps by lazy { listOf( ChildWebApp("/aws_coder", AwsCodingApp()), ChildWebApp("/bash", BashCodingApp()), ) } private fun fetchPlaintextSecret(secretArn: String, region: Region) = SecretsManagerClient.builder() .region(region) .credentialsProvider(DefaultCredentialsProvider.create()) .build().getSecretValue( GetSecretValueRequest.builder() .secretId(secretArn) .build() ).secretString() }
0
Kotlin
0
0
6dfa7261b4d4c8d139316d3afa82ec40392f6370
1,421
SkyenetCommander
Apache License 2.0
src/test/kotlin/org/wfanet/measurement/api/v2alpha/EventTemplateTest.kt
world-federation-of-advertisers
349,561,061
false
null
// Copyright 2020 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.api.v2alpha import com.google.common.truth.Truth.assertThat import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.api.v2alpha.event_templates.testing.TestVideoTemplate import org.wfanet.measurement.api.v2alpha.event_templates.testing.TestVideoTemplate.AgeRange import org.wfanet.measurement.api.v2alpha.event_templates.testing.TestVideoTemplate.ViewDuration @RunWith(JUnit4::class) class EventTemplateTest { @Test fun `populated fields contain correct values`() { val eventTemplate = EventTemplate(TestVideoTemplate.getDescriptor()) assertThat(eventTemplate.name).isEqualTo("test_video_template") assertThat(eventTemplate.displayName).isEqualTo("Video Ad") assertThat(eventTemplate.description).isEqualTo("A simple Event Template for a video ad.") assertThat(eventTemplate.eventFields).contains(EventField(AgeRange.getDescriptor())) assertThat(eventTemplate.eventFields).contains(EventField(ViewDuration.getDescriptor())) } @Test fun `init throws exception if EventTemplate annotation missing`() { assertFailsWith( IllegalArgumentException::class, "Descriptor does not have EventTemplate annotation" ) { EventTemplate(AgeRange.getDescriptor()) } } }
61
null
7
22
b3af7ed4161f31077eaafb6cfddc58dd1ad956f0
1,962
cross-media-measurement
Apache License 2.0
common/src/main/java/io/novafoundation/nova/common/utils/KotlinExt.kt
novasamatech
496,649,319
false
null
package io.novafoundation.nova.common.utils import android.net.Uri import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job import kotlinx.coroutines.async import java.io.ByteArrayOutputStream import java.io.InputStream import java.math.BigDecimal import java.math.BigInteger import java.math.MathContext import java.util.UUID import java.util.concurrent.TimeUnit import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlin.math.sqrt private val PERCENTAGE_MULTIPLIER = 100.toBigDecimal() fun BigDecimal.fractionToPercentage() = this * PERCENTAGE_MULTIPLIER fun Double.percentageToFraction() = this / PERCENTAGE_MULTIPLIER.toDouble() fun BigDecimal.percentageToFraction() = this.divide(PERCENTAGE_MULTIPLIER, MathContext.DECIMAL64) infix fun Int.floorMod(divisor: Int) = Math.floorMod(this, divisor) /** * Compares two BigDecimals taking into account only values but not scale unlike `==` operator */ infix fun BigDecimal.hasTheSaveValueAs(another: BigDecimal) = compareTo(another) == 0 fun BigInteger.intSqrt() = sqrt(toDouble()).toLong().toBigInteger() val BigDecimal.isZero: Boolean get() = signum() == 0 val BigDecimal.isPositive: Boolean get() = signum() > 0 val BigDecimal.isNonNegative: Boolean get() = signum() >= 0 val BigInteger.isZero: Boolean get() = signum() == 0 fun BigInteger?.orZero(): BigInteger = this ?: BigInteger.ZERO fun BigDecimal?.orZero(): BigDecimal = this ?: 0.toBigDecimal() fun BigInteger.divideToDecimal(divisor: BigInteger, mathContext: MathContext = MathContext.DECIMAL64): BigDecimal { return toBigDecimal().divide(divisor.toBigDecimal(), mathContext) } fun Long.daysFromMillis() = TimeUnit.MILLISECONDS.toDays(this) inline fun <T> Collection<T>.sumByBigInteger(extractor: (T) -> BigInteger) = fold(BigInteger.ZERO) { acc, element -> acc + extractor(element) } suspend operator fun <T> Deferred<T>.invoke() = await() inline fun <T> List<T>.sumByBigDecimal(extractor: (T) -> BigDecimal) = fold(BigDecimal.ZERO) { acc, element -> acc + extractor(element) } inline fun <reified T> Any?.castOrNull(): T? { return this as? T } fun <K, V> Map<K, V>.reversed() = HashMap<V, K>().also { newMap -> entries.forEach { newMap[it.value] = it.key } } fun <T> Iterable<T>.isAscending(comparator: Comparator<T>) = zipWithNext().all { (first, second) -> comparator.compare(first, second) < 0 } fun <T> Result<T>.requireException() = exceptionOrNull()!! fun <T> Result<T>.requireValue() = getOrThrow()!! fun InputStream.readText() = bufferedReader().use { it.readText() } fun <T> List<T>.second() = get(1) fun <E : Enum<E>> Collection<Enum<E>>.anyIs(value: E) = any { it == value } fun Int.quantize(factor: Int) = this - this % factor @Suppress("UNCHECKED_CAST") inline fun <K, V, R> Map<K, V>.mapValuesNotNull(crossinline mapper: (Map.Entry<K, V>) -> R?): Map<K, R> { return mapValues(mapper) .filterNotNull() } @Suppress("UNCHECKED_CAST") inline fun <K, V> Map<K, V?>.filterNotNull(): Map<K, V> { return filterValues { it != null } as Map<K, V> } fun String.bigIntegerFromHex() = removeHexPrefix().toBigInteger(16) fun String.intFromHex() = removeHexPrefix().toInt(16) /** * Complexity: O(n * log(n)) */ // TODO possible to optimize fun List<Double>.median(): Double = sorted().let { val middleRight = it[it.size / 2] val middleLeft = it[(it.size - 1) / 2] // will be same as middleRight if list size is odd (middleLeft + middleRight) / 2 } fun generateLinearSequence(initial: Int, step: Int) = generateSequence(initial) { it + step } fun <T> Set<T>.toggle(item: T): Set<T> = if (item in this) { this - item } else { this + item } fun <T> List<T>.cycle(): Sequence<T> { var i = 0 return generateSequence { this[i++ % this.size] } } inline fun <T> CoroutineScope.lazyAsync(context: CoroutineContext = EmptyCoroutineContext, crossinline producer: suspend () -> T) = lazy { async(context) { producer() } } inline fun CoroutineScope.invokeOnCompletion(crossinline action: () -> Unit) { coroutineContext[Job]?.invokeOnCompletion { action() } } inline fun <T> Iterable<T>.filterToSet(predicate: (T) -> Boolean): Set<T> = filterTo(mutableSetOf(), predicate) fun String.nullIfEmpty(): String? = if (isEmpty()) null else this fun String.ensureSuffix(suffix: String) = if (endsWith(suffix)) this else this + suffix private val NAMED_PATTERN_REGEX = "\\{([a-zA-z]+)\\}".toRegex() fun String.formatNamed(vararg values: Pair<String, String>) = formatNamed(values.toMap()) fun String.capitalize() = this.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() } /** * Replaces all parts in form of '{name}' to the corresponding value from values using 'name' as a key. * * @return formatted string */ fun String.formatNamed(values: Map<String, String>): String { return NAMED_PATTERN_REGEX.replace(this) { matchResult -> val argumentName = matchResult.groupValues.second() values[argumentName] ?: "null" } } inline fun <T> T?.defaultOnNull(lazyProducer: () -> T): T { return this ?: lazyProducer() } fun <T> List<T>.modified(modification: T, condition: (T) -> Boolean): List<T> { return modified(indexOfFirst(condition), modification) } fun <T> List<T>.removed(condition: (T) -> Boolean): List<T> { return toMutableList().apply { removeAll(condition) } } fun <T> List<T>.added(toAdd: T): List<T> { return toMutableList().apply { add(toAdd) } } fun <T> List<T>.prepended(toPrepend: T): List<T> { return toMutableList().apply { add(0, toPrepend) } } fun <T> List<T>.modified(index: Int, modification: T): List<T> { val newList = this.toMutableList() newList[index] = modification return newList } fun <K, V> Map<K, V>.inserted(key: K, value: V): Map<K, V> { return toMutableMap().apply { put(key, value) } } inline fun <T, R> Iterable<T>.mapToSet(mapper: (T) -> R): Set<R> = mapTo(mutableSetOf(), mapper) inline fun <T, R : Any> Iterable<T>.mapNotNullToSet(mapper: (T) -> R?): Set<R> = mapNotNullTo(mutableSetOf(), mapper) fun <T> List<T>.indexOfFirstOrNull(predicate: (T) -> Boolean) = indexOfFirst(predicate).takeIf { it >= 0 } @Suppress("IfThenToElvis") fun ByteArray?.optionalContentEquals(other: ByteArray?): Boolean { return if (this == null) { other == null } else { this.contentEquals(other) } } fun Uri.Builder.appendNullableQueryParameter(name: String, value: String?) = apply { value?.let { appendQueryParameter(name, value) } } fun ByteArray.dropBytes(count: Int) = copyOfRange(count, size) fun ByteArray.dropBytesLast(count: Int) = copyOfRange(0, size - count) fun ByteArray.chunked(count: Int): List<ByteArray> = toList().chunked(count).map { it.toByteArray() } fun buildByteArray(block: (ByteArrayOutputStream) -> Unit): ByteArray = ByteArrayOutputStream().apply { block(this) }.toByteArray() fun String.toUuid() = UUID.fromString(this) val Int.kilobytes: BigInteger get() = this.toBigInteger() * 1024.toBigInteger() operator fun ByteArray.compareTo(other: ByteArray): Int { if (size != other.size) { return size - other.size } for (i in 0 until size) { val result = this[i].compareTo(other[i]) if (result != 0) { return result } } return 0 } fun ByteArrayComparator() = Comparator<ByteArray> { a, b -> a.compareTo(b) }
5
null
9
28
fcd118ab5cbedded709ec062ae5d4bc890aaf96d
7,476
nova-android-app
Apache License 2.0
src/main/kotlin/example4/examples.kt
digital-magic-io
561,851,043
false
{"Kotlin": 8416, "Java": 5897}
package example4 sealed class KEither<out A, out B> { data class Left<A>(val value: A): KEither<A, Nothing>() data class Right<B>(val value: B): KEither<Nothing, B>() } @JvmInline value class KError(val value: String) typealias Validated<T> = KEither<KError, T> typealias Validator<T> = (T) -> Validated<T> val emptyStringValidator: Validator<String> = { value -> value.takeUnless { value.isEmpty() } ?.let { KEither.Right(it) } ?: KEither.Left(KError("Value can't be empty!")) } @JvmInline value class KNonEmptyString private constructor(val value: String) { companion object { fun of(value: String): Validated<String> = emptyStringValidator(value) } }
0
Kotlin
0
0
8cf420c53f79a6e86a5b072b6d043589a5094e63
696
type-driven-kotlin
MIT License
examples/src/tl/telegram/auth/AuthLoginToken.kt
andreypfau
719,064,910
false
{"Kotlin": 62259}
// This file is generated by TLGenerator.kt // Do not edit manually! package tl.telegram.auth import io.github.andreypfau.tl.serialization.Base64ByteStringSerializer import io.github.andreypfau.tl.serialization.TLCombinatorId import kotlin.jvm.JvmName import kotlinx.io.bytestring.ByteString import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonClassDiscriminator @Serializable @JsonClassDiscriminator("@type") public sealed interface AuthLoginToken { @Serializable @SerialName("auth.loginToken") @TLCombinatorId(0x629F1980) public data class LoginToken( @get:JvmName("expires") public val expires: Int, @get:JvmName("token") public val token: @Serializable(Base64ByteStringSerializer::class) ByteString, ) : AuthLoginToken { public companion object } @Serializable @SerialName("auth.loginTokenMigrateTo") @TLCombinatorId(0x68E9916) public data class LoginTokenMigrateTo( @SerialName("dc_id") @get:JvmName("dcId") public val dcId: Int, @get:JvmName("token") public val token: @Serializable(Base64ByteStringSerializer::class) ByteString, ) : AuthLoginToken { public companion object } @Serializable @SerialName("auth.loginTokenSuccess") @TLCombinatorId(0x390D5C5E) public data class LoginTokenSuccess( @get:JvmName("authorization") public val authorization: AuthAuthorization, ) : AuthLoginToken { public companion object } public companion object }
0
Kotlin
0
1
11f05ad1f977235e3e360cd6f6ada6f26993208e
1,609
tl-kotlin
MIT License
src/main/kotlin/io/github/tundraclimate/clib/serialize/VectorSerializer.kt
TundraClimate
539,458,885
false
null
package io.github.tundraclimate.clib.serialize import org.bukkit.util.Vector import org.bukkit.util.io.BukkitObjectOutputStream import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder import java.io.ByteArrayOutputStream class VectorSerializer: Base64Serializer<Vector> { override fun encode(t: Vector): String? { val os = ByteArrayOutputStream() val bos = BukkitObjectOutputStream(os) return try { bos.writeObject(t) Base64Coder.encodeLines(os.toByteArray()) } catch (e: Exception) { null } finally { os.close() bos.close() } } }
0
Kotlin
0
0
81e7e68ea008916554683377e25f5f1cd3aa0798
656
ColdLib-Reloaded
MIT License
src/main/kotlin/org/datacraft/loaders/CharClassLoader.kt
bbux-dev
783,882,166
false
{"Kotlin": 198619}
package org.datacraft.loaders import org.datacraft.* import org.datacraft.models.ValueSupplierLoader open class CharClassLoader : ValueSupplierLoader<String> { override fun typeNames(): List<String> = listOf("char_class") override fun load(spec: FieldSpec, loader: Loader): ValueSupplier<String> { if (spec.data == null) { throw SpecException("Data is a required field for char_class type: $spec") } var data = spec.data val config = (spec.config ?: mapOf()).toMutableMap() if (data is String && CharClassMappings.CLASS_MAPPING.containsKey(data)) { data = CharClassMappings.CLASS_MAPPING[data]!! } if (data is List<*>) { val newData = data.map { datum -> if (datum is String && CharClassMappings.CLASS_MAPPING.containsKey(datum)) { CharClassMappings.CLASS_MAPPING[datum]!! } else { datum.toString() } } data = newData.joinToString("") } if (!config.containsKey("join_with")) { config["join_with"] = Registries.getDefault<String>("char_class_join_with") } var modifiedData = data as String // Exclude characters if 'exclude' key exists in config if (config.containsKey("exclude")) { val exclude = config["exclude"] as String modifiedData = excludeCharacters(modifiedData, exclude) } val supplier = Suppliers.characterClass( modifiedData, mean = gitConfigAsDouble(config, "mean"), stddev = gitConfigAsDouble(config, "stddev"), count = gitConfigAsInt(config, "count"), min = gitConfigAsInt(config, "min"), max = gitConfigAsInt(config, "max") ) // Escape characters if 'escape' key exists in config if (config.containsKey("escape")) { val escape = config["escape"] as String val escapeStr = config.getOrDefault("escape_str", "\\") as String val replacements: Map<String, String> = escape.associate { it.toString() to "$escapeStr$it" } return Suppliers.replace(supplier, replacements) } return supplier } private fun excludeCharacters(data: String, exclude: String): String { return data.filterNot { it in exclude } } }
0
Kotlin
0
1
725208559706a035f1f8902308d660ce67c51edc
2,417
datacraft-jvm
MIT License
composeApp/src/commonMain/kotlin/com/akexorcist/kotlin/multiplatform/ui/component/Dimensions.kt
akexorcist
805,908,311
false
{"Kotlin": 283665, "Swift": 1625, "Objective-C": 1265, "Ruby": 872, "HTML": 470, "JavaScript": 325, "CSS": 122}
package com.akexorcist.kotlin.multiplatform.ui.component import androidx.compose.ui.unit.dp val VerticalScreenPadding = 64.dp val HorizontalScreenPadding = 96.dp
0
Kotlin
1
7
8f347d12a11b69b700d39a470f556c5c6210fb43
163
kotlin-multiplatform-presentation
Apache License 2.0
app/src/main/java/com/example/rangtech/ui/Color.kt
sumit-kotal
812,948,251
false
{"Kotlin": 26150}
package com.example.rangtech.ui import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5) val Teal700 = Color(0xFF018786) val White = Color(0xFFFFFFFF) val Black = Color(0xFF000000)
0
Kotlin
0
0
7e74a50c99001f89e2d08b93fe9b1562fd22d0c6
302
RangTechnologies
MIT License
app/src/main/java/com/abbaraees/weatherly/data/Network.kt
Abbaraees
777,191,517
false
{"Kotlin": 53609}
package com.abbaraees.weatherly.data data class WeatherDataNetwork( val weather: List<Weather>, val base: String, val main: Main, val visibility: Int, val dt: Long, val sys: Sys, val timezone: Int, val id: Int, val name: String, val cod: Int ) data class Weather( val id: Int, val main: String, val description: String, val icon: String ) data class Main( val temp: Double, val feels_like: Double, val temp_min: Double, val temp_max: Double, val pressure: Int, val humidity: Int, val sea_level: Int, val grnd_level: Int ) data class Sys( val country: String, val sunrise: Long, val sunset: Long ) data class LocationResponse( val results: List<Location>, val generationtime_ms: Double ) data class Location( val id: Int, val name: String, val latitude: Double, val longitude: Double, val elevation: Double, val feature_code: String, val country_code: String, val admin1_id: Int, val admin2_id: Int, val admin3_id: Int, val timezone: String, val population: Int, val country_id: Int, val country: String, val admin1: String, val admin2: String, val admin3: String )
0
Kotlin
0
0
7c7d7601fbef45bcfcebd3276c1090fbdc0279e1
1,251
weatherly
Apache License 2.0
adapter_example/src/main/kotlin/com/wuhenzhizao/adapter/example/ui/SingleTypeListViewFragment.kt
wuhenzhizao
104,157,622
false
null
package com.wuhenzhizao.adapter.example.ui import android.widget.CheckBox import android.widget.TextView import co.metalab.asyncawait.async import com.google.gson.Gson import com.wuhenzhizao.adapter.* import com.wuhenzhizao.adapter.example.R import com.wuhenzhizao.adapter.example.bean.Province import com.wuhenzhizao.adapter.example.bean.ProvinceList import com.wuhenzhizao.adapter.example.databinding.FragmentSingleTypeListViewBinding import com.wuhenzhizao.adapter.extension.getItems /** * Created by liufei on 2017/12/13. */ class SingleTypeListViewFragment : BaseFragment<FragmentSingleTypeListViewBinding>() { private lateinit var adapter: ListViewAdapter<Province> private lateinit var list: ProvinceList override fun getContentViewId(): Int = R.layout.fragment_single_type_list_view override fun initViews() { async { await { val json = getString(R.string.provinces) list = Gson().fromJson<ProvinceList>(json, ProvinceList::class.java) } bindAdapter() } } private fun bindAdapter() { adapter = ListViewAdapter(context, list.provinceList) .match(Province::class, R.layout.item_single_type_list_view) .holderCreateListener { } .holderBindListener { holder, position -> val province = adapter.getItem(position) holder.withView<TextView>(R.id.tv, { text = province.name }) .withView<CheckBox>(R.id.cb, { isChecked = province.checked }) } .clickListener { holder, position -> val province = adapter.getItem(position) showToast("position $position, ${province.name} clicked") adapter.getItems().forEachIndexed { index, province -> province.checked = (index == position) } adapter.notifyDataSetChanged() } .longClickListener { holder, position -> val province = adapter.getItem(position) showToast("position $position, ${province.name} long clicked") } .attach(binding.lv) } }
1
Kotlin
16
146
1d40fde543e87891a80f9e06170631c98c6ee57d
2,297
kotlin-adapter
Apache License 2.0
examples/src/commonMain/kotlin/org/kobjects/parserlib/examples/expressions/Evaluable.kt
kobjects
455,979,563
false
{"Kotlin": 17001, "Ruby": 1596}
package org.kobjects.parsek.examples.expressions interface Evaluable { fun precedence(): Int = 10 // No parens required by default fun eval(ctx: Context): Any fun evalDouble(context: Context): Double { val value = eval(context) return if (value is Number) value.toDouble() else if (value is Boolean) { if (value) 1.0 else 0.0 } else throw IllegalArgumentException("Number expected; got: 'value'") } fun evalInt(context: Context): Int = (eval(context) as Number).toInt() fun evalString(context: Context): String = eval(context) as String fun is0() = (this is Literal) && value is Number && value.toDouble() == 0.0 fun is1() = (this is Literal) && value is Number && value.toDouble() == 1.0 fun isBuiltin(kind: Builtin.Kind) = (this is Builtin) && this.kind == kind fun isIntLiteral() = (this is Literal) && this.value is Number && this.value.toDouble() == this.value.toInt().toDouble() fun parenthesize(parentPrecedence: Int) = if (parentPrecedence > precedence()) "($this)" else toString() fun evalBoolean(context: Context): Boolean = evalDouble(context) != 0.0 }
0
Kotlin
0
3
ff39a8d98a1228c498bbbb1f5f97db2cb65e80a3
1,193
parsek
Apache License 2.0
examples/src/commonMain/kotlin/org/kobjects/parserlib/examples/expressions/Evaluable.kt
kobjects
455,979,563
false
{"Kotlin": 17001, "Ruby": 1596}
package org.kobjects.parsek.examples.expressions interface Evaluable { fun precedence(): Int = 10 // No parens required by default fun eval(ctx: Context): Any fun evalDouble(context: Context): Double { val value = eval(context) return if (value is Number) value.toDouble() else if (value is Boolean) { if (value) 1.0 else 0.0 } else throw IllegalArgumentException("Number expected; got: 'value'") } fun evalInt(context: Context): Int = (eval(context) as Number).toInt() fun evalString(context: Context): String = eval(context) as String fun is0() = (this is Literal) && value is Number && value.toDouble() == 0.0 fun is1() = (this is Literal) && value is Number && value.toDouble() == 1.0 fun isBuiltin(kind: Builtin.Kind) = (this is Builtin) && this.kind == kind fun isIntLiteral() = (this is Literal) && this.value is Number && this.value.toDouble() == this.value.toInt().toDouble() fun parenthesize(parentPrecedence: Int) = if (parentPrecedence > precedence()) "($this)" else toString() fun evalBoolean(context: Context): Boolean = evalDouble(context) != 0.0 }
0
Kotlin
0
3
ff39a8d98a1228c498bbbb1f5f97db2cb65e80a3
1,193
parsek
Apache License 2.0
src/main/kotlin/repository/api.kt
TVBlackman1
722,028,675
false
{"Kotlin": 20004}
package repository object ApiRoutes { private const val BASE_URL = "http://172.20.180.208:8080" const val EXPERIMENTS = "$BASE_URL/experiments" }
0
Kotlin
0
0
7952844d322ed9a9eae501a0d16712d84ae1a582
153
mechstat-app-ui
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonertonomisupdate/incentives/IncentivesDataRepairResource.kt
ministryofjustice
445,140,246
false
{"Kotlin": 1290877, "Mustache": 1803, "Dockerfile": 1118}
package uk.gov.justice.digital.hmpps.prisonertonomisupdate.incentives import com.microsoft.applicationinsights.TelemetryClient import org.springframework.http.HttpStatus import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.prisonertonomisupdate.services.NomisApiService @RestController class IncentivesDataRepairResource( private val incentivesApiService: IncentivesApiService, private val nomisApiService: NomisApiService, private val telemetryClient: TelemetryClient, ) { @PostMapping("/incentives/prisoner/booking-id/{bookingId}/repair") @ResponseStatus(HttpStatus.OK) @PreAuthorize("hasRole('ROLE_NOMIS_INCENTIVES')") suspend fun repair(@PathVariable bookingId: Long) { incentivesApiService.getCurrentIncentive(bookingId)?.also { currentIncentive -> incentivesApiService.getIncentive(currentIncentive.id) .run { nomisApiService.createIncentive( this.bookingId, this.toNomisIncentive(), ).also { nomisIep -> // no need for a mapping - mappings are only used to prevent double creates // this is invoked by a user, so we know it's not a double create telemetryClient.trackEvent( "incentives-repair", mapOf( "nomisBookingId" to bookingId.toString(), "nomisIncentiveSequence" to nomisIep.sequence.toString(), "id" to currentIncentive.id.toString(), "offenderNo" to currentIncentive.prisonerNumber, "iep" to this.iepCode, ), null, ) } } } ?: run { throw IllegalArgumentException("No current incentive for bookingId $bookingId") } } }
0
Kotlin
0
2
01db0c1f1bb49b889a6b6be25955c5f2e16f29b9
2,019
hmpps-prisoner-to-nomis-update
MIT License
ktor-client/ktor-client-plugins/ktor-client-tracing/ktor-client-tracing-stetho/android/src/io/ktor/client/features/tracing/KtorInterceptorResponse.kt
ktorio
40,136,600
false
null
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugin.tracing import com.facebook.stetho.inspector.network.* import io.ktor.client.request.* /** * Implementation of [NetworkEventReporter.InspectorResponse] that is built to work with [StethoTracer]. */ internal class KtorInterceptorResponse( private val requestId: String, private val requestData: HttpRequestData, private val responseData: HttpResponseData ) : NetworkEventReporter.InspectorResponse, NetworkEventReporter.InspectorHeaders by KtorInterceptorHeaders(responseData.headers) { override fun requestId(): String { return requestId } override fun reasonPhrase(): String { return responseData.statusCode.description } override fun url(): String { return requestData.url.toString() } override fun connectionReused(): Boolean { return false } override fun fromDiskCache(): Boolean { return false } override fun connectionId(): Int { return 0 } override fun statusCode(): Int { return responseData.statusCode.value } }
269
Kotlin
806
9,709
9e0eb99aa2a0a6bc095f162328525be1a76edb21
1,216
ktor
Apache License 2.0
test/src/main/kotlin/de/faweizz/poc/util/CodeExecutionPoll.kt
faweizz
390,689,980
false
null
package de.faweizz.poc.util import kotlinx.serialization.Serializable @Serializable data class CodeExecutionPoll( val id: String, val requester: String, val resourceName: String, val name: String, val gitUrl: String, val commitHash: String, val comment: String, val actorsToAccept: Set<String>, val acceptedActors: MutableSet<String>, val declinedActors: MutableSet<String> )
0
Kotlin
0
0
b5b494e81e6643c86d51f884309497bc78715f36
418
florescence
Apache License 2.0
common_component/src/main/java/com/xyoye/common_component/utils/PlayHistoryUtils.kt
xyoye
138,993,190
false
null
package com.xyoye.common_component.utils import com.xyoye.common_component.database.DatabaseManager import com.xyoye.common_component.extension.toText import com.xyoye.data_component.entity.PlayHistoryEntity import com.xyoye.data_component.enums.MediaType import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.util.* import kotlin.time.DurationUnit import kotlin.time.toDuration /** * Created by XYJ on 2021/2/8. */ object PlayHistoryUtils { private val dayName = arrayOf("今天", "昨天", "前天") suspend fun getPlayHistory(uniqueKey: String, mediaType: MediaType): PlayHistoryEntity? { return withContext(Dispatchers.IO) { return@withContext DatabaseManager.instance.getPlayHistoryDao() .getPlayHistory(uniqueKey, mediaType) } } fun formatPlayTime(time: Date): String { if (time.after(Date())) { return time.toText("yyyy-MM-dd HH:mm") } val playTime = time.time.toDuration(DurationUnit.MILLISECONDS) val currentTime = System.currentTimeMillis().toDuration(DurationUnit.MILLISECONDS) val intervalDay = currentTime.minus(playTime).toInt(DurationUnit.DAYS) if (intervalDay in dayName.indices) { return dayName[intervalDay] + " " + time.toText("HH:mm") } return time.toText("yyyy-MM-dd HH:mm") } }
67
null
84
850
f752fdf8cd6457198cfe64493b4caf97b576d0e6
1,383
DanDanPlayForAndroid
Apache License 2.0