code
stringlengths
6
1.04M
language
stringclasses
1 value
AST_depth
int64
-1
40
alphanumeric_fraction
float64
0
0.97
max_line_length
int64
0
1k
avg_line_length
float64
0
171
num_lines
int64
0
4.25k
source
stringclasses
1 value
package net.corda.core.flows import net.corda.core.crypto.Party import net.corda.core.utilities.ALICE import net.corda.core.utilities.BOB import net.corda.core.utilities.DUMMY_NOTARY import net.corda.testing.MOCK_IDENTITY_SERVICE import net.corda.testing.node.MockNetwork import org.junit.Before import org.junit.Test import java.security.PublicKey import kotlin.test.assertNotNull class TxKeyFlowUtilitiesTests { lateinit var net: MockNetwork @Before fun before() { net = MockNetwork(false) net.identities += MOCK_IDENTITY_SERVICE.identities } @Test fun `issue key`() { // We run this in parallel threads to help catch any race conditions that may exist. net = MockNetwork(false, true) // Set up values we'll need val notaryNode = net.createNotaryNode(null, DUMMY_NOTARY.name) val aliceNode = net.createPartyNode(notaryNode.info.address, ALICE.name) val bobNode = net.createPartyNode(notaryNode.info.address, BOB.name) val bobKey: Party = bobNode.services.myInfo.legalIdentity // Run the flows bobNode.registerServiceFlow(TxKeyFlow.Requester::class) { TxKeyFlow.Provider(it) } val requesterFlow = aliceNode.services.startFlow(TxKeyFlow.Requester(bobKey)) // Get the results val actual: PublicKey = requesterFlow.resultFuture.get().first assertNotNull(actual) } }
kotlin
15
0.717407
92
32.785714
42
starcoderdata
<reponame>allen-hsu/migo<gh_stars>0 package com.allen.migo.logic class MockExpiredPassProvider : PassportProvider { override fun expiredTimestamp(num: Int, activateTimestamp: Long): Long { return activateTimestamp + 1000 } override fun passType(): PassType { return PassType.DAY } }
kotlin
9
0.712025
76
25.416667
12
starcoderdata
/* * Copyright (c) 2018 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.app.browser.useragent import android.os.Build import androidx.core.net.toUri import com.duckduckgo.app.global.UriString import com.duckduckgo.app.global.device.DeviceInfo /** * Example Default User Agent (From Chrome): * Mozilla/5.0 (Linux; Android 8.1.0; Nexus 6P Build/OPM3.171019.014) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.137 Mobile Safari/537.36 * * Example Default Desktop User Agent (From Chrome): * Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.137 Safari/537.36 */ class UserAgentProvider constructor(private val defaultUserAgent: String, private val device: DeviceInfo) { private val baseAgent: String private val baseDesktopAgent: String private val safariComponent: String? private val applicationComponent = "DuckDuckGo/${device.majorAppVersion}" init { safariComponent = getSafariComponent() baseAgent = concatWithSpaces(mobilePrefix, getWebKitVersionOnwards(false)) baseDesktopAgent = concatWithSpaces(desktopPrefix, getWebKitVersionOnwards(true)) } /** * Returns, our custom UA, including our application component before Safari * * Modifies UA string to omits the user's device make and model and drops components that may casue breakages * If the user is requesting a desktop site, we add generic X11 Linux indicator, but include the real architecture * If the user is requesting a mobile site, we add Linux Android indicator, and include the real Android OS version * If the site breaks when our application component is included, we exclude it * * We include everything from the original UA string from AppleWebKit onwards (omitting if missing) */ fun userAgent(url: String? = null, isDesktop: Boolean = false): String { val host = url?.toUri()?.host val omitApplicationComponent = if (host != null) sitesThatOmitApplication.any { UriString.sameOrSubdomain(host, it) } else false val omitVersionComponent = if (host != null) sitesThatOmitVersion.any { UriString.sameOrSubdomain(host, it) } else false val shouldUseDesktopAgent = if (url != null && host != null) { sitesThatShouldUseDesktopAgent.any { UriString.sameOrSubdomain(host, it.host) && !containsExcludedPath(url, it) } } else { false } var prefix = if (isDesktop || shouldUseDesktopAgent) baseDesktopAgent else baseAgent if (omitVersionComponent) { prefix = prefix.replace(AgentRegex.version, "") } val application = if (!omitApplicationComponent) applicationComponent else null return concatWithSpaces(prefix, application, safariComponent) } private fun containsExcludedPath(url: String?, site: DesktopAgentSiteOnly): Boolean { return if (url != null) { val segments = url.toUri().pathSegments site.excludedPaths.any { segments.contains(it) } } else { false } } private fun getWebKitVersionOnwards(forDesktop: Boolean): String? { val matches = AgentRegex.webkitUntilSafari.find(defaultUserAgent) ?: AgentRegex.webkitUntilEnd.find(defaultUserAgent) ?: return null var result = matches.groupValues.last() if (forDesktop) { result = result.replace(" Mobile", "") } return result } private fun concatWithSpaces(vararg elements: String?): String { return elements.filterNotNull().joinToString(SPACE) } private fun getSafariComponent(): String? { val matches = AgentRegex.safari.find(defaultUserAgent) ?: return null return matches.groupValues.last() } private object AgentRegex { val webkitUntilSafari = Regex("(AppleWebKit/.*) Safari") val webkitUntilEnd = Regex("(AppleWebKit/.*)") val safari = Regex("(Safari/[^ ]+) *") val version = Regex("(Version/[^ ]+) *") } companion object { const val SPACE = " " val mobilePrefix = "Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE})" val desktopPrefix = "Mozilla/5.0 (X11; Linux ${System.getProperty("os.arch")})" val sitesThatOmitApplication = listOf( "cvs.com", "chase.com", "tirerack.com", "sovietgames.su", "thesun.co.uk", "accounts.google.com", "mail.google.com" ) val sitesThatOmitVersion = listOf( "ing.nl", "chase.com", "digid.nl", "accounts.google.com", "xfinity.com" ) val sitesThatShouldUseDesktopAgent = listOf( DesktopAgentSiteOnly("m.facebook.com", listOf("dialog", "sharer")) ) } data class DesktopAgentSiteOnly(val host: String, val excludedPaths: List<String> = emptyList()) }
kotlin
22
0.6654
150
39.632353
136
starcoderdata
<reponame>dwyck/space-app package sk.kasper.repository import sk.kasper.entity.FalconCore interface FalconInfoRepository { suspend fun getFalconCore(launchId: String): FalconCore? }
kotlin
7
0.812834
60
22.5
8
starcoderdata
// !LANGUAGE: +NewInference // !DIAGNOSTICS: -UNUSED_EXPRESSION // SKIP_TXT /* * KOTLIN DIAGNOSTICS NOT LINKED SPEC TEST (POSITIVE) * * SECTIONS: dfa * NUMBER: 26 * DESCRIPTION: Raw data flow analysis test * HELPERS: classes, objects, typealiases, enumClasses, interfaces, sealedClasses */ /* * TESTCASE NUMBER: 1 * UNEXPECTED BEHAVIOUR */ open class Case1<K : Number> { open inner class Case1_1<L>: Case1<Int>() where L : CharSequence { inner class Case1_2<M>: Case1<K>.Case1_1<M>() where M : Map<K, L> { inline fun <reified T>case_1(x: Any?) { x as M x as L x as K if (x is T) { <!DEBUG_INFO_EXPRESSION_TYPE("M & L & K & T!! & kotlin.Any?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("M & L & K & T!! & kotlin.Any?")!>x<!>.toByte() <!DEBUG_INFO_EXPRESSION_TYPE("M & L & K & T!! & kotlin.Any?")!>x<!>.length <!DEBUG_INFO_EXPRESSION_TYPE("M & L & K & T!! & kotlin.Any?")!>x<!>.<!AMBIGUITY!>get<!>(0) <!DEBUG_INFO_EXPRESSION_TYPE("M & L & K & T!! & kotlin.Any?")!>x<!>.size <!DEBUG_INFO_EXPRESSION_TYPE("M & L & K & T!! & kotlin.Any?")!>x<!>.isEmpty() <!DEBUG_INFO_EXPRESSION_TYPE("M & L & K & T!! & kotlin.Any?")!>x<!>[null] } } } } } // TESTCASE NUMBER: 2 inline fun <reified T : CharSequence>case_2(x: Any?) { x as T if (x !is T) { <!DEBUG_INFO_EXPRESSION_TYPE("T & kotlin.Any?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("T & kotlin.Any?")!>x<!>.length <!DEBUG_INFO_EXPRESSION_TYPE("T & kotlin.Any?")!>x<!>.get(0) } } // TESTCASE NUMBER: 3 inline fun <reified T : CharSequence>case_3(x: Any?) { x as T? if (x is T) { <!DEBUG_INFO_EXPRESSION_TYPE("T & kotlin.Any?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("T & kotlin.Any?")!>x<!>.length <!DEBUG_INFO_EXPRESSION_TYPE("T & kotlin.Any?")!>x<!>.get(0) } } // TESTCASE NUMBER: 4 inline fun <reified T : CharSequence>case_4(x: Any?) { (x as? T)!! if (x is T?) { <!DEBUG_INFO_EXPRESSION_TYPE("T? & kotlin.Any?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("T? & kotlin.Any?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>length<!> <!DEBUG_INFO_EXPRESSION_TYPE("T? & kotlin.Any?")!>x<!>.<!INAPPLICABLE_CANDIDATE!>get<!>(0) } } // TESTCASE NUMBER: 5 inline fun <reified T : CharSequence>case_5(x: Any?) { if (x as? T != null) { if (x is T?) { <!DEBUG_INFO_EXPRESSION_TYPE("T?!! & kotlin.Any?")!>x<!> <!DEBUG_INFO_EXPRESSION_TYPE("T?!! & kotlin.Any?")!>x<!>.length <!DEBUG_INFO_EXPRESSION_TYPE("T?!! & kotlin.Any?")!>x<!>.get(0) } } }
kotlin
40
0.519727
110
34.74359
78
starcoderdata
package com.mathewsachin.fategrandautomata.accessibility import android.accessibilityservice.AccessibilityService import android.app.Activity.RESULT_OK import android.app.AlarmManager import android.app.PendingIntent import android.content.ClipData import android.content.ClipboardManager import android.content.Intent import android.content.res.Configuration import android.media.projection.MediaProjectionManager import android.os.SystemClock import android.view.accessibility.AccessibilityEvent import android.widget.ImageButton import android.widget.Toast import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.mathewsachin.fategrandautomata.R import com.mathewsachin.fategrandautomata.di.script.ScriptComponentBuilder import com.mathewsachin.fategrandautomata.imaging.MediaProjectionScreenshotService import com.mathewsachin.fategrandautomata.root.RootScreenshotService import com.mathewsachin.fategrandautomata.root.SuperUser import com.mathewsachin.fategrandautomata.scripts.enums.GameServerEnum import com.mathewsachin.fategrandautomata.scripts.prefs.IPreferences import com.mathewsachin.fategrandautomata.util.* import com.mathewsachin.libautomata.IPlatformImpl import com.mathewsachin.libautomata.IScreenshotService import com.mathewsachin.libautomata.messageAndStackTrace import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import timber.log.Timber import timber.log.debug import timber.log.info import timber.log.verbose import javax.inject.Inject import kotlin.time.seconds @AndroidEntryPoint class ScriptRunnerService : AccessibilityService() { companion object { var Instance: ScriptRunnerService? = null private set fun isAccessibilityServiceRunning() = Instance != null fun isServiceStarted() = Instance?.serviceState is ServiceState.Started private val _serviceStarted = MutableLiveData(isServiceStarted()) val serviceStarted: LiveData<Boolean> = _serviceStarted fun startService(mediaProjectionToken: Intent? = null): Boolean { return Instance?.let { service -> service.start(mediaProjectionToken).also { success -> if (success) { _serviceStarted.value = true val msg = service.getString(R.string.start_service_toast) service.platformImpl.toast(msg) } } } ?: false } fun stopService(): Boolean { return (Instance?.stop() == true).also { _serviceStarted.value = false } } } @Inject lateinit var imageLoader: ImageLoader @Inject lateinit var prefs: IPreferences @Inject lateinit var mediaProjectionManager: MediaProjectionManager @Inject lateinit var storageProvider: StorageProvider @Inject lateinit var userInterface: ScriptRunnerUserInterface @Inject lateinit var scriptManager: ScriptManager @Inject lateinit var notification: ScriptRunnerNotification @Inject lateinit var platformImpl: IPlatformImpl @Inject lateinit var scriptComponentBuilder: ScriptComponentBuilder @Inject lateinit var alarmManager: AlarmManager @Inject lateinit var clipboardManager: ClipboardManager private val screenOffReceiver = ScreenOffReceiver() override fun onUnbind(intent: Intent?): Boolean { Timber.info { "Accessibility Service unbind" } stop() screenOffReceiver.unregister(this) Instance = null return super.onUnbind(intent) } override fun onDestroy() { super.onDestroy() Instance = null } val wantsMediaProjectionToken: Boolean get() = !prefs.useRootForScreenshots var serviceState: ServiceState = ServiceState.Stopped private set private fun start(MediaProjectionToken: Intent? = null): Boolean { if (serviceState is ServiceState.Started) { return false } val screenshotService = registerScreenshot(MediaProjectionToken) ?: return false serviceState = ServiceState.Started(screenshotService) if (isLandscape()) { userInterface.show() } return true } private fun registerScreenshot(MediaProjectionToken: Intent?): IScreenshotService? { return try { if (MediaProjectionToken != null) { val mediaProjection = mediaProjectionManager.getMediaProjection(RESULT_OK, MediaProjectionToken) MediaProjectionScreenshotService( mediaProjection!!, userInterface.mediaProjectionMetrics, storageProvider ) } else RootScreenshotService(SuperUser(), storageProvider, platformImpl) } catch (e: Exception) { Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show() null } } private fun stop(): Boolean { scriptManager.stopScript() serviceState.let { if (it is ServiceState.Started) { it.screenshotService.close() } else return false } imageLoader.clearImageCache() userInterface.hide() serviceState = ServiceState.Stopped notification.hide() return true } override fun onTaskRemoved(rootIntent: Intent?) { // from https://stackoverflow.com/a/43310945/5971497 val restartServiceIntent = Intent(applicationContext, javaClass) restartServiceIntent.setPackage(packageName) val restartServicePendingIntent = PendingIntent.getService( applicationContext, 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT ) alarmManager.set( AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePendingIntent ) super.onTaskRemoved(rootIntent) } fun registerScriptCtrlBtnListeners(scriptCtrlBtn: ImageButton) { scriptCtrlBtn.setOnClickListener { val state = serviceState if (state is ServiceState.Started) { when (scriptManager.scriptState) { is ScriptState.Started -> scriptManager.stopScript() is ScriptState.Stopped -> { scriptManager.startScript(this, state.screenshotService, scriptComponentBuilder) } is ScriptState.Stopping -> { Timber.debug { "Already stopping ..." } } } } } } fun registerScriptPauseBtnListeners(scriptPauseBtn: ImageButton) = scriptPauseBtn.setOnClickListener { scriptManager.pause(ScriptManager.PauseAction.Toggle) } override fun onServiceConnected() { Timber.info { "Accessibility Service bound to system" } // We only want events from FGO serviceInfo = serviceInfo.apply { packageNames = GameServerEnum .values() .flatMap { it.packageNames.toList() } .toTypedArray() } Instance = this screenOffReceiver.register(this) { Timber.verbose { "SCREEN OFF" } scriptManager.pause(ScriptManager.PauseAction.Pause).let { success -> if (success) { val title = getString(R.string.script_paused) val msg = getString(R.string.screen_turned_off) platformImpl.notify(msg) platformImpl.messageBox(title, msg) } } } super.onServiceConnected() } override fun onInterrupt() {} private fun isLandscape() = userInterface.metrics.let { it.widthPixels >= it.heightPixels } override fun onConfigurationChanged(newConfig: Configuration) { // Hide overlay in Portrait orientation if (isLandscape()) { Timber.verbose { "LANDSCAPE" } if (serviceState is ServiceState.Started) { userInterface.show() } } else { Timber.verbose { "PORTRAIT" } userInterface.hide() // Pause if script is running GlobalScope.launch { // This delay is to avoid race-condition with screen turn OFF listener delay(1.seconds) scriptManager.pause(ScriptManager.PauseAction.Pause).let { success -> if (success) { val msg = getString(R.string.script_paused) platformImpl.toast(msg) } } } } } /** * This method is called on any subscribed [AccessibilityEvent] in script_runner_service.xml. * * When the app in the foreground changes, this method will check if the foreground app is one * of the FGO APKs. */ override fun onAccessibilityEvent(event: AccessibilityEvent?) { when (event?.eventType) { AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> { val foregroundAppName = event.packageName?.toString() ?: return GameServerEnum.fromPackageName(foregroundAppName)?.let { server -> Timber.debug { "Detected FGO: $server" } prefs.gameServer = server } } } } fun showMessageBox(Title: String, Message: String, Error: Exception?, onDismiss: () -> Unit) { showOverlayDialog(this) { setTitle(Title) .setMessage(Message) .setPositiveButton(android.R.string.ok) { _, _ -> } .setOnDismissListener { notification.hideMessage() onDismiss() } .let { if (Error != null) { // TODO: Translate it.setNeutralButton("Copy") { _, _ -> val clipData = ClipData.newPlainText("Error", Error.messageAndStackTrace) clipboardManager.setPrimaryClip(clipData) } } } } } }
kotlin
31
0.617575
104
30.747748
333
starcoderdata
/* * Copyright 2020 <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.monkopedia.scriptorium import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.option import com.monkopedia.FileLogger import com.monkopedia.Log import com.monkopedia.StdoutLogger import com.monkopedia.error import com.monkopedia.imdex.Scriptorium import com.monkopedia.ksrpc.SerializedChannel import com.monkopedia.ksrpc.ServiceApp import com.monkopedia.ksrpc.serializedChannel import com.monkopedia.ksrpc.serve import com.monkopedia.ksrpc.serveOnStd import io.ktor.application.* import io.ktor.features.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.response.* import io.ktor.routing.* import io.ktor.server.engine.* import io.ktor.server.netty.* import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.newSingleThreadContext import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import java.io.File import java.io.PrintWriter import java.io.StringWriter import java.net.ServerSocket import kotlin.concurrent.thread import kotlin.system.exitProcess fun main(args: Array<String>) = App().main(args) class App : ServiceApp("scriptorium") { private val log by option("-l", "--log", help = "Path to log to, or stdout") .default("/tmp/scriptorium.log") private val service by lazy { ScriptoriumService(Config()) } override fun run() { if (log == "stdout") { Log.init(StdoutLogger) } else { Log.init(FileLogger(File(log))) } if (!stdOut && port.isEmpty() && http.isEmpty()) { println("No output mechanism specified, exiting") exitProcess(1) } for (p in port) { thread(start = true) { val socket = ServerSocket(p) while (true) { val s = socket.accept() GlobalScope.launch { val context = newSingleThreadContext("$appName-socket-$p") withContext(context) { createChannel().serve(s.getInputStream(), s.getOutputStream()) } context.close() } } } } for (h in http) { embeddedServer(Netty, h) { install(CORS) { anyHost() } install(StatusPages) { status(HttpStatusCode.NotFound) { val content = call.resolveResource("web/index.html", null) if (content != null) call.respond(content) } } routing { serve("/${appName.decapitalize()}", createChannel()) static("/") { // default("index.html") resources("web") defaultResource("web/index.html") } } }.start() } if (stdOut) { runBlocking { createChannel().serveOnStd() } } } override fun createChannel(): SerializedChannel { return Scriptorium.serializedChannel( service, errorListener = { e -> Log.error( StringWriter().also { e.printStackTrace(PrintWriter(it)) }.toString() ) } ) } }
kotlin
34
0.574061
90
31.648438
128
starcoderdata
<reponame>matbadev/dabirva<filename>example/src/main/java/com/matbadev/dabirva/example/ui/NoteColumnViewModel.kt<gh_stars>0 package com.matbadev.dabirva.example.ui import androidx.annotation.ColorInt import com.matbadev.dabirva.ItemViewModel import com.matbadev.dabirva.example.BR import com.matbadev.dabirva.example.R data class NoteColumnViewModel( val id: Long, val text: String, @ColorInt val color: Int, ) : ItemViewModel { override val bindingId: Int get() = BR.viewModel override val layoutId: Int get() = R.layout.item_note_column override fun entityEquals(other: Any?): Boolean { return other is NoteColumnViewModel && id == other.id } }
kotlin
13
0.733333
123
27.2
25
starcoderdata
/* * Copyright 2017 GLodi * * 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 giuliolodi.brokersim.utils import android.content.Context import android.support.v4.content.ContextCompat import giuliolodi.brokersim.R class ColorUtils(context: Context) { var t: Int = 0 var mContext = context fun getRandomColor(): Int { val colorList: IntArray = intArrayOf( ContextCompat.getColor(mContext, R.color.brown), ContextCompat.getColor(mContext, R.color.deepOrange), ContextCompat.getColor(mContext, R.color.orange), ContextCompat.getColor(mContext, R.color.amber), ContextCompat.getColor(mContext, R.color.lime), ContextCompat.getColor(mContext, R.color.lightGreen), ContextCompat.getColor(mContext, R.color.green), ContextCompat.getColor(mContext, R.color.teal), ContextCompat.getColor(mContext, R.color.cyan), ContextCompat.getColor(mContext, R.color.lightBlue), ContextCompat.getColor(mContext, R.color.blue), ContextCompat.getColor(mContext, R.color.indigo), ContextCompat.getColor(mContext, R.color.deepPurple), ContextCompat.getColor(mContext, R.color.purple), ContextCompat.getColor(mContext, R.color.pink), ContextCompat.getColor(mContext, R.color.red)) t = colorList[(Math.random() * colorList.size).toInt()] return t } fun getRandomDarkColor(): Int { when(t) { ContextCompat.getColor(mContext, R.color.brown) -> return ContextCompat.getColor(mContext, R.color.brownDark) ContextCompat.getColor(mContext, R.color.deepOrange) -> return ContextCompat.getColor(mContext, R.color.deepOrangeDark) ContextCompat.getColor(mContext, R.color.orange) -> return ContextCompat.getColor(mContext, R.color.orangeDark) ContextCompat.getColor(mContext, R.color.amber) -> return ContextCompat.getColor(mContext, R.color.amberDark) ContextCompat.getColor(mContext, R.color.lime) -> return ContextCompat.getColor(mContext, R.color.limeDark) ContextCompat.getColor(mContext, R.color.lightGreen) -> return ContextCompat.getColor(mContext, R.color.lightGreenDark) ContextCompat.getColor(mContext, R.color.green) -> return ContextCompat.getColor(mContext, R.color.greenDark) ContextCompat.getColor(mContext, R.color.teal) -> return ContextCompat.getColor(mContext, R.color.tealDark) ContextCompat.getColor(mContext, R.color.cyan) -> return ContextCompat.getColor(mContext, R.color.cyanDark) ContextCompat.getColor(mContext, R.color.lightBlue) -> return ContextCompat.getColor(mContext, R.color.lightBlueDark) ContextCompat.getColor(mContext, R.color.blue) -> return ContextCompat.getColor(mContext, R.color.blueDark) ContextCompat.getColor(mContext, R.color.indigo) -> return ContextCompat.getColor(mContext, R.color.indigoDark) ContextCompat.getColor(mContext, R.color.deepPurple) -> return ContextCompat.getColor(mContext, R.color.deepPurpleDark) ContextCompat.getColor(mContext, R.color.purple) -> return ContextCompat.getColor(mContext, R.color.purpleDark) ContextCompat.getColor(mContext, R.color.pink) -> return ContextCompat.getColor(mContext, R.color.pinkDark) ContextCompat.getColor(mContext, R.color.red) -> return ContextCompat.getColor(mContext, R.color.redDark) } return 0 } }
kotlin
18
0.696338
131
55.493151
73
starcoderdata
package ar.com.francojaramillo.popcorn.data.repositories import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.util.Log import ar.com.francojaramillo.popcorn.data.models.SearchResult import ar.com.francojaramillo.popcorn.data.services.MovieService import ar.com.francojaramillo.popcorn.utils.Constants import java.util.concurrent.Executor import javax.inject.Inject import javax.inject.Singleton /** * SearchRepository in charge of interacting with the Movie Webservice. * Its dependencies are provided by Dagger: * - MovieService is a webservice that manages queries from a remote server * - Executor is an object that runs tasks in different thread than the MainThread. * The idea of using one as a dependency, is that Dagger would have a small pool of threads and * would provide one instead of the Repository to have to create its own, whereas to use it to * make a web request or read from an internal DB */ @Singleton class SearchRepository @Inject constructor(private val movieService: MovieService, private val executor: Executor) { // Tag for Logging private val TAG = "POPCORN_TAG" /** * Searches for the movies with the searchQuery argument. It returns a LiveData object * immediately that will be filled once the network request finished */ fun getSearchResult(searchQuery: String, yearQuery: String?): LiveData<SearchResult> { // Construct the params for the request var params = HashMap<String, String>() params.put(Constants.API_SEARCH_KEY, searchQuery) if (yearQuery != null) { params.put(Constants.API_SEARCH_YEAR_KEY, yearQuery.toString()) } val request = movieService.getMovieSearchResult(params = params) Log.d(TAG, "REQUEST: " + request.request()?.url()) // We return a liveData immediately and fill it with the result of the request when // is available val liveDataSearchResult = MutableLiveData<SearchResult>() // Execute the request in the Executor thread executor.execute { try { val response = request.execute() if (response.isSuccessful) { // If there is no result, it shows response as false. We will wrap the object // in a "true" result and 0 elements if (response.body()!!.response == false) { var searchResult = SearchResult(emptyList(), 0, true) liveDataSearchResult.postValue(searchResult) } else { liveDataSearchResult.postValue(response.body()) } } else { Log.d(TAG, "NOT SUCCESFUL") // If something happens, just return an empty list var searchResult = SearchResult(emptyList(), 0, false) liveDataSearchResult.postValue(searchResult) } Log.d(TAG, "FINISHED") } catch (e: Exception) { Log.d(TAG, "FAILURE: " + e.localizedMessage + " ||| " + e.message) var searchResult = SearchResult(emptyList(), 0, false) liveDataSearchResult.postValue(searchResult) } } return liveDataSearchResult } }
kotlin
27
0.630352
100
41.925
80
starcoderdata
/* * Copyright 2010-2017 JetBrains s.r.o. * * 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.jetbrains.kotlin.ir.util import org.jetbrains.kotlin.backend.common.atMostOne import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl import org.jetbrains.kotlin.ir.declarations.impl.IrPropertyImpl import org.jetbrains.kotlin.ir.declarations.impl.IrTypeParameterImpl import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.symbols.* import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.source.PsiSourceElement import org.jetbrains.kotlin.types.KotlinType /** * Binds the arguments explicitly represented in the IR to the parameters of the accessed function. * The arguments are to be evaluated in the same order as they appear in the resulting list. */ fun IrMemberAccessExpression.getArguments(): List<Pair<ParameterDescriptor, IrExpression>> { val res = mutableListOf<Pair<ParameterDescriptor, IrExpression>>() val descriptor = descriptor // TODO: ensure the order below corresponds to the one defined in Kotlin specs. dispatchReceiver?.let { res += (descriptor.dispatchReceiverParameter!! to it) } extensionReceiver?.let { res += (descriptor.extensionReceiverParameter!! to it) } descriptor.valueParameters.forEach { val arg = getValueArgument(it.index) if (arg != null) { res += (it to arg) } } return res } /** * Binds the arguments explicitly represented in the IR to the parameters of the accessed function. * The arguments are to be evaluated in the same order as they appear in the resulting list. */ fun IrFunctionAccessExpression.getArgumentsWithSymbols(): List<Pair<IrValueParameterSymbol, IrExpression>> { val res = mutableListOf<Pair<IrValueParameterSymbol, IrExpression>>() val irFunction = symbol.owner as IrFunction dispatchReceiver?.let { res += (irFunction.dispatchReceiverParameter!!.symbol to it) } extensionReceiver?.let { res += (irFunction.extensionReceiverParameter!!.symbol to it) } irFunction.valueParameters.forEach { val arg = getValueArgument(it.descriptor as ValueParameterDescriptor) if (arg != null) { res += (it.symbol to arg) } } return res } /** * Sets arguments that are specified by given mapping of parameters. */ fun IrMemberAccessExpression.addArguments(args: Map<ParameterDescriptor, IrExpression>) { descriptor.dispatchReceiverParameter?.let { val arg = args[it] if (arg != null) { this.dispatchReceiver = arg } } descriptor.extensionReceiverParameter?.let { val arg = args[it] if (arg != null) { this.extensionReceiver = arg } } descriptor.valueParameters.forEach { val arg = args[it] if (arg != null) { this.putValueArgument(it.index, arg) } } } fun IrMemberAccessExpression.addArguments(args: List<Pair<ParameterDescriptor, IrExpression>>) = this.addArguments(args.toMap()) fun IrExpression.isNullConst() = this is IrConst<*> && this.kind == IrConstKind.Null fun IrMemberAccessExpression.usesDefaultArguments(): Boolean = this.descriptor.valueParameters.any { this.getValueArgument(it) == null} fun IrFunction.createParameterDeclarations() { fun ParameterDescriptor.irValueParameter() = IrValueParameterImpl( innerStartOffset(this), innerEndOffset(this), IrDeclarationOrigin.DEFINED, this ) dispatchReceiverParameter = descriptor.dispatchReceiverParameter?.irValueParameter() extensionReceiverParameter = descriptor.extensionReceiverParameter?.irValueParameter() assert(valueParameters.isEmpty()) descriptor.valueParameters.mapTo(valueParameters) { it.irValueParameter() } assert(typeParameters.isEmpty()) descriptor.typeParameters.mapTo(typeParameters) { IrTypeParameterImpl( innerStartOffset(it), innerEndOffset(it), IrDeclarationOrigin.DEFINED, it ) } } fun IrClass.createParameterDeclarations() { descriptor.thisAsReceiverParameter.let { thisReceiver = IrValueParameterImpl( innerStartOffset(it), innerEndOffset(it), IrDeclarationOrigin.INSTANCE_RECEIVER, it ) } assert(typeParameters.isEmpty()) descriptor.declaredTypeParameters.mapTo(typeParameters) { IrTypeParameterImpl( innerStartOffset(it), innerEndOffset(it), IrDeclarationOrigin.DEFINED, it ) } } fun IrClass.addFakeOverrides() { val startOffset = this.startOffset val endOffset = this.endOffset fun FunctionDescriptor.createFunction(): IrFunction = IrFunctionImpl( startOffset, endOffset, IrDeclarationOrigin.FAKE_OVERRIDE, this ).apply { createParameterDeclarations() } descriptor.unsubstitutedMemberScope.getContributedDescriptors() .filterIsInstance<CallableMemberDescriptor>() .filter { it.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE } .mapTo(this.declarations) { when (it) { is FunctionDescriptor -> it.createFunction() is PropertyDescriptor -> IrPropertyImpl(startOffset, endOffset, IrDeclarationOrigin.FAKE_OVERRIDE, it).apply { // TODO: add field if getter is missing? getter = it.getter?.createFunction() setter = it.setter?.createFunction() } else -> TODO(it.toString()) } } } private fun IrElement.innerStartOffset(descriptor: DeclarationDescriptorWithSource): Int = descriptor.startOffset ?: this.startOffset private fun IrElement.innerEndOffset(descriptor: DeclarationDescriptorWithSource): Int = descriptor.endOffset ?: this.endOffset val DeclarationDescriptorWithSource.startOffset: Int? get() = (this.source as? PsiSourceElement)?.psi?.startOffset val DeclarationDescriptorWithSource.endOffset: Int? get() = (this.source as? PsiSourceElement)?.psi?.endOffset val DeclarationDescriptorWithSource.startOffsetOrUndefined: Int get() = startOffset ?: UNDEFINED_OFFSET val DeclarationDescriptorWithSource.endOffsetOrUndefined: Int get() = endOffset ?: UNDEFINED_OFFSET val IrClassSymbol.functions: Sequence<IrSimpleFunctionSymbol> get() = this.owner.declarations.asSequence().filterIsInstance<IrSimpleFunction>().map { it.symbol } val IrClassSymbol.constructors: Sequence<IrConstructorSymbol> get() = this.owner.declarations.asSequence().filterIsInstance<IrConstructor>().map { it.symbol } private fun IrClassSymbol.getPropertyDeclaration(name: String) = this.owner.declarations.filterIsInstance<IrProperty>() .atMostOne { it.descriptor.name == Name.identifier(name) } fun IrClassSymbol.getPropertyGetter(name: String): IrFunctionSymbol? = this.getPropertyDeclaration(name)?.getter?.symbol fun IrClassSymbol.getPropertySetter(name: String): IrFunctionSymbol? = this.getPropertyDeclaration(name)?.setter?.symbol val IrFunction.explicitParameters: List<IrValueParameterSymbol> get() = (listOfNotNull(dispatchReceiverParameter, extensionReceiverParameter) + valueParameters).map { it.symbol } val IrValueParameter.type: KotlinType get() = this.descriptor.type val IrClass.defaultType: KotlinType get() = this.descriptor.defaultType
kotlin
22
0.706389
118
36.199134
231
starcoderdata
/* * Copyright 2010-2017 JetBrains s.r.o. * * 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.jetbrains.kotlin.gradle.plugin.tasks import org.gradle.api.artifacts.FileCollectionDependency import org.gradle.api.file.FileCollection import org.gradle.api.tasks.* import org.jetbrains.kotlin.gradle.plugin.* import org.jetbrains.kotlin.konan.target.CompilerOutputKind import org.jetbrains.kotlin.konan.util.visibleName import java.io.File enum class Produce(val cliOption: String, val kind: CompilerOutputKind) { PROGRAM("program", CompilerOutputKind.PROGRAM), DYNAMIC("dynamic", CompilerOutputKind.DYNAMIC), FRAMEWORK("framework", CompilerOutputKind.FRAMEWORK), LIBRARY("library", CompilerOutputKind.LIBRARY), BITCODE("bitcode", CompilerOutputKind.BITCODE) } /** * A task compiling the target executable/library using Kotlin/Native compiler */ abstract class KonanCompileTask: KonanBuildingTask(), KonanCompileSpec { @Internal override val toolRunner = KonanCompilerRunner(project) abstract val produce: Produce @Internal get // Output artifact -------------------------------------------------------- override val artifactSuffix: String @Internal get() = produce.kind.suffix(konanTarget) override val artifactPrefix: String @Internal get() = produce.kind.prefix(konanTarget) // Multiplatform support -------------------------------------------------- @Input var commonSourceSets = listOf("main") @Internal var enableMultiplatform = false internal val commonSrcFiles_ = mutableSetOf<FileCollection>() val commonSrcFiles: Collection<FileCollection> @InputFiles get() = if (enableMultiplatform) commonSrcFiles_ else emptyList() // Other compilation parameters ------------------------------------------- protected val srcFiles_ = mutableSetOf<FileCollection>() val srcFiles: Collection<FileCollection> @InputFiles get() = srcFiles_.takeIf { !it.isEmpty() } ?: listOf(project.konanDefaultSrcFiles) @InputFiles val nativeLibraries = mutableSetOf<FileCollection>() @Input val linkerOpts = mutableListOf<String>() @Input var enableDebug = project.findProperty("enableDebug")?.toString()?.toBoolean() ?: project.environmentVariables.debuggingSymbols @Input var noStdLib = false @Input var noMain = false @Input var enableOptimizations = project.environmentVariables.enableOptimizations @Input var enableAssertions = false @Optional @Input var entryPoint: String? = null @Console var measureTime = false val languageVersion : String? @Optional @Input get() = project.konanExtension.languageVersion val apiVersion : String? @Optional @Input get() = project.konanExtension.apiVersion protected fun directoryToKt(dir: Any) = project.fileTree(dir).apply { include("**/*.kt") exclude { it.file.startsWith(project.buildDir) } } // Command line ------------------------------------------------------------ override fun buildArgs() = mutableListOf<String>().apply { addArg("-output", artifact.canonicalPath) addArgs("-repo", libraries.repos.map { it.canonicalPath }) if (platformConfiguration.files.isNotEmpty()) { platformConfiguration.files.filter { it.name.endsWith(".klib") }.forEach { addFileArgs("-library", project.files(it.absolutePath)) } } addFileArgs("-library", libraries.files) addArgs("-library", libraries.namedKlibs) addArgs("-library", libraries.artifacts.map { it.artifact.canonicalPath }) addFileArgs("-nativelibrary", nativeLibraries) addArg("-produce", produce.cliOption) addListArg("-linkerOpts", linkerOpts) addArgIfNotNull("-target", konanTarget.visibleName) addArgIfNotNull("-language-version", languageVersion) addArgIfNotNull("-api-version", apiVersion) addArgIfNotNull("-entry", entryPoint) addKey("-g", enableDebug) addKey("-nostdlib", noStdLib) addKey("-nomain", noMain) addKey("-opt", enableOptimizations) addKey("-ea", enableAssertions) addKey("--time", measureTime) addKey("-nodefaultlibs", noDefaultLibs) addKey("-Xmulti-platform", enableMultiplatform) addAll(extraOpts) listOf(srcFiles, commonSrcFiles).forEach { it.flatMap { it.files }.filter { it.name.endsWith(".kt") }.mapTo(this) { it.canonicalPath } } } // region DSL. // DSL. Input/output files. override fun srcDir(dir: Any) { srcFiles_.add(directoryToKt(dir)) } override fun srcFiles(vararg files: Any) { srcFiles_.add(project.files(files)) } override fun srcFiles(files: Collection<Any>) = srcFiles(*files.toTypedArray()) // DSL. Native libraries. override fun nativeLibrary(lib: Any) = nativeLibraries(lib) override fun nativeLibraries(vararg libs: Any) { nativeLibraries.add(project.files(*libs)) } override fun nativeLibraries(libs: FileCollection) { nativeLibraries.add(libs) } // DSL. Multiplatform projects. override fun enableMultiplatform(flag: Boolean) { enableMultiplatform = flag } @Deprecated("Use commonSourceSets instead", ReplaceWith("commonSourceSets(sourceSetName)")) override fun commonSourceSet(sourceSetName: String) { commonSourceSets = listOf(sourceSetName) enableMultiplatform(true) } override fun commonSourceSets(vararg sourceSetNames: String) { commonSourceSets = sourceSetNames.toList() enableMultiplatform(true) } internal fun commonSrcDir(dir: Any) { commonSrcFiles_.add(directoryToKt(dir)) } // DSL. Other parameters. override fun linkerOpts(values: List<String>) = linkerOpts(*values.toTypedArray()) override fun linkerOpts(vararg values: String) { linkerOpts.addAll(values) } override fun enableDebug(flag: Boolean) { enableDebug = flag } override fun noStdLib(flag: Boolean) { noStdLib = flag } override fun noMain(flag: Boolean) { noMain = flag } override fun enableOptimizations(flag: Boolean) { enableOptimizations = flag } override fun enableAssertions(flag: Boolean) { enableAssertions = flag } override fun entryPoint(entryPoint: String) { this.entryPoint = entryPoint } override fun measureTime(flag: Boolean) { measureTime = flag } // endregion } open class KonanCompileProgramTask: KonanCompileTask() { override val produce: Produce get() = Produce.PROGRAM } open class KonanCompileDynamicTask: KonanCompileTask() { override val produce: Produce get() = Produce.DYNAMIC val headerFile: File @OutputFile get() = destinationDir.resolve("$artifactPrefix${artifactName}_api.h") } open class KonanCompileFrameworkTask: KonanCompileTask() { override val produce: Produce get() = Produce.FRAMEWORK override val artifact @OutputDirectory get() = super.artifact } open class KonanCompileLibraryTask: KonanCompileTask() { override val produce: Produce get() = Produce.LIBRARY } open class KonanCompileBitcodeTask: KonanCompileTask() { override val produce: Produce get() = Produce.BITCODE }
kotlin
28
0.672242
103
31.855372
242
starcoderdata
<filename>app/src/main/java/levkaantonov/com/study/notice/databases/firebase/AllNotisesLiveData.kt package levkaantonov.com.study.notice.databases.firebase import androidx.lifecycle.LiveData import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import levkaantonov.com.study.notice.models.AppNotice import levkaantonov.com.study.notice.utils.FB_REF_DB class AllNotisesLiveData : LiveData<List<AppNotice>>() { override fun onActive() { FB_REF_DB.addValueEventListener(listener) super.onActive() } override fun onInactive() { FB_REF_DB.removeEventListener(listener) super.onInactive() } private val listener = object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { value = snapshot.children.map { it.getValue(AppNotice::class.java) ?: AppNotice() } } override fun onCancelled(error: DatabaseError) { } } }
kotlin
22
0.728916
98
32.228571
35
starcoderdata
<filename>src/test/kotlin/solved/p700/SolutionTest.kt package solved.p700 import common.TreeNode import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.DynamicTest import org.junit.jupiter.api.TestFactory internal class SolutionTest { @TestFactory fun `test solution`() = listOf( InputData(arrayOf(4, 2, 7, 1, 3), 2) to arrayOf(2, 1, 3), InputData(arrayOf(4, 2, 7, 1, 3), 5) to arrayOf(), ).map { (inputData, expected) -> DynamicTest.dynamicTest("The subtree with root ${inputData.searchValue} from tree [${inputData.tree.joinToString()}] should be [${expected.joinToString()}]") { Assertions.assertEquals( Solution().searchBST(TreeNode.from(inputData.tree.toList()), inputData.searchValue), TreeNode.from(expected.toList()) ) } } data class InputData(val tree: Array<Int>, val searchValue: Int) }
kotlin
31
0.667028
167
37.458333
24
starcoderdata
/* Copyright 2020 <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 settler.generators import io.kotest.property.Arb import io.kotest.property.Exhaustive import io.kotest.property.arbitrary.arb import io.kotest.property.arbitrary.localDate import io.kotest.property.arbitrary.long import io.kotest.property.arbitrary.map import io.kotest.property.arbitrary.set import io.kotest.property.arbitrary.stringPattern import io.kotest.property.exhaustive.enum import settler.WorkWeek import java.time.DayOfWeek import java.time.DayOfWeek.SATURDAY import java.time.DayOfWeek.SUNDAY import java.time.LocalDate import kotlin.ranges.IntRange val genCurrency = Arb.stringPattern("[A-Z0-9]{3}") val genCurrencyPair = Arb.set(genCurrency, range = 2..2).map { ss -> ss.joinTo(StringBuilder(), separator = "").toString() } fun genHolidays(date: LocalDate): Arb<Set<LocalDate>> = genHolidays(date, 0..10) fun genHolidays(date: LocalDate, range: IntRange): Arb<Set<LocalDate>> { return Arb.set(Arb.long(min = 1, max = 10), range).map { ns -> ns.map { n -> date.plusDays(n) }.toSet() } } val genTradeDate = Arb.localDate(minYear = 2020) fun genTradeDate(allowWeekends: Boolean = true): Arb<LocalDate> { val gen = Arb.localDate(minYear = 2020) return if (allowWeekends) { gen } else { gen.map({ d -> d.datesUntil(d.plusDays(7L)).filter { x -> x.dayOfWeek !in setOf(SATURDAY, SUNDAY) }.findFirst().get() }) } } val genWorkWeek = Arb.set(Exhaustive.enum<DayOfWeek>(), range = 0..2).map { WorkWeek(it) } fun <A, B> let(genA: Arb<A>, genBFn: (A) -> Arb<B>): Arb<Pair<A, B>> = arb { val iterA = genA.generate(it).iterator() generateSequence { val a = iterA.next().value val b = genBFn(a).generate(it).iterator().next().value Pair(a, b) } } fun <A, B, C> let( genA: Arb<A>, genBFn: (A) -> Arb<B>, genCFn: (A) -> Arb<C> ): Arb<Triple<A, B, C>> = arb { val iterA = genA.generate(it).iterator() generateSequence { val a = iterA.next().value val b = genBFn(a).generate(it).iterator().next().value val c = genCFn(a).generate(it).iterator().next().value Triple(a, b, c) } }
kotlin
29
0.668946
80
29.538462
91
starcoderdata
<reponame>tshd78/ka-materials import java.io.File println("Hello, scripting!") if (args.isEmpty()) { println("[no args]") } else { println("Args:\n ${args.joinToString("\n ")}") } fun currentFolder(): File { return File("").absoluteFile } fun File.contents(includingHidden: Boolean): List<File> { val fileList = this.listFiles().toList() return if (includingHidden) { fileList } else { fileList.filter { !it.isHidden } } } fun File.folders(includingHidden: Boolean): List<File> { return this.contents(includingHidden).filter { it.isDirectory } } fun File.files(includingHidden: Boolean): List<File> { return this.contents(includingHidden).filter { it.isFile } } fun File.filenames(includingHidden: Boolean): List<String> { return this.files(includingHidden).map { it.name } } fun File.folderNames(includingHidden: Boolean): List<String> { return this.folders(includingHidden).map { it.name } } fun File.printFolderInfo(includingHidden: Boolean) { println("Contents of `${this.name}`:") if (this.folders(includingHidden).isNotEmpty()) { println("- Folders:\n ${this.folderNames(includingHidden).joinToString("\n ")}") } if (this.files(includingHidden).isNotEmpty()) { println("- Files:\n ${this.filenames(includingHidden).joinToString("\n ")}") } println("Parent: ${this.parentFile.name}") } fun valueFromArgsForPrefix(prefix: String): String? { val arg = args.firstOrNull { it.startsWith(prefix) } if (arg == null) return null val pieces = arg.split("=") return if (pieces.size == 2) { pieces[1] } else { null } } val folderPrefix = "folder=" val folderValue = valueFromArgsForPrefix(folderPrefix) val hiddenPrefix = "showHidden=" val hiddenStringValue = valueFromArgsForPrefix(hiddenPrefix) val hiddenValue = hiddenStringValue?.toBoolean() ?: false val current = currentFolder() //println("Current folder contents:\n ${current.filenames().joinToString("\n ")}") current.printFolderInfo(hiddenValue) if (folderValue != null) { val folder = File(folderValue).absoluteFile folder.printFolderInfo(hiddenValue) } else { println("No path provided, printing working directory info") currentFolder().printFolderInfo(hiddenValue) }
kotlin
19
0.686632
88
24.32967
91
starcoderdata
<gh_stars>0 package com.yg.newsproject.ui.login import android.annotation.SuppressLint import android.os.Bundle import android.os.CountDownTimer import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.view.* import android.widget.* import androidx.constraintlayout.widget.ConstraintLayout import androidx.fragment.app.DialogFragment import com.blankj.utilcode.util.KeyboardUtils import com.blankj.utilcode.util.RegexUtils import com.yg.lib_core.bean.UserInfoBean import com.yg.newsproject.R import com.yg.newsproject.baselibs.config.UserManager import com.yg.newsproject.baselibs.utils.ToastUtils import com.yg.lib_core.http.ApiRetrofit import com.yg.main.dialog.ImgCodeDialog import com.yg.newsproject.baselibs.ext.ss import org.jetbrains.anko.find import org.jetbrains.anko.textColor class LoginDialog : DialogFragment() , ImgCodeDialog.OnRandomVerificationCodeInputListener { lateinit var img_finish :ImageView lateinit var ed_phone :EditText lateinit var iv_clear :ImageView lateinit var ed_code :EditText lateinit var ed_pass :EditText lateinit var tv_get_otp :TextView lateinit var btnLogin:Button lateinit var cv:CheckBox lateinit var tv_pass:TextView lateinit var iv_clear1:ImageView lateinit var cl_code:ConstraintLayout lateinit var cl_pass:ConstraintLayout lateinit var listener:OnLoginSuccessListener fun newInstance(): LoginDialog? { return LoginDialog() } override fun onStart() { super.onStart() val dialog = dialog if (dialog != null && dialog.window != null) { dialog.setCancelable(false) val window = dialog.window val wlp = window!!.attributes wlp.gravity = Gravity.BOTTOM wlp.width = WindowManager.LayoutParams.MATCH_PARENT wlp.height = WindowManager.LayoutParams.MATCH_PARENT window!!.attributes = wlp } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NORMAL, R.style.BottomDialog1) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.item_login_dialog,container,false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView(view) } private fun initView(view: View) { img_finish = view.find(R.id.img_finish) ed_phone = view.find(R.id.ed_phone) iv_clear = view.find(R.id.iv_clear) ed_code = view.find(R.id.ed_code) tv_get_otp = view.find(R.id.tv_get_otp) btnLogin = view.find(R.id.btn_login_register) cv = view.find(R.id.cv_userAgreement) cl_code = view.find(R.id.cl_code) ed_pass = view.find(R.id.ed_pass) tv_pass = view.find(R.id.tv_pass) iv_clear1 = view.find(R.id.iv_clear1) cl_pass = view.find(R.id.cl_pass) img_finish.setOnClickListener { dismiss() } ed_phone.addTextChangedListener(object :TextWatcher{ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable?) { if (s.toString().length > 0){ iv_clear.visibility = View.VISIBLE } else{ iv_clear.visibility = View.GONE } if (s.toString().length == 11) { tv_get_otp.textColor = resources.getColor(R.color.app_blue) tv_get_otp.isClickable = true } else { tv_get_otp.textColor = resources.getColor(R.color.text_grey) tv_get_otp.isClickable = true } } }) ed_code.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} @SuppressLint("Range") override fun afterTextChanged(s: Editable) { if (s.toString().length > 0) { btnLogin.isClickable = true btnLogin.alpha = 1f } else { btnLogin.isClickable = false btnLogin.alpha = 0.5f } } }) ed_pass.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} @SuppressLint("Range") override fun afterTextChanged(s: Editable) { if (TextUtils.isEmpty(s.toString())){ iv_clear1.visibility = View.GONE } else { iv_clear1.visibility = View.VISIBLE } if (s.toString().length > 7) { btnLogin.isClickable = true btnLogin.alpha = 1f } else { btnLogin.isClickable = false btnLogin.alpha = 0.5f } } }) iv_clear.setOnClickListener { ed_phone.text.clear() } iv_clear1.setOnClickListener { ed_pass.text.clear() } tv_get_otp.setOnClickListener { //send otp if (ed_phone.getText().toString().length == 11) { val vDialog = context?.let { it1 -> ImgCodeDialog(it1, ed_phone.text.toString(), this) } vDialog?.show() } else { ToastUtils.showToast("手机号格式错误") } } btnLogin.setOnClickListener { KeyboardUtils.hideSoftInput(btnLogin) if (cv.isChecked){ val phone = ed_phone.text.toString() val code = ed_code.text.toString() val pass = ed_pass.text.toString() if (TextUtils.isEmpty(phone)){ ToastUtils.showToast("请输入手机号") return@setOnClickListener } if (!RegexUtils.isMobileSimple(phone)){ ToastUtils.showToast("请输入正确的手机号") return@setOnClickListener } if (cl_code.visibility == View.VISIBLE){ if (TextUtils.isEmpty(code)){ ToastUtils.showToast("请输入验证码") return@setOnClickListener } loginCode() } else { if (TextUtils.isEmpty(pass)){ ToastUtils.showToast("请输入密码") return@setOnClickListener } if (pass.length < 8){ ToastUtils.showToast("密码不正确") return@setOnClickListener } loginPass() } } else{ ToastUtils.showToast("请同意用户协议") } } tv_pass.setOnClickListener { if (cl_code.visibility == View.VISIBLE){ cl_code.visibility = View.GONE cl_pass.visibility = View.VISIBLE tv_pass.text = "验证码登录" getTimeCount()?.cancel() } else { cl_code.visibility = View.VISIBLE cl_pass.visibility = View.GONE tv_pass.text = "账号<PASSWORD>" } } } //获取短信验证码 override fun inputCode(code: String?) { code?.let { ApiRetrofit.service.getPhoneCode(ed_phone.text.toString(), it)?.ss(onSuccess = { if (it.retcode == "0000"){ startTimer() } else { ToastUtils.showToast(it.retmsg) } }) } } private fun startTimer(){ getTimeCount()?.start() tv_get_otp.isClickable = false } private fun getTimeCount(): TimeCount? { return if (mTimeCount == null) TimeCount(60 * 1000, 500).also { mTimeCount = it } else mTimeCount } //验证码登录 private fun loginCode() { var map = HashMap<String,String>() map.put("code",ed_code.text.toString()) map.put("mobile",ed_phone.text.toString()) ApiRetrofit.service.loginCode(map)?.ss(onSuccess = { val data = it.data if (data != null && it.retcode == "0000"){ UserManager.get().setNickName(if (TextUtils.isEmpty(data.nickName)) "" else data.nickName) UserManager.get().setUserToken(if (TextUtils.isEmpty(data.token)) "" else data.token) UserManager.get().setUserHead(if (TextUtils.isEmpty(data.headUrl)) "" else data.headUrl) UserManager.get().setUserMobile(if (TextUtils.isEmpty(data.mobile)) "" else data.mobile) if (listener != null){ listener.OnLoginSuccess(data) } dismiss() } else { ToastUtils.showToast(it.retmsg) } }) } //密码登录 private fun loginPass() { var map = HashMap<String,String>() map.put("password",<PASSWORD>()) map.put("mobile",ed_phone.text.toString()) ApiRetrofit.service.loginPass(map)?.ss(onSuccess = { val data = it.data if (data != null && it.retcode == "0000"){ UserManager.get().setNickName(if (TextUtils.isEmpty(data.nickName)) "" else data.nickName) UserManager.get().setUserToken(if (TextUtils.isEmpty(data.token)) "" else data.token) UserManager.get().setUserHead(if (TextUtils.isEmpty(data.headUrl)) "" else data.headUrl) UserManager.get().setUserMobile(if (TextUtils.isEmpty(data.mobile)) "" else data.mobile) if (listener != null){ listener.OnLoginSuccess(data) } dismiss() } else { ToastUtils.showToast(it.retmsg) } }) } private var mTimeCount: TimeCount? = null inner class TimeCount(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) { override fun onTick(millisUntilFinished: Long) { // text.set(makeWaitingText(millisUntilFinished)); tv_get_otp.text = makeWaitingText(millisUntilFinished) tv_get_otp.isClickable = true tv_get_otp.isEnabled = true } override fun onFinish() { onStopTimer() } private fun onStopTimer() { tv_get_otp.isClickable = true tv_get_otp.text = "获取验证码" tv_get_otp.isEnabled = true } private fun makeWaitingText(time: Long): String? { return generateSendCodeText(time) } } fun generateSendCodeText(time: Long): String? { return ((time - 250) / 1000).toString() + "s" } interface OnLoginSuccessListener{ fun OnLoginSuccess(bean: UserInfoBean) } fun setLoginListener(l: OnLoginSuccessListener){ listener = l } }
kotlin
28
0.556135
106
34.017964
334
starcoderdata
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation import androidx.compose.runtime.Composable import androidx.compose.runtime.emptyContent import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.layout.Layout import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.paint import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.DefaultAlpha import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.painter.ColorPainter import androidx.compose.ui.graphics.painter.ImagePainter import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics /** * A composable that lays out and draws a given [ImageBitmap]. This will attempt to * size the composable according to the [ImageBitmap]'s given width and height. However, an * optional [Modifier] parameter can be provided to adjust sizing or draw additional content (ex. * background). Any unspecified dimension will leverage the [ImageBitmap]'s size as a minimum * constraint. * * The following sample shows basic usage of an Image composable to position and draw an * [ImageBitmap] on screen * @sample androidx.compose.foundation.samples.ImageSample * * For use cases that require drawing a rectangular subset of the [ImageBitmap] consumers can use * overload that consumes a [Painter] parameter shown in this sample * @sample androidx.compose.foundation.samples.ImagePainterSubsectionSample * * @param bitmap The [ImageBitmap] to draw * @param contentDescription text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. This text should be * localized, such as by using [androidx.compose.ui.res.stringResource] or similar * @param modifier Modifier used to adjust the layout algorithm or draw decoration content (ex. * background) * @param alignment Optional alignment parameter used to place the [ImageBitmap] in the given * bounds defined by the width and height * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be used * if the bounds are a different size from the intrinsic size of the [ImageBitmap] * @param alpha Optional opacity to be applied to the [ImageBitmap] when it is rendered onscreen * @param colorFilter Optional ColorFilter to apply for the [ImageBitmap] when it is rendered * onscreen */ @Suppress("NOTHING_TO_INLINE") @Composable inline fun Image( bitmap: ImageBitmap, contentDescription: String?, modifier: Modifier = Modifier, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null ) { val imagePainter = remember(bitmap) { ImagePainter(bitmap) } Image( painter = imagePainter, contentDescription = contentDescription, modifier = modifier, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter ) } /** * A composable that lays out and draws a given [ImageVector]. This will attempt to * size the composable according to the [ImageVector]'s given width and height. However, an * optional [Modifier] parameter can be provided to adjust sizing or draw additional content (ex. * background). Any unspecified dimension will leverage the [ImageVector]'s size as a minimum * constraint. * * @sample androidx.compose.foundation.samples.ImageVectorSample * * @param imageVector The [ImageVector] to draw * @param contentDescription text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. This text should be * localized, such as by using [androidx.compose.ui.res.stringResource] or similar * @param modifier Modifier used to adjust the layout algorithm or draw decoration content (ex. * background) * @param alignment Optional alignment parameter used to place the [ImageVector] in the given * bounds defined by the width and height * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be used * if the bounds are a different size from the intrinsic size of the [ImageVector] * @param alpha Optional opacity to be applied to the [ImageVector] when it is rendered onscreen * @param colorFilter Optional ColorFilter to apply for the [ImageVector] when it is rendered * onscreen */ @Suppress("NOTHING_TO_INLINE") @Composable inline fun Image( imageVector: ImageVector, contentDescription: String?, modifier: Modifier = Modifier, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null ) = Image( painter = rememberVectorPainter(imageVector), contentDescription = contentDescription, modifier = modifier, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter ) /** * Creates a composable that lays out and draws a given [Painter]. This will attempt to size * the composable according to the [Painter]'s intrinsic size. However, an optional [Modifier] * parameter can be provided to adjust sizing or draw additional content (ex. background) * * **NOTE** a Painter might not have an intrinsic size, so if no LayoutModifier is provided * as part of the Modifier chain this might size the [Image] composable to a width and height * of zero and will not draw any content. This can happen for Painter implementations that * always attempt to fill the bounds like [ColorPainter] * * @sample androidx.compose.foundation.samples.ImagePainterSample * * @param painter to draw * @param contentDescription text used by accessibility services to describe what this image * represents. This should always be provided unless this image is used for decorative purposes, * and does not represent a meaningful action that a user can take. This text should be * localized, such as by using [androidx.compose.ui.res.stringResource] or similar * @param modifier Modifier used to adjust the layout algorithm or draw decoration content (ex. * background) * @param alignment Optional alignment parameter used to place the [Painter] in the given * bounds defined by the width and height. * @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be used * if the bounds are a different size from the intrinsic size of the [Painter] * @param alpha Optional opacity to be applied to the [Painter] when it is rendered onscreen * the default renders the [Painter] completely opaque * @param colorFilter Optional colorFilter to apply for the [Painter] when it is rendered onscreen */ @Composable fun Image( painter: Painter, contentDescription: String?, modifier: Modifier = Modifier, alignment: Alignment = Alignment.Center, contentScale: ContentScale = ContentScale.Fit, alpha: Float = DefaultAlpha, colorFilter: ColorFilter? = null ) { val semantics = if (contentDescription != null) { Modifier.semantics { this.contentDescription = contentDescription this.role = Role.Image } } else { Modifier } // Explicitly use a simple Layout implementation here as Spacer squashes any non fixed // constraint with zero Layout( emptyContent(), modifier.then(semantics).clipToBounds().paint( painter, alignment = alignment, contentScale = contentScale, alpha = alpha, colorFilter = colorFilter ) ) { _, constraints -> layout(constraints.minWidth, constraints.minHeight) {} } }
kotlin
17
0.756642
101
44.247475
198
starcoderdata
<gh_stars>0 package com.danielgergely.cgmath.vec2 @Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS") inline class Vec2 internal constructor(val array: FloatArray) { inline var x: Float get() = array[0] set(value) { array[0] = value } inline var y: Float get() = array[1] set(value) { array[1] = value } operator fun component1() = array[0] operator fun component2() = array[1] } fun Vec2(x: Float, y: Float): Vec2 = Vec2(floatArrayOf(x, y)) fun Vec2(other: Vec2): Vec2 = Vec2(other.array.copyOf())
kotlin
11
0.603333
63
23.04
25
starcoderdata
<reponame>verkhovin/kotlintest package io.kotlintest import io.kotlintest.assertions.AssertionCounter import io.kotlintest.assertions.Failures /** * Verifies that a block of code throws any [Throwable] * * Use function to wrap a block of code that you want to verify that throws any kind of [Throwable], where using * [shouldThrowAny] can't be used for any reason, such as an assignment of a variable (assignments are statements, * therefore has no return value). * * If you want to verify a specific [Throwable], use [shouldThrowExactlyUnit]. * * If you want to verify a [Throwable] and any subclass, use [shouldThrowUnit]. * * @see [shouldThrowAny] */ inline fun shouldThrowAnyUnit(block: () -> Unit) = shouldThrowAny(block) /** * Verifies that a block of code does NOT throw any [Throwable] * * Use function to wrap a block of code that you want to make sure doesn't throw any [Throwable], * where using [shouldNotThrowAny] can't be used for any reason, such as an assignment of a variable (assignments are * statements, therefore has no return value). * * Note that executing this code is no different to executing [block] itself, as any uncaught exception will * be propagated up anyways. * * @see [shouldNotThrowAny] * @see [shouldNotThrowExactlyUnit] * @see [shouldNotThrowUnit] * */ inline fun shouldNotThrowAnyUnit(block: () -> Unit) = shouldNotThrowAny(block) /** * Verifies that a block of code throws any [Throwable] * * Use function to wrap a block of code that you want to verify that throws any kind of [Throwable]. * * If you want to verify a specific [Throwable], use [shouldThrowExactly]. * * If you want to verify a [Throwable] and any subclasses, use [shouldThrow] * * * **Attention to assignment operations:** * * When doing an assignment to a variable, the code won't compile, because an assignment is not of type [Any], as required * by [block]. If you need to test that an assignment throws a [Throwable], use [shouldThrowAnyUnit] or it's variations. * * ``` * val thrownThrowable: Throwable = shouldThrowAny { * throw FooException() // This is a random Throwable, could be anything * } * ``` * * @see [shouldThrowAnyUnit] */ inline fun shouldThrowAny(block: () -> Any?): Throwable { AssertionCounter.inc() val thrownException = try { block() null } catch (e: Throwable) { e } return thrownException ?: throw Failures.failure("Expected a throwable, but nothing was thrown.") } /** * Verifies that a block of code does NOT throw any [Throwable] * * Use function to wrap a block of code that you want to make sure doesn't throw any [Throwable]. * * Note that executing this code is no different to executing [block] itself, as any uncaught exception will * be propagated up anyways. * * **Attention to assignment operations:** * * When doing an assignment to a variable, the code won't compile, because an assignment is not of type [Any], as required * by [block]. If you need to test that an assignment doesn't throw a [Throwable], use [shouldNotThrowAnyUnit] or it's * variations. * * @see [shouldNotThrowAnyUnit] * @see [shouldNotThrowExactly] * @see [shouldNotThrow] * */ inline fun <T> shouldNotThrowAny(block: () -> T): T { AssertionCounter.inc() val thrownException = try { return block() } catch (e: Throwable) { e } throw Failures.failure("No exception expected, but a ${thrownException::class.simpleName} was thrown.", thrownException) }
kotlin
13
0.709101
122
32.590476
105
starcoderdata
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { java kotlin("jvm") version "1.6.10" `maven-publish` } repositories { mavenCentral() } dependencies { implementation(kotlin("stdlib")) } tasks.withType<KotlinCompile> { kotlinOptions.jvmTarget = "1.8" } publishing { publications { create<MavenPublication>("maven") { groupId = "me.exerro" artifactId = "observables" version = "1.2.0" from(components["java"]) } } }
kotlin
22
0.595104
54
16.129032
31
starcoderdata
@file:Suppress("UNCHECKED_CAST") package org.koin.experimental.property import org.koin.core.Koin import org.koin.core.context.GlobalContext import org.koin.core.scope.Scope import kotlin.reflect.KClass import kotlin.reflect.KMutableProperty0 fun <T : Any> T.inject(vararg properties: KMutableProperty0<*>) { properties.forEach { val prop = it as KMutableProperty0<Any> val type = prop.returnType.classifier as KClass<*> val value = GlobalContext.get().get<Any>(type) prop.set(value) } } fun <T : Any> T.inject(koin: Koin, vararg properties: KMutableProperty0<*>) { properties.forEach { val prop = it as KMutableProperty0<Any> val type = prop.returnType.classifier as KClass<*> val value = koin.get<Any>(type) prop.set(value) } } fun <T : Any> T.inject(scope: Scope, vararg properties: KMutableProperty0<*>) { properties.forEach { val prop = it as KMutableProperty0<Any> val type = prop.returnType.classifier as KClass<*> val value = scope.get<Any>(type) prop.set(value) } }
kotlin
16
0.673339
79
29.555556
36
starcoderdata
package com.bytedance.android.plugin.tasks import com.android.build.gradle.internal.scope.VariantScope import com.bytedance.android.aabresguard.commands.ObfuscateBundleCommand import com.bytedance.android.plugin.extensions.AabResGuardExtension import com.bytedance.android.plugin.internal.getBundleFilePath import com.bytedance.android.plugin.internal.getSigningConfig import com.bytedance.android.plugin.model.SigningConfig import org.gradle.api.DefaultTask import org.gradle.api.tasks.TaskAction import java.io.File import java.nio.file.Path /** * Created by YangJing on 2019/10/15 . * Email: <EMAIL> */ open class AabResGuardTask : DefaultTask() { private lateinit var variantScope: VariantScope lateinit var signingConfig: SigningConfig var aabResGuard: AabResGuardExtension = project.extensions.getByName("aabResGuard") as AabResGuardExtension private lateinit var bundlePath: Path private lateinit var obfuscatedBundlePath: Path init { description = "Assemble resource proguard for bundle file" group = "bundle" outputs.upToDateWhen { false } } fun setVariantScope(variantScope: VariantScope) { this.variantScope = variantScope // init bundleFile, obfuscatedBundlePath must init before task action. bundlePath = getBundleFilePath(project, variantScope) obfuscatedBundlePath = File(bundlePath.toFile().parentFile, aabResGuard.obfuscatedBundleFileName).toPath() } fun getObfuscatedBundlePath(): Path { return obfuscatedBundlePath } @TaskAction private fun execute() { println(aabResGuard.toString()) // init signing config signingConfig = getSigningConfig(project, variantScope) printSignConfiguration() prepareUnusedFile() val command = ObfuscateBundleCommand.builder() .setEnableObfuscate(aabResGuard.enableObfuscate) .setBundlePath(bundlePath) .setOutputPath(obfuscatedBundlePath) .setMergeDuplicatedResources(aabResGuard.mergeDuplicatedRes) .setWhiteList(aabResGuard.whiteList) .setFilterFile(aabResGuard.enableFilterFiles) .setFileFilterRules(aabResGuard.filterList) .setRemoveStr(aabResGuard.enableFilterStrings) .setUnusedStrPath(aabResGuard.unusedStringPath) .setLanguageWhiteList(aabResGuard.languageWhiteList) if (aabResGuard.mappingFile != null) { command.setMappingPath(aabResGuard.mappingFile) } if (signingConfig.storeFile != null && signingConfig.storeFile!!.exists()) { command.setStoreFile(signingConfig.storeFile!!.toPath()) .setKeyAlias(signingConfig.keyAlias) .setKeyPassword(signingConfig.keyPassword) .setStorePassword(signingConfig.storePassword) } command.build().execute() } private fun prepareUnusedFile() { val simpleName = variantScope.variantData.name.replace("Release", "") val name = simpleName[0].toLowerCase() + simpleName.substring(1) val resourcePath = "${project.buildDir}/outputs/mapping/$name/release/unused.txt" val usedFile = File(resourcePath) if (usedFile.exists()) { println("find unused.txt : ${usedFile.absolutePath}") if (aabResGuard.enableFilterStrings) { if (aabResGuard.unusedStringPath == null || aabResGuard.unusedStringPath!!.isBlank()) { aabResGuard.unusedStringPath = usedFile.absolutePath println("replace unused.txt!") } } } else { println("not exists unused.txt : ${usedFile.absolutePath}\n" + "use default path : ${aabResGuard.unusedStringPath}") } } private fun printSignConfiguration() { println("-------------- sign configuration --------------") println("\tstoreFile : ${signingConfig.storeFile}") println("\tkeyPassword : ${encrypt(signingConfig.keyPassword)}") println("\talias : ${encrypt(signingConfig.keyAlias)}") println("\tstorePassword : ${encrypt(signingConfig.storePassword)}") println("-------------- sign configuration --------------") } private fun encrypt(value: String?): String { if (value == null) return "/" if (value.length > 2) { return "${value.substring(0, value.length / 2)}****" } return "****" } }
kotlin
31
0.658494
114
40.162162
111
starcoderdata
<filename>leakcanary-android-core/src/main/java/leakcanary/internal/InternalLeakCanary.kt package leakcanary.internal import android.app.Application import android.content.ComponentName import android.content.Intent import android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED import android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED import android.content.pm.PackageManager.DONT_KILL_APP import android.content.pm.ShortcutInfo.Builder import android.content.pm.ShortcutManager import android.graphics.drawable.Icon import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.os.Handler import android.os.HandlerThread import com.squareup.leakcanary.core.BuildConfig import com.squareup.leakcanary.core.R import leakcanary.AppWatcher import leakcanary.GcTrigger import leakcanary.LeakCanary import leakcanary.LeakCanary.Config import leakcanary.OnHeapAnalyzedListener import leakcanary.OnObjectRetainedListener import leakcanary.internal.activity.LeakActivity import shark.SharkLog import java.lang.reflect.InvocationHandler import java.lang.reflect.Proxy internal object InternalLeakCanary : (Application) -> Unit, OnObjectRetainedListener { private const val DYNAMIC_SHORTCUT_ID = "com.squareup.leakcanary.dynamic_shortcut" private lateinit var heapDumpTrigger: HeapDumpTrigger lateinit var application: Application // BuildConfig.LIBRARY_VERSION is stripped so this static var is how we keep it around to find // it later when parsing the heap dump. @Suppress("unused") @JvmStatic private var version = BuildConfig.LIBRARY_VERSION @Volatile var applicationVisible = false private set private val isJunitAvailable by lazy { try { Class.forName("org.junit.Test") true } catch (e: Exception) { false } } val leakDirectoryProvider: LeakDirectoryProvider by lazy { LeakDirectoryProvider(application, { LeakCanary.config.maxStoredHeapDumps }, { LeakCanary.config.requestWriteExternalStoragePermission }) } val leakDisplayActivityIntent: Intent get() = LeakActivity.createIntent(application) val noInstallConfig: Config get() = Config( dumpHeap = false, referenceMatchers = emptyList(), objectInspectors = emptyList(), onHeapAnalyzedListener = OnHeapAnalyzedListener {} ) override fun invoke(application: Application) { this.application = application AppWatcher.objectWatcher.addOnObjectRetainedListener(this) val heapDumper = AndroidHeapDumper(application, leakDirectoryProvider) val gcTrigger = GcTrigger.Default val configProvider = { LeakCanary.config } val handlerThread = HandlerThread(LEAK_CANARY_THREAD_NAME) handlerThread.start() val backgroundHandler = Handler(handlerThread.looper) heapDumpTrigger = HeapDumpTrigger( application, backgroundHandler, AppWatcher.objectWatcher, gcTrigger, heapDumper, configProvider ) application.registerVisibilityListener { applicationVisible -> this.applicationVisible = applicationVisible heapDumpTrigger.onApplicationVisibilityChanged(applicationVisible) } addDynamicShortcut(application) disableDumpHeapInTests() } private fun disableDumpHeapInTests() { // This is called before Application.onCreate(), so if the class is loaded through a secondary // dex it might not be available yet. Handler().post { if (isJunitAvailable) { SharkLog.d { "Tests detected, setting LeakCanary.Config.dumpHeap to false" } LeakCanary.config = LeakCanary.config.copy(dumpHeap = false) } } } @Suppress("ReturnCount") private fun addDynamicShortcut(application: Application) { if (VERSION.SDK_INT < VERSION_CODES.N_MR1) { return } if (!application.resources.getBoolean(R.bool.leak_canary_add_dynamic_shortcut)) { return } if (VERSION.SDK_INT >= VERSION_CODES.O && application.packageManager.isInstantApp) { // Instant Apps don't have access to ShortcutManager return } val shortcutManager = application.getSystemService(ShortcutManager::class.java)!! val dynamicShortcuts = shortcutManager.dynamicShortcuts val shortcutInstalled = dynamicShortcuts.any { shortcut -> shortcut.id == DYNAMIC_SHORTCUT_ID } if (shortcutInstalled) { return } val mainIntent = Intent(Intent.ACTION_MAIN, null) mainIntent.addCategory(Intent.CATEGORY_LAUNCHER) mainIntent.setPackage(application.packageName) val activities = application.packageManager.queryIntentActivities(mainIntent, 0) .filter { it.activityInfo.name != "leakcanary.internal.activity.LeakLauncherActivity" } if (activities.isEmpty()) { return } val firstMainActivity = activities.first() .activityInfo // Displayed on long tap on app icon val longLabel: String // Label when dropping shortcut to launcher val shortLabel: String val leakActivityLabel = application.getString(R.string.leak_canary_shortcut_label) if (activities.isEmpty()) { longLabel = leakActivityLabel shortLabel = leakActivityLabel } else { val firstLauncherActivityLabel = if (firstMainActivity.labelRes != 0) { application.getString(firstMainActivity.labelRes) } else { application.packageManager.getApplicationLabel(application.applicationInfo) } val fullLengthLabel = "$firstLauncherActivityLabel $leakActivityLabel" // short label should be under 10 and long label under 25 if (fullLengthLabel.length > 10) { if (fullLengthLabel.length <= 25) { longLabel = fullLengthLabel shortLabel = leakActivityLabel } else { longLabel = leakActivityLabel shortLabel = leakActivityLabel } } else { longLabel = fullLengthLabel shortLabel = fullLengthLabel } } val componentName = ComponentName(firstMainActivity.packageName, firstMainActivity.name) val shortcutCount = dynamicShortcuts.count { shortcutInfo -> shortcutInfo.activity == componentName } + shortcutManager.manifestShortcuts.count { shortcutInfo -> shortcutInfo.activity == componentName } if (shortcutCount >= shortcutManager.maxShortcutCountPerActivity) { return } val intent = leakDisplayActivityIntent intent.action = "Dummy Action because Android is stupid" val shortcut = Builder(application, DYNAMIC_SHORTCUT_ID) .setLongLabel(longLabel) .setShortLabel(shortLabel) .setActivity(componentName) .setIcon(Icon.createWithResource(application, R.mipmap.leak_canary_icon)) .setIntent(intent) .build() try { shortcutManager.addDynamicShortcuts(listOf(shortcut)) } catch (ignored: Throwable) { SharkLog.d(ignored) { "Could not add dynamic shortcut. " + "shortcutCount=$shortcutCount, " + "maxShortcutCountPerActivity=${shortcutManager.maxShortcutCountPerActivity}" } } } override fun onObjectRetained() { if (this::heapDumpTrigger.isInitialized) { heapDumpTrigger.onObjectRetained() } } fun onDumpHeapReceived(forceDump: Boolean) { if (this::heapDumpTrigger.isInitialized) { heapDumpTrigger.onDumpHeapReceived(forceDump) } } fun setEnabledBlocking( componentClassName: String, enabled: Boolean ) { val component = ComponentName(application, componentClassName) val newState = if (enabled) COMPONENT_ENABLED_STATE_ENABLED else COMPONENT_ENABLED_STATE_DISABLED // Blocks on IPC. application.packageManager.setComponentEnabledSetting(component, newState, DONT_KILL_APP) } inline fun <reified T : Any> noOpDelegate(): T { val javaClass = T::class.java val noOpHandler = InvocationHandler { _, _, _ -> // no op } return Proxy.newProxyInstance( javaClass.classLoader, arrayOf(javaClass), noOpHandler ) as T } private const val LEAK_CANARY_THREAD_NAME = "LeakCanary-Heap-Dump" }
kotlin
23
0.724693
98
31.301587
252
starcoderdata
<reponame>rainboy93/MVVMTemplate package app.web.drjackycv.data.network import app.web.drjackycv.data.base.ResponseObject import app.web.drjackycv.domain.base.Failure import app.web.drjackycv.domain.base.ResultState import retrofit2.Call open class BaseRemoteDataSource { fun <RO : List<ResponseObject<DO>>, DO : Any> syncRequest( request: Call<RO>, onResult: (ResultState<List<DO>?>) -> Unit ) { try { val response = request.execute() val data = response.body()?.map { it.toDomain() } ?: emptyList() onResult(ResultState.Success(data)) } catch (e: Exception) { onResult( ResultState.Error( Failure.FailureWithMessage(e.message ?: "Unknown Error"), null ) ) } } }
kotlin
24
0.604567
82
27.724138
29
starcoderdata
<filename>src/token/BooleanLiteral.kt package token class BooleanLiteral(val value: Boolean): Token(BOOLEAN) { override fun toString(): String { return "$value" } }
kotlin
13
0.696133
58
21.75
8
starcoderdata
<gh_stars>0 package io.github.serpro69.kfaker.provider import io.github.serpro69.kfaker.* import io.github.serpro69.kfaker.dictionary.* /** * [FakeDataProvider] implementation for [CategoryName.DRIVING_LICENCE] category. */ @Suppress("unused") class DrivingLicense internal constructor(fakerService: FakerService) : AbstractFakeDataProvider<DrivingLicense>(fakerService) { override val categoryName = CategoryName.DRIVING_LICENCE override val localUniqueDataProvider = LocalUniqueDataProvider<DrivingLicense>() override val unique by UniqueProviderDelegate(localUniqueDataProvider) fun license() = resolve("usa", "") fun licenseByState(state: String) = resolve("usa", state) }
kotlin
9
0.78602
128
38
18
starcoderdata
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.cds import com.intellij.diagnostic.VMOptions import com.intellij.execution.process.OSProcessUtil import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.projectRoots.JdkUtil import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.util.text.VersionComparatorUtil import com.sun.tools.attach.VirtualMachine import java.io.File import java.io.IOException import java.lang.management.ManagementFactory import java.time.Instant import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import kotlin.system.measureTimeMillis //TODO: report to FUS if we use AppCDS in the product object CDSManager { private val LOG = Logger.getInstance(javaClass) val isValidEnv: Boolean get() { // The AppCDS (JEP 310) is only added in JDK10, // The closest JRE we ship/support is 11 if (!SystemInfo.isJavaVersionAtLeast(11)) return false //AppCDS does not support Windows and macOS if (!SystemInfo.isLinux) { //Specific patches are included into JetBrains runtime //to support Windows and macOS if (!SystemInfo.isJetBrainsJvm) return false if (VersionComparatorUtil.compare(SystemInfo.JAVA_RUNTIME_VERSION, "11.0.4+10-b520.2") < 0) return false } return true } val isRunningWithCDS: Boolean get() { return isValidEnv && currentCDSArchive?.isFile == true } val canBuildOrUpdateCDS: Boolean get() { if (!isValidEnv) return false val paths = CDSPaths.current() return !paths.isSame(currentCDSArchive) } private val currentCDSArchive: File? get() { val arguments = ManagementFactory.getRuntimeMXBean().inputArguments val xShare = arguments.any { it == "-Xshare:auto" || it == "-Xshare:on" } if (!xShare) return null val key = "-XX:SharedArchiveFile=" return arguments.firstOrNull { it.startsWith(key) }?.removePrefix(key)?.let(::File) } fun cleanupStaleCDSFiles(indicator: ProgressIndicator) = rejectIfRunning(Unit) { val paths = CDSPaths.current() val currentCDSPath = currentCDSArchive val files = paths.baseDir.listFiles() ?: arrayOf() if (files.isEmpty()) return indicator.text2 = "Removing old Class Data Sharing files..." for (path in files) { indicator.checkCanceled() if (path != currentCDSPath && !paths.isOurFile(path)) { FileUtil.delete(path) } } } fun installCDS(indicator: ProgressIndicator): CDSPaths? = rejectIfRunning(null) { if (VMOptions.getWriteFile() == null) { LOG.warn("VMOptions.getWriteFile() == null. Are you running from an IDE run configuration?") return null } val paths = CDSPaths.current() if (paths.isSame(currentCDSArchive)) { LOG.warn("CDS archive is already generated. Nothing to do") return null } if (paths.classesMarkerFile.isFile) { LOG.warn("CDS archive is already generated. The marker file exists") return null } paths.classesMarkerFile.writeText(Instant.now().toString()) // we need roughly 400mb of disk space, let's avoid disk space pressure if (paths.baseDir.freeSpace < 3L * 1024 * FileUtil.MEGABYTE) { LOG.warn("Not enough disk space to enable CDS archive") return null } LOG.info("Starting generation of CDS archive to the ${paths.classesArchiveFile} and ${paths.classesArchiveFile} files") indicator.text2 = "Collecting classes list..." indicator.checkCanceled() val durationList = measureTimeMillis { try { val agentPath = run { val libPath = File(PathManager.getLibPath()) / "cds" / "classesLogAgent.jar" if (libPath.isFile) return@run libPath LOG.warn("Failed to find bundled CDS classes agent in $libPath") //consider local debug IDE case val probe = File(PathManager.getHomePath()) / "out" / "classes" / "artifacts" / "classesLogAgent_jar" / "classesLogAgent.jar" if (probe.isFile) return@run probe error("Failed to resolve path to the CDS agent") } val vm = VirtualMachine.attach(OSProcessUtil.getApplicationPid()) try { vm.loadAgent(agentPath.path, "${paths.classesListFile}") } finally { vm.detach() } } catch (t: Throwable) { LOG.warn("Failed to attach CDS Java Agent to the running IDE instance. ${t.message}\n" + "Please check you have -Djdk.attach.allowAttachSelf=true in the VM options of the IDE", t) return null } } LOG.info("CDS classes file is generated in ${StringUtil.formatDuration(durationList)}") indicator.text2 = "Generating classes archive..." indicator.checkCanceled() val logLevel = if (LOG.isDebugEnabled) "=debug" else "" val args = listOf( "-Djava.class.path=${ManagementFactory.getRuntimeMXBean().classPath}", "-Xlog:cds$logLevel", "-Xlog:class+path$logLevel", "-Xshare:dump", "-XX:+UnlockDiagnosticVMOptions", "-XX:SharedClassListFile=${paths.classesListFile}", "-XX:SharedArchiveFile=${paths.classesArchiveFile}" ) JdkUtil.writeArgumentsToParameterFile(paths.classesPathFile, args) val durationLink = measureTimeMillis { val ext = if (SystemInfo.isWindows) ".exe" else "" val javaExe = File(System.getProperty("java.home")!!) / "bin" / "java$ext" val javaArgs = listOf( javaExe.path, "@${paths.classesPathFile}" ) val cwd = File(".").canonicalFile LOG.info("Running CDS generation process: $javaArgs in $cwd with classpath: ${args}") indicator.checkCanceled() //recreate logs file FileUtil.delete(paths.dumpOutputFile) val process = ProcessBuilder() .directory(cwd) .command(javaArgs) .redirectErrorStream(true) .redirectInput(ProcessBuilder.Redirect.PIPE) .redirectOutput(paths.dumpOutputFile) .start() try { process.outputStream.close() } catch (t: IOException) { //NOP } try { if (!process.waitFor(10, TimeUnit.MINUTES)) { LOG.warn("Failed to generate CDS archive, the process took too long and will be killed. See ${paths.dumpOutputFile} for details") process.destroyForcibly() return null } } catch (t: InterruptedException) { LOG.warn("Failed to generate CDS archive, the process is interrupted") process.destroyForcibly() return null } val exitValue = process.exitValue() if (exitValue != 0) { LOG.warn("Failed to generate CDS archive, the process existed with code $exitValue. See ${paths.dumpOutputFile} for details") return null } } VMOptions.writeEnableCDSArchiveOption(paths.classesArchiveFile.absolutePath) LOG.warn("Enabled CDS archive from ${paths.classesArchiveFile}, " + "size = ${StringUtil.formatFileSize(paths.classesArchiveFile.length())}, " + "it took ${StringUtil.formatDuration(durationLink)} (VMOptions were updated)") return paths } fun removeCDS() = rejectIfRunning(Unit) { if (!isRunningWithCDS) return VMOptions.writeDisableCDSArchiveOption() LOG.warn("Disabled CDS") } private operator fun File.div(s: String) = File(this, s) private val ourIsRunning = AtomicBoolean(false) private inline fun <T> rejectIfRunning(rejected: T, action: () -> T): T { if (!ourIsRunning.compareAndSet(false, true)) return rejected try { return action() } finally { ourIsRunning.set(false) } } }
kotlin
37
0.671526
140
32.4375
240
starcoderdata
<filename>app/src/main/java/com/docwei/retrofitdemo/model/CardModule.kt package com.docwei.retrofitdemo.model data class CardModule( val padResourceUrl: String, val resourceUrl: String, val router: String )
kotlin
10
0.776256
71
26.5
8
starcoderdata
<reponame>f3401pal/WeatherAndNews<filename>app/src/main/java/com/f3401pal/accuweather/presentation/MainViewModel.kt package com.f3401pal.accuweather.presentation import android.app.Application import android.location.Geocoder import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.f3401pal.accuweather.domain.usecase.GetCurrentWeather import com.f3401pal.accuweather.domain.usecase.GetTopHeadline import com.f3401pal.accuweather.domain.usecase.GetWeatherForecast import com.f3401pal.accuweather.domain.model.CurrentWeatherItem import com.f3401pal.accuweather.domain.model.NewsItem import com.f3401pal.accuweather.domain.model.WeatherForecastItem import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch class MainViewModel @ViewModelInject constructor( application: Application, private val getCurrentWeather: GetCurrentWeather, private val getWeatherForecast: GetWeatherForecast, private val getTopHeadline: GetTopHeadline ) : AndroidViewModel(application) { private val curJob = SupervisorJob() private val bgContext: CoroutineScope = CoroutineScope(Dispatchers.Default + curJob) private val geoCoder: Geocoder = Geocoder(application) private val _currentWeather: MutableLiveData<CurrentWeatherItem> = MutableLiveData() val currentWeather: LiveData<CurrentWeatherItem> = _currentWeather private val _weatherForecast: MutableLiveData<WeatherForecastItem> = MutableLiveData() val weatherForecast: LiveData<WeatherForecastItem> = _weatherForecast private val _topHeadline: MutableLiveData<List<NewsItem>> = MutableLiveData() val topHeadline: LiveData<List<NewsItem>> = _topHeadline private val _error: MutableLiveData<String?> = MutableLiveData() val error: LiveData<String?> = _error init { loadAll(INITIAL_QUERY) } fun loadAll(query: String) { bgContext.launch { geoCoder.getFromLocationName(query, 1).firstOrNull()?.let { _currentWeather.postValue(getCurrentWeather.execute(it.locality)) _weatherForecast.postValue(getWeatherForecast.execute(it.locality)) _topHeadline.postValue(getTopHeadline.execute(it.countryCode)) } ?: _error.postValue("Could not find city by \"$query\"") } } override fun onCleared() { super.onCleared() curJob.cancel() } companion object { private const val INITIAL_QUERY = "Calgary" } }
kotlin
27
0.767871
115
38.686567
67
starcoderdata
<gh_stars>0 package <%= appPackage %>.data.example.file.file.entity import com.google.gson.annotations.SerializedName /** * Created by Dwi_Ari on 10/13/17. */ data class ExampleListEntity( @SerializedName("data") val data: List<ExampleEntity> )
kotlin
9
0.695489
55
19.461538
13
starcoderdata
<gh_stars>0 package mobdao.com.openquiz.modules.base import androidx.activity.OnBackPressedCallback import androidx.annotation.StringRes import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import mobdao.com.openquiz.R import mobdao.com.openquiz.utils.extensions.navigate import mobdao.com.openquiz.utils.extensions.setupObserver import mobdao.com.openquiz.utils.helpers.DialogHelper abstract class BaseFragment : Fragment() { protected open val viewModel: BaseViewModel? = null @Suppress("RedundantLambdaArrow") protected fun setupGenericErrorObserver() = viewModel?.run { setupObserver( genericErrorEvent to { _ -> showDefaultErrorDialog() } ) } protected fun setupNavigationObserver() = viewModel?.run { setupObserver( routeEvent to { direction -> navigate(direction) } ) } protected fun onBackPressed(callback: () -> Unit) { requireActivity().onBackPressedDispatcher.addCallback( this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { callback() } } ) } protected fun showAlertDialog( title: String? = null, message: String? = null, @StringRes positiveButtonText: Int? = android.R.string.ok, @StringRes negativeButtonText: Int? = null, positiveCallback: (() -> Unit)? = null, negativeCallback: (() -> Unit)? = null, dismissCallback: (() -> Unit)? = null, cancelable: Boolean = true, ) { AlertDialog.Builder(requireContext()).apply { title?.let(::setTitle) message?.let(::setMessage) dismissCallback?.run { setOnDismissListener { invoke() } } positiveButtonText?.let { setPositiveButton(positiveButtonText) { dialog, _ -> dialog.dismiss() positiveCallback?.invoke() } } negativeButtonText?.let { setNegativeButton(negativeButtonText) { dialog, _ -> dialog.dismiss() negativeCallback?.invoke() } } setCancelable(cancelable) }.create().show() } // region private private fun showDefaultErrorDialog() { DialogHelper.buildDialog( context ?: return, title = R.string.ops, message = R.string.something_wrong ).show() } // endregion }
kotlin
28
0.579644
70
29.732558
86
starcoderdata
<reponame>karthikv8058/kitchen-app<filename>android/app/src/main/java/com/smarttoni/guestgroup/entities/Guest.kt<gh_stars>0 package com.smarttoni.guestgroup.entities import androidx.room.Entity @Entity class Guest(var name: String)
kotlin
13
0.82906
123
32.571429
7
starcoderdata
<gh_stars>0 package com.stripe.samplestore import java.text.DecimalFormat import java.util.Currency import kotlin.math.pow /** * Class for utility functions. */ internal object StoreUtils { private const val CURRENCY_SIGN = '\u00A4' fun getEmojiByUnicode(unicode: Int): String { return String(Character.toChars(unicode)) } fun getPriceString(price: Long, currency: Currency?): String { val displayCurrency = currency ?: Currency.getInstance("USD") val fractionDigits = displayCurrency.defaultFractionDigits val totalLength = price.toString().length val builder = StringBuilder().append(CURRENCY_SIGN) if (fractionDigits == 0) { for (i in 0 until totalLength) { builder.append('#') } val noDecimalCurrencyFormat = DecimalFormat(builder.toString()) noDecimalCurrencyFormat.currency = displayCurrency return noDecimalCurrencyFormat.format(price) } val beforeDecimal = totalLength - fractionDigits for (i in 0 until beforeDecimal) { builder.append('#') } // So we display "$0.55" instead of "$.55" if (totalLength <= fractionDigits) { builder.append('0') } builder.append('.') for (i in 0 until fractionDigits) { builder.append('0') } val modBreak = 10.0.pow(fractionDigits.toDouble()) val decimalPrice = price / modBreak val decimalFormat = DecimalFormat(builder.toString()) decimalFormat.currency = displayCurrency return decimalFormat.format(decimalPrice) } }
kotlin
17
0.629563
75
29.381818
55
starcoderdata
package com.rentmycar.rentmycar.network.response data class PostPaymentResponse( val id: Int, val reservationNumber: String, val userId: Int, val price: Double, val paymentStatus: String, val paymentMethod: String, val paidAt: String?, val createdAt: String, val updatedAt: String )
kotlin
6
0.70625
48
23.615385
13
starcoderdata
<gh_stars>0 package com.noway.gg.toutiao.base /** * 包名: com.noway.gg.toutiao.base * 标题: * 描述: TODO * 作者: NoWay * 邮箱: <EMAIL> * 日期: 2017/12/21 * 版本: V-1.0.0 */ interface FragmentPresenter<V : IBaseFragmentView>{ fun attachView(view: V) fun detachView() }
kotlin
7
0.589041
51
15.277778
18
starcoderdata
<gh_stars>0 import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF02622" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 5 to 10 16 to 21 } value = "#1f3703" } color { location { 24 to 26 82 to 84 } value = "#9c0a89" } color { location { 27 to 28 79 to 80 } value = "#d1591c" } color { location { 33 to 35 73 to 75 } value = "#c98afe" } color { location { 38 to 40 68 to 70 } value = "#9b4483" } color { location { 42 to 43 65 to 66 } value = "#3de198" } color { location { 45 to 46 62 to 63 } value = "#163f5e" } color { location { 49 to 52 58 to 61 } value = "#4a370d" } color { location { 87 to 89 110 to 112 } value = "#b328ae" } color { location { 94 to 95 102 to 103 } value = "#053f5f" } color { location { 11 to 15 } value = "#7b6da8" } color { location { 27 to 26 81 to 81 } value = "#f5766d" } color { location { 29 to 32 76 to 78 } value = "#966d85" } color { location { 36 to 37 71 to 72 } value = "#3fc198" } color { location { 41 to 41 67 to 67 } value = "#64ac30" } color { location { 44 to 44 64 to 64 } value = "#2dd8ad" } color { location { 47 to 48 62 to 61 } value = "#0eb1b4" } color { location { 53 to 57 } value = "#8ccc85" } color { location { 90 to 93 104 to 109 } value = "#8f460f" } color { location { 96 to 101 } value = "#c71d13" } color { location { 1 to 4 } value = "#23e6a1" } color { location { 22 to 23 } value = "#45343d" } color { location { 85 to 86 } value = "#cf5677" } color { location { 113 to 116 } value = "#81d60a" } } }
kotlin
24
0.262632
48
14.733624
229
starcoderdata
package no.nav.syfo.domain.inntektsmelding enum class Naturalytelse { KOSTDOEGN, LOSJI, ANNET, SKATTEPLIKTIGDELFORSIKRINGER, BIL, KOSTDAGER, RENTEFORDELLAAN, BOLIG, ELEKTRONISKKOMMUNIKASJON, AKSJERGRUNNFONDSBEVISTILUNDERKURS, OPSJONER, KOSTBESPARELSEIHJEMMET, FRITRANSPORT, BEDRIFTSBARNEHAGEPLASS, TILSKUDDBARNEHAGEPLASS, BESOEKSREISERHJEMMETANNET, INNBETALINGTILUTENLANDSKPENSJONSORDNING, YRKEBILTJENESTLIGBEHOVLISTEPRIS, YRKEBILTJENESTLIGBEHOVKILOMETER }
kotlin
4
0.880952
388
91.4
5
starcoderdata
package org.arend.psi.ext import com.intellij.lang.ASTNode import com.intellij.psi.search.LocalSearchScope import org.arend.naming.reference.ClassReferable import org.arend.psi.ArendExpr import org.arend.psi.ArendLetClause import org.arend.psi.ArendNameTele import org.arend.psi.ArendNewExpr import org.arend.term.abs.Abstract import org.arend.resolving.util.ReferableExtractVisitor abstract class ArendLetClauseImplMixin(node: ASTNode) : ArendCompositeElementImpl(node), ArendLetClause { override fun getReferable() = defIdentifier override fun getPattern(): Abstract.LetClausePattern? = letClausePattern override fun getParameters(): List<ArendNameTele> = nameTeleList override fun getResultType(): ArendExpr? = typeAnnotation?.expr override fun getTerm(): ArendExpr? = expr override fun getUseScope() = LocalSearchScope(parent) val typeClassReference: ClassReferable? get() { val type = resultType ?: (expr as? ArendNewExpr)?.let { if (it.appPrefix?.newKw != null) it.argumentAppExpr else null } ?: return null return if (parameters.all { !it.isExplicit }) ReferableExtractVisitor().findClassReferable(type) else null } override fun getTopmostEquivalentSourceNode() = getTopmostEquivalentSourceNode(this) override fun getParentSourceNode() = getParentSourceNode(this) }
kotlin
19
0.76674
146
36.777778
36
starcoderdata
<reponame>arbelkilani/To-Do-Sample-App<gh_stars>0 package edu.arbelkilani.to_doapp.data.models enum class Priority { HIGH, MEDIUM, LOW }
kotlin
8
0.765957
49
22.666667
6
starcoderdata
package com.stripe.android.view import android.content.Context import androidx.test.core.app.ApplicationProvider import com.stripe.android.CardNumberFixtures.AMEX_NO_SPACES import com.stripe.android.CardNumberFixtures.AMEX_WITH_SPACES import com.stripe.android.CardNumberFixtures.DINERS_CLUB_14_NO_SPACES import com.stripe.android.CardNumberFixtures.DINERS_CLUB_14_WITH_SPACES import com.stripe.android.CardNumberFixtures.DINERS_CLUB_16_NO_SPACES import com.stripe.android.CardNumberFixtures.DINERS_CLUB_16_WITH_SPACES import com.stripe.android.CardNumberFixtures.VISA_NO_SPACES import com.stripe.android.CardNumberFixtures.VISA_WITH_SPACES import com.stripe.android.model.CardBrand import com.stripe.android.testharness.ViewTestUtils import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner /** * Test class for [CardNumberEditText]. */ @RunWith(RobolectricTestRunner::class) class CardNumberEditTextTest { private var completionCallbackInvocations = 0 private val completionCallback: () -> Unit = { completionCallbackInvocations++ } private var lastBrandChangeCallbackInvocation: CardBrand? = null private val brandChangeCallback: (CardBrand) -> Unit = { lastBrandChangeCallbackInvocation = it } private val cardNumberEditText: CardNumberEditText by lazy { CardNumberEditText(ApplicationProvider.getApplicationContext<Context>()) } @BeforeTest fun setup() { cardNumberEditText.setText("") cardNumberEditText.completionCallback = completionCallback cardNumberEditText.brandChangeCallback = brandChangeCallback } @Test fun updateSelectionIndex_whenVisa_increasesIndexWhenGoingPastTheSpaces() { // Directly setting card brand as a testing hack (annotated in source) cardNumberEditText.cardBrand = CardBrand.Visa // Adding 1 character, starting at position 4, with a final string length 6 assertEquals(6, cardNumberEditText.updateSelectionIndex(6, 4, 1)) assertEquals(6, cardNumberEditText.updateSelectionIndex(8, 4, 1)) assertEquals(11, cardNumberEditText.updateSelectionIndex(11, 9, 1)) assertEquals(16, cardNumberEditText.updateSelectionIndex(16, 14, 1)) } @Test fun updateSelectionIndex_whenAmEx_increasesIndexWhenGoingPastTheSpaces() { cardNumberEditText.cardBrand = CardBrand.AmericanExpress assertEquals(6, cardNumberEditText.updateSelectionIndex(6, 4, 1)) assertEquals(13, cardNumberEditText.updateSelectionIndex(13, 11, 1)) } @Test fun updateSelectionIndex_whenDinersClub_decreasesIndexWhenDeletingPastTheSpaces() { cardNumberEditText.cardBrand = CardBrand.DinersClub assertEquals(4, cardNumberEditText.updateSelectionIndex(6, 5, 0)) assertEquals(9, cardNumberEditText.updateSelectionIndex(13, 10, 0)) assertEquals(14, cardNumberEditText.updateSelectionIndex(17, 15, 0)) } @Test fun updateSelectionIndex_whenDeletingNotOnGaps_doesNotDecreaseIndex() { cardNumberEditText.cardBrand = CardBrand.DinersClub assertEquals(7, cardNumberEditText.updateSelectionIndex(12, 7, 0)) } @Test fun updateSelectionIndex_whenAmEx_decreasesIndexWhenDeletingPastTheSpaces() { cardNumberEditText.cardBrand = CardBrand.AmericanExpress assertEquals(4, cardNumberEditText.updateSelectionIndex(10, 5, 0)) assertEquals(11, cardNumberEditText.updateSelectionIndex(13, 12, 0)) } @Test fun updateSelectionIndex_whenSelectionInTheMiddle_increasesIndexOverASpace() { cardNumberEditText.cardBrand = CardBrand.Visa assertEquals(6, cardNumberEditText.updateSelectionIndex(10, 4, 1)) } @Test fun updateSelectionIndex_whenPastingIntoAGap_includesTheGapJump() { cardNumberEditText.cardBrand = CardBrand.Unknown assertEquals(11, cardNumberEditText.updateSelectionIndex(12, 8, 2)) } @Test fun updateSelectionIndex_whenPastingOverAGap_includesTheGapJump() { cardNumberEditText.cardBrand = CardBrand.Unknown assertEquals(9, cardNumberEditText.updateSelectionIndex(12, 3, 5)) } @Test fun updateSelectionIndex_whenIndexWouldGoOutOfBounds_setsToEndOfString() { cardNumberEditText.cardBrand = CardBrand.Visa // This case could happen when you paste over 5 digits with only 2 assertEquals(3, cardNumberEditText.updateSelectionIndex(3, 3, 2)) } @Test fun setText_whenTextIsValidCommonLengthNumber_changesCardValidState() { cardNumberEditText.setText(VISA_WITH_SPACES) assertTrue(cardNumberEditText.isCardNumberValid) assertEquals(1, completionCallbackInvocations) } @Test fun setText_whenTextIsSpacelessValidNumber_changesToSpaceNumberAndValidates() { cardNumberEditText.setText(VISA_NO_SPACES) assertTrue(cardNumberEditText.isCardNumberValid) assertEquals(1, completionCallbackInvocations) } @Test fun setText_whenTextIsValidAmExDinersClubLengthNumber_changesCardValidState() { cardNumberEditText.setText(AMEX_WITH_SPACES) assertTrue(cardNumberEditText.isCardNumberValid) assertEquals(1, completionCallbackInvocations) } @Test fun setText_whenTextChangesFromValidToInvalid_changesCardValidState() { cardNumberEditText.setText(VISA_WITH_SPACES) // Simply setting the value interacts with this mock once -- that is tested elsewhere completionCallbackInvocations = 0 var mutable = cardNumberEditText.text.toString() // Removing a single character should make this invalid mutable = mutable.substring(0, 18) cardNumberEditText.setText(mutable) assertFalse(cardNumberEditText.isCardNumberValid) assertEquals(0, completionCallbackInvocations) } @Test fun setText_whenTextIsInvalidCommonLengthNumber_doesNotNotifyListener() { // This creates a full-length but not valid number: 4242 4242 4242 4243 val almostValid = VISA_WITH_SPACES.substring(0, 18) + "3" cardNumberEditText.setText(almostValid) assertFalse(cardNumberEditText.isCardNumberValid) assertEquals(0, completionCallbackInvocations) } @Test fun whenNotFinishedTyping_doesNotSetErrorValue() { // We definitely shouldn't start out in an error state. assertFalse(cardNumberEditText.shouldShowError) cardNumberEditText.setText(cardNumberEditText.text?.toString() + "123") assertFalse(cardNumberEditText.shouldShowError) } @Test fun finishTypingCommonLengthCardNumber_whenValidCard_doesNotSetErrorValue() { val almostThere = VISA_WITH_SPACES.substring(0, 18) cardNumberEditText.setText(almostThere) assertFalse(cardNumberEditText.shouldShowError) // We now have the valid 4242 Visa cardNumberEditText.setText(cardNumberEditText.text?.toString() + "2") assertFalse(cardNumberEditText.shouldShowError) } @Test fun finishTypingCommonLengthCardNumber_whenInvalidCard_setsErrorValue() { val almostThere = VISA_WITH_SPACES.substring(0, 18) cardNumberEditText.setText(almostThere) // This makes the number officially invalid cardNumberEditText.setText(cardNumberEditText.text?.toString() + "3") assertTrue(cardNumberEditText.shouldShowError) } @Test fun finishTypingInvalidCardNumber_whenFollowedByDelete_setsErrorBackToFalse() { val notQuiteValid = VISA_WITH_SPACES.substring(0, 18) + "3" cardNumberEditText.setText(notQuiteValid) assertTrue(cardNumberEditText.shouldShowError) // Now that we're in an error state, back up by one ViewTestUtils.sendDeleteKeyEvent(cardNumberEditText) assertFalse(cardNumberEditText.shouldShowError) } @Test fun finishTypingDinersClub14_whenInvalid_setsErrorValueAndRemovesItAppropriately() { val notQuiteValid = DINERS_CLUB_14_WITH_SPACES.take(DINERS_CLUB_14_WITH_SPACES.length - 1) + "3" cardNumberEditText.setText(notQuiteValid) assertTrue(cardNumberEditText.shouldShowError) // Now that we're in an error state, back up by one ViewTestUtils.sendDeleteKeyEvent(cardNumberEditText) assertFalse(cardNumberEditText.shouldShowError) cardNumberEditText.setText(cardNumberEditText.text?.toString() + DINERS_CLUB_14_WITH_SPACES.last()) assertFalse(cardNumberEditText.shouldShowError) } @Test fun finishTypingDinersClub16_whenInvalid_setsErrorValueAndRemovesItAppropriately() { val notQuiteValid = DINERS_CLUB_16_WITH_SPACES.take(DINERS_CLUB_16_WITH_SPACES.length - 1) + "3" cardNumberEditText.setText(notQuiteValid) assertTrue(cardNumberEditText.shouldShowError) // Now that we're in an error state, back up by one ViewTestUtils.sendDeleteKeyEvent(cardNumberEditText) assertFalse(cardNumberEditText.shouldShowError) cardNumberEditText.setText(cardNumberEditText.text?.toString() + DINERS_CLUB_16_WITH_SPACES.last()) assertFalse(cardNumberEditText.shouldShowError) } @Test fun finishTypingAmEx_whenInvalid_setsErrorValueAndRemovesItAppropriately() { val notQuiteValid = AMEX_WITH_SPACES.substring(0, 16) + "3" cardNumberEditText.setText(notQuiteValid) assertTrue(cardNumberEditText.shouldShowError) // Now that we're in an error state, back up by one ViewTestUtils.sendDeleteKeyEvent(cardNumberEditText) assertFalse(cardNumberEditText.shouldShowError) cardNumberEditText.setText(cardNumberEditText.text?.toString() + "5") assertFalse(cardNumberEditText.shouldShowError) } @Test fun setCardBrandChangeListener_callsSetCardBrand() { assertEquals(CardBrand.Unknown, lastBrandChangeCallbackInvocation) } @Test fun addVisaPrefix_callsBrandListener() { // We reset because just attaching the listener calls the method once. lastBrandChangeCallbackInvocation = null // There is only one Visa Prefix. cardNumberEditText.setText(cardNumberEditText.text?.toString() + CardBrand.Visa.prefixes[0]) assertEquals(CardBrand.Visa, lastBrandChangeCallbackInvocation) } @Test fun addAmExPrefix_callsBrandListener() { CardBrand.AmericanExpress.prefixes.forEach( verifyCardBrandPrefix(CardBrand.AmericanExpress) ) } @Test fun addDinersClubPrefix_callsBrandListener() { CardBrand.DinersClub.prefixes.forEach(verifyCardBrandPrefix(CardBrand.DinersClub)) } @Test fun addDiscoverPrefix_callsBrandListener() { CardBrand.Discover.prefixes.forEach(verifyCardBrandPrefix(CardBrand.Discover)) } @Test fun addMasterCardPrefix_callsBrandListener() { CardBrand.MasterCard.prefixes.forEach(verifyCardBrandPrefix(CardBrand.MasterCard)) } @Test fun addJCBPrefix_callsBrandListener() { CardBrand.JCB.prefixes.forEach(verifyCardBrandPrefix(CardBrand.JCB)) } @Test fun enterCompleteNumberInParts_onlyCallsBrandListenerOnce() { lastBrandChangeCallbackInvocation = null val prefix = AMEX_WITH_SPACES.substring(0, 2) val suffix = AMEX_WITH_SPACES.substring(2) cardNumberEditText.setText(cardNumberEditText.text?.toString() + prefix) cardNumberEditText.setText(cardNumberEditText.text?.toString() + suffix) assertEquals(CardBrand.AmericanExpress, lastBrandChangeCallbackInvocation) } @Test fun enterBrandPrefix_thenDelete_callsUpdateWithUnknown() { lastBrandChangeCallbackInvocation = null val dinersPrefix = CardBrand.DinersClub.prefixes[0] // All the Diners Club prefixes are longer than one character, but I specifically want // to test that a nonempty string still triggers this action, so this test will fail if // the Diners Club prefixes are ever changed. assertTrue(dinersPrefix.length > 1) cardNumberEditText.setText(cardNumberEditText.text?.toString() + dinersPrefix) assertEquals(CardBrand.DinersClub, lastBrandChangeCallbackInvocation) ViewTestUtils.sendDeleteKeyEvent(cardNumberEditText) assertEquals(CardBrand.Unknown, lastBrandChangeCallbackInvocation) } @Test fun enterBrandPrefix_thenClearAllText_callsUpdateWithUnknown() { lastBrandChangeCallbackInvocation = null val prefixVisa = CardBrand.Visa.prefixes[0] cardNumberEditText.setText(cardNumberEditText.text?.toString() + prefixVisa) assertEquals(CardBrand.Visa, lastBrandChangeCallbackInvocation) // Just adding some other text. Not enough to invalidate the card or complete it. lastBrandChangeCallbackInvocation = null cardNumberEditText.setText(cardNumberEditText.text?.toString() + "123") assertNull(lastBrandChangeCallbackInvocation) // This simulates the user selecting all text and deleting it. cardNumberEditText.setText("") assertEquals(CardBrand.Unknown, lastBrandChangeCallbackInvocation) } @Test fun cardNumber_withSpaces_returnsCardNumberWithoutSpaces() { cardNumberEditText.setText(VISA_WITH_SPACES) assertEquals(VISA_NO_SPACES, cardNumberEditText.cardNumber) cardNumberEditText.setText("") cardNumberEditText.setText(AMEX_WITH_SPACES) assertEquals(AMEX_NO_SPACES, cardNumberEditText.cardNumber) cardNumberEditText.setText("") cardNumberEditText.setText(DINERS_CLUB_14_WITH_SPACES) assertEquals(DINERS_CLUB_14_NO_SPACES, cardNumberEditText.cardNumber) cardNumberEditText.setText("") cardNumberEditText.setText(DINERS_CLUB_16_WITH_SPACES) assertEquals(DINERS_CLUB_16_NO_SPACES, cardNumberEditText.cardNumber) } @Test fun getCardNumber_whenIncompleteCard_returnsNull() { cardNumberEditText.setText( DINERS_CLUB_14_WITH_SPACES .substring(0, DINERS_CLUB_14_WITH_SPACES.length - 2)) assertNull(cardNumberEditText.cardNumber) } @Test fun getCardNumber_whenInvalidCardNumber_returnsNull() { var almostVisa = VISA_WITH_SPACES.substring(0, VISA_WITH_SPACES.length - 1) almostVisa += "3" // creates the 4242 4242 4242 4243 bad number cardNumberEditText.setText(almostVisa) assertNull(cardNumberEditText.cardNumber) } @Test fun getCardNumber_whenValidNumberIsChangedToInvalid_returnsNull() { cardNumberEditText.setText(AMEX_WITH_SPACES) ViewTestUtils.sendDeleteKeyEvent(cardNumberEditText) assertNull(cardNumberEditText.cardNumber) } @Test fun testUpdateCardBrandFromNumber() { cardNumberEditText.updateCardBrandFromNumber(DINERS_CLUB_14_NO_SPACES) assertEquals(CardBrand.DinersClub, lastBrandChangeCallbackInvocation) cardNumberEditText.updateCardBrandFromNumber(AMEX_NO_SPACES) assertEquals(CardBrand.AmericanExpress, lastBrandChangeCallbackInvocation) } private fun verifyCardBrandPrefix(cardBrand: CardBrand): (String) -> Unit { return { prefix -> // Reset inside the loop so we don't count each prefix lastBrandChangeCallbackInvocation = null cardNumberEditText.setText(cardNumberEditText.text?.toString() + prefix) assertEquals(cardBrand, lastBrandChangeCallbackInvocation) cardNumberEditText.setText("") } } }
kotlin
19
0.737427
107
39.797927
386
starcoderdata
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins import com.intellij.openapi.extensions.PluginId import com.intellij.util.io.Compressor import com.intellij.util.io.write import org.intellij.lang.annotations.Language import java.io.ByteArrayOutputStream import java.io.OutputStream import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.atomic.AtomicInteger private val pluginIdCounter = AtomicInteger() fun plugin(outDir: Path, @Language("XML") descriptor: String) { val rawDescriptor = try { readModuleDescriptorForTest(descriptor.toByteArray()) } catch (e: Throwable) { throw RuntimeException("Cannot parse:\n ${descriptor.trimIndent().prependIndent(" ")}", e) } outDir.resolve("${rawDescriptor.id!!}/META-INF/plugin.xml").write(descriptor.trimIndent()) } fun module(outDir: Path, ownerId: String, moduleId: String, @Language("XML") descriptor: String) { try { readModuleDescriptorForTest(descriptor.toByteArray()) } catch (e: Throwable) { throw RuntimeException("Cannot parse:\n ${descriptor.trimIndent().prependIndent(" ")}", e) } outDir.resolve("$ownerId/$moduleId.xml").write(descriptor.trimIndent()) } class PluginBuilder { private data class ExtensionBlock(val ns: String, val text: String) private data class DependsTag(val pluginId: String, val configFile: String?) // counter is used to reduce plugin id length var id: String = "p_${pluginIdCounter.incrementAndGet()}" private set private var implementationDetail = false private var name: String? = null private var description: String? = null private var packagePrefix: String? = null private val dependsTags = mutableListOf<DependsTag>() private var applicationListeners: String? = null private var actions: String? = null private val extensions = mutableListOf<ExtensionBlock>() private var extensionPoints: String? = null private var untilBuild: String? = null private var version: String? = null private val content = mutableListOf<PluginContentDescriptor.ModuleItem>() private val dependencies = mutableListOf<ModuleDependenciesDescriptor.ModuleReference>() private val pluginDependencies = mutableListOf<ModuleDependenciesDescriptor.PluginReference>() private val subDescriptors = HashMap<String, PluginBuilder>() init { depends("com.intellij.modules.lang") } fun id(id: String): PluginBuilder { this.id = id return this } fun randomId(idPrefix: String): PluginBuilder { this.id = "${idPrefix}_${pluginIdCounter.incrementAndGet()}" return this } fun name(name: String): PluginBuilder { this.name = name return this } fun description(description: String): PluginBuilder { this.description = description return this } fun packagePrefix(value: String?): PluginBuilder { packagePrefix = value return this } fun depends(pluginId: String, configFile: String? = null): PluginBuilder { dependsTags.add(DependsTag(pluginId, configFile)) return this } fun depends(pluginId: String, subDescriptor: PluginBuilder): PluginBuilder { val fileName = "dep_${pluginIdCounter.incrementAndGet()}.xml" subDescriptors.put("META-INF/$fileName", subDescriptor) depends(pluginId, fileName) return this } fun module(moduleName: String, moduleDescriptor: PluginBuilder): PluginBuilder { val fileName = "$moduleName.xml" subDescriptors.put(fileName, moduleDescriptor) content.add(PluginContentDescriptor.ModuleItem(name = moduleName, configFile = null)) // remove default dependency on lang moduleDescriptor.noDepends() return this } fun dependency(moduleName: String): PluginBuilder { dependencies.add(ModuleDependenciesDescriptor.ModuleReference(moduleName)) return this } fun pluginDependency(pluginId: String): PluginBuilder { pluginDependencies.add(ModuleDependenciesDescriptor.PluginReference(PluginId.getId(pluginId))) return this } fun noDepends(): PluginBuilder { dependsTags.clear() return this } fun untilBuild(buildNumber: String): PluginBuilder { untilBuild = buildNumber return this } fun version(version: String): PluginBuilder { this.version = version return this } fun applicationListeners(text: String): PluginBuilder { applicationListeners = text return this } fun actions(text: String): PluginBuilder { actions = text return this } fun extensions(text: String, ns: String = "com.intellij"): PluginBuilder { extensions.add(ExtensionBlock(ns, text)) return this } fun extensionPoints(@Language("XML") text: String): PluginBuilder { extensionPoints = text return this } fun implementationDetail(): PluginBuilder { implementationDetail = true return this } fun text(requireId: Boolean = true): String { return buildString { append("<idea-plugin") if (implementationDetail) { append(""" implementation-detail="true"""") } packagePrefix?.let { append(""" package="$it"""") } append(">") if (requireId) { append("<id>$id</id>") } name?.let { append("<name>$it</name>") } description?.let { append("<description>$it</description>") } for (dependsTag in dependsTags) { val configFile = dependsTag.configFile if (configFile != null) { append("""<depends optional="true" config-file="$configFile">${dependsTag.pluginId}</depends>""") } else { append("<depends>${dependsTag.pluginId}</depends>") } } version?.let { append("<version>$it</version>") } if (untilBuild != null) { append("""<idea-version until-build="${untilBuild}"/>""") } for (extensionBlock in extensions) { append("""<extensions defaultExtensionNs="${extensionBlock.ns}">${extensionBlock.text}</extensions>""") } extensionPoints?.let { append("<extensionPoints>$it</extensionPoints>") } applicationListeners?.let { append("<applicationListeners>$it</applicationListeners>") } actions?.let { append("<actions>$it</actions>") } if (content.isNotEmpty()) { append("\n<content>\n ") content.joinTo(this, separator = "\n ") { """<module name="${it.name}" />""" } append("\n</content>") } if (dependencies.isNotEmpty() || pluginDependencies.isNotEmpty()) { append("\n<dependencies>\n ") if (dependencies.isNotEmpty()) { dependencies.joinTo(this, separator = "\n ") { """<module name="${it.name}" />""" } } if (pluginDependencies.isNotEmpty()) { pluginDependencies.joinTo(this, separator = "\n ") { """<plugin id="${it.id}" />""" } } append("\n</dependencies>") } append("</idea-plugin>") } } fun build(path: Path): PluginBuilder { path.resolve("META-INF/plugin.xml").write(text()) writeSubDescriptors(path) return this } fun writeSubDescriptors(path: Path) { for ((fileName, subDescriptor) in subDescriptors) { path.resolve(fileName).write(subDescriptor.text(requireId = false)) subDescriptor.writeSubDescriptors(path) } } fun buildJar(path: Path): PluginBuilder { buildJarToStream(Files.newOutputStream(path)) return this } private fun buildJarToStream(outputStream: OutputStream) { Compressor.Zip(outputStream).use { it.addFile("META-INF/plugin.xml", text().toByteArray()) } } fun buildZip(path: Path): PluginBuilder { val jarStream = ByteArrayOutputStream() buildJarToStream(jarStream) val pluginName = name ?: id Compressor.Zip(Files.newOutputStream(path)).use { it.addDirectory(pluginName) it.addDirectory("$pluginName/lib") it.addFile("$pluginName/lib/$pluginName.jar", jarStream.toByteArray()) } return this } }
kotlin
27
0.683209
158
30.40625
256
starcoderdata
<filename>plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/gradle/GradleTaskIR.kt<gh_stars>0 // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.FreeIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.render import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter interface GradleTaskAccessIR : GradleIR data class GradleNamedTaskAccessIR( val name: String, val taskClass: String? = null ) : GradleTaskAccessIR { override fun GradlePrinter.renderGradle() { when (dsl) { GradlePrinter.GradleDsl.GROOVY -> { +"tasks.named('$name')" } GradlePrinter.GradleDsl.KOTLIN -> { +"tasks.named" taskClass?.let { +"<$it>" } +"(${name.quotified})" } } } } data class GradleByClassTasksAccessIR( @NonNls val taskClass: String ) : GradleTaskAccessIR { override fun GradlePrinter.renderGradle() { when (dsl) { GradlePrinter.GradleDsl.GROOVY -> { +"tasks.withType($taskClass)" } GradlePrinter.GradleDsl.KOTLIN -> { +"tasks.withType<$taskClass>" } } } } data class GradleByClassTasksCreateIR( val taskName: String, val taskClass: String ) : GradleTaskAccessIR { override fun GradlePrinter.renderGradle() { when (dsl) { GradlePrinter.GradleDsl.KOTLIN -> { +"val $taskName by tasks.creating($taskClass::class)" } GradlePrinter.GradleDsl.GROOVY -> { +"task($taskName, type: $taskClass)" } } } } data class GradleConfigureTaskIR( val taskAccess: GradleTaskAccessIR, val dependsOn: List<BuildSystemIR> = emptyList(), val irs: List<BuildSystemIR> = emptyList() ) : GradleIR, FreeIR { constructor( taskAccess: GradleTaskAccessIR, dependsOn: List<BuildSystemIR> = emptyList(), createIrs: IRsListBuilderFunction ) : this(taskAccess, dependsOn, createIrs.build()) override fun GradlePrinter.renderGradle() { taskAccess.render(this) +" " inBrackets { if (dependsOn.isNotEmpty()) { indent() call("dependsOn", forceBrackets = true) { dependsOn.list { it.render(this) } } nl() } irs.listNl() } } }
kotlin
29
0.619577
158
31.738636
88
starcoderdata
<reponame>06needhamt/intellij-community /* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.asJava.classes import org.jetbrains.kotlin.executeOnPooledThreadInReadAction import org.jetbrains.kotlin.findUsages.doTestWithFIRFlagsByPath import org.jetbrains.kotlin.idea.caches.resolve.LightClassTestCommon import org.jetbrains.kotlin.idea.caches.resolve.PsiElementChecker import org.jetbrains.kotlin.idea.caches.resolve.findClass import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.KotlinTestUtils import java.io.File abstract class AbstractFirLightClassTest : KotlinLightCodeInsightFixtureTestCase() { override fun isFirPlugin(): Boolean = true fun doTest(path: String) = doTestWithFIRFlagsByPath(path) { doTestImpl() } private fun doTestImpl() { val fileName = fileName() val extraFilePath = when { fileName.endsWith(fileExtension) -> fileName.replace(fileExtension, ".extra" + fileExtension) else -> error("Invalid test data extension") } val testFiles = if (File(testDataPath, extraFilePath).isFile) listOf(fileName, extraFilePath) else listOf(fileName) myFixture.configureByFiles(*testFiles.toTypedArray()) if ((myFixture.file as? KtFile)?.isScript() == true) { error { "FIR for scripts does not supported yet" } ScriptConfigurationManager.updateScriptDependenciesSynchronously(myFixture.file) } val ktFile = myFixture.file as KtFile val testData = testDataFile() val actual = executeOnPooledThreadInReadAction { LightClassTestCommon.getActualLightClassText( testData, { fqName -> findClass(fqName, ktFile, project)?.apply { PsiElementChecker.checkPsiElementStructure(this) } }, { it } ) }!! KotlinTestUtils.assertEqualsToFile(KotlinTestUtils.replaceExtension(testData, "java"), actual) } override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE open val fileExtension = ".kt" }
kotlin
29
0.714781
123
38.984615
65
starcoderdata
package com.github.aachartmodel.aainfographics.aaoptionsmodel class AADateTimeLabelFormats { var millisecond: String? = null var second: String? = null var minute: String? = null var hour: String? = null var day: String? = null var week: String? = null var month: String? = null var year: String? = null fun millisecond(prop: String?): AADateTimeLabelFormats { millisecond = prop return this } fun second(prop: String?): AADateTimeLabelFormats { second = prop return this } fun minute(prop: String?): AADateTimeLabelFormats { minute = prop return this } fun hour(prop: String?): AADateTimeLabelFormats { hour = prop return this } fun day(prop: String?): AADateTimeLabelFormats { day = prop return this } fun week(prop: String?): AADateTimeLabelFormats { week = prop return this } fun month(prop: String?): AADateTimeLabelFormats { month = prop return this } fun year(prop: String?): AADateTimeLabelFormats { year = prop return this } }
kotlin
8
0.605646
61
21.480769
52
starcoderdata
package com.architectcoders.openweather import android.app.Application class WeatherApp : Application() { override fun onCreate() { super.onCreate() initDI() } }
kotlin
9
0.675532
39
16.181818
11
starcoderdata
package de.dqmme.andimaru.command import de.dqmme.andimaru.manager.message import de.dqmme.andimaru.util.availableHomes import de.dqmme.andimaru.util.replace import de.dqmme.andimaru.util.setHome import de.dqmme.andimaru.util.setHomeGUI import net.axay.kspigot.gui.openGUI import net.axay.kspigot.main.KSpigotMainInstance import org.bukkit.command.CommandSender import org.bukkit.command.defaults.BukkitCommand import org.bukkit.entity.Player class SetHomeCommand : BukkitCommand("sethome") { private val server = KSpigotMainInstance.server init { server.commandMap.register("community", this) } override fun execute(sender: CommandSender, commandLabel: String, args: Array<out String>): Boolean { if (sender !is Player) { sender.sendMessage(message("not_a_player")) return false } if (args.isEmpty()) { sender.openGUI(sender.setHomeGUI()) } else if (args.size == 1) { val homeNumber = args[0].toIntOrNull() if (homeNumber == null) { sender.sendMessage( message("invalid_usage") .replace("\${command_usage}", "/sethome <home>") ) return false } if (homeNumber > sender.availableHomes()) { sender.sendMessage(message("not_enough_home_slots")) return false } val location = sender.location val worldName = location.world.name val x = location.blockX val y = location.blockY val z = location.blockZ sender.setHome(homeNumber, location) sender.sendMessage( message("home_set") .replace("\${home_number}", "$homeNumber.") .replace("\${world}", worldName) .replace("\${x}", x) .replace("\${y}", y) .replace("\${z}", z) ) } return true } override fun tabComplete(sender: CommandSender, alias: String, args: Array<out String>): MutableList<String> { if (sender !is Player) return mutableListOf() if (args.size == 1) { val homeSlotList = mutableListOf<String>() homeSlotList.add("1") homeSlotList.add("2") val availableHomes = sender.availableHomes() if (availableHomes >= 3) homeSlotList.add("3") if (availableHomes >= 4) homeSlotList.add("4") if (availableHomes >= 5) homeSlotList.add("5") return homeSlotList } return mutableListOf() } }
kotlin
29
0.569254
114
30.325581
86
starcoderdata
package com.example.weatherdemo.util import android.app.Activity import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkRequest import android.os.Handler import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import timber.log.Timber object NetworkNotifier { private val privateNetworkRestoredEvent = MutableLiveData<Event<Unit>>() val networkRestoredEvent: LiveData<Event<Unit>> = privateNetworkRestoredEvent @Volatile private var isNetworkAvailable = false private var connectivityManager: ConnectivityManager? = null private val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { super.onAvailable(network) Handler().postDelayed({ if (!isNetworkAvailable && !connectivityManager?.allNetworks.isNullOrEmpty()) { Timber.i("Network connection was restored, let's notify observers!") privateNetworkRestoredEvent.postValue(Event(Unit)) } isNetworkAvailable = true Timber.i("Some network became available. Available networks count: ${connectivityManager?.allNetworks?.size}") }, 1000) } override fun onLost(network: Network) { super.onLost(network) Handler().postDelayed({ isNetworkAvailable = !connectivityManager?.allNetworks.isNullOrEmpty() Timber.i("Some network was lost. Available networks count: ${connectivityManager?.allNetworks?.size}") }, 1000) } } fun turnOnUpdates(activity: Activity) { Timber.i("Updates are turned on") connectivityManager = activity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager isNetworkAvailable = !connectivityManager?.allNetworks.isNullOrEmpty() val networkRequest = NetworkRequest.Builder().build() connectivityManager?.registerNetworkCallback(networkRequest, networkCallback) } fun turnOffUpdates() { Timber.i("Updates are turned off") connectivityManager?.unregisterNetworkCallback(networkCallback) } }
kotlin
26
0.694945
126
37.576271
59
starcoderdata
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.jetbrains.uast.evaluation import com.intellij.lang.Language import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.psi.PsiMethod import org.jetbrains.uast.* import org.jetbrains.uast.values.UValue interface UEvaluatorExtension { companion object { val EXTENSION_POINT_NAME: ExtensionPointName<UEvaluatorExtension> = ExtensionPointName.create<UEvaluatorExtension>("org.jetbrains.uast.evaluation.UEvaluatorExtension") } @Deprecated("kept for binary compatibility, will be removed in IDEA 2019.2", ReplaceWith("org.jetbrains.uast.evaluation.UEvaluationInfoKt.to")) fun UValue.to(state: UEvaluationState): UEvaluationInfo = UEvaluationInfo(this, state) val language: Language fun evaluatePostfix( operator: UastPostfixOperator, operandValue: UValue, state: UEvaluationState ): UEvaluationInfo fun evaluatePrefix( operator: UastPrefixOperator, operandValue: UValue, state: UEvaluationState ): UEvaluationInfo fun evaluateBinary( binaryExpression: UBinaryExpression, leftValue: UValue, rightValue: UValue, state: UEvaluationState ): UEvaluationInfo fun evaluateQualified( accessType: UastQualifiedExpressionAccessType, receiverInfo: UEvaluationInfo, selectorInfo: UEvaluationInfo ): UEvaluationInfo fun evaluateMethodCall( target: PsiMethod, argumentValues: List<UValue>, state: UEvaluationState ): UEvaluationInfo fun evaluateVariable( variable: UVariable, state: UEvaluationState ): UEvaluationInfo }
kotlin
13
0.75989
105
29.194444
72
starcoderdata
package eu.kanade.tachiyomi.animeextension.it.animeworld import android.app.Application import android.content.SharedPreferences import androidx.preference.ListPreference import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.animeextension.it.animeworld.extractors.DoodExtractor import eu.kanade.tachiyomi.animeextension.it.animeworld.extractors.StreamSBExtractor import eu.kanade.tachiyomi.animeextension.it.animeworld.extractors.StreamTapeExtractor import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource import eu.kanade.tachiyomi.animesource.model.AnimeFilter import eu.kanade.tachiyomi.animesource.model.AnimeFilterList import eu.kanade.tachiyomi.animesource.model.SAnime import eu.kanade.tachiyomi.animesource.model.SEpisode import eu.kanade.tachiyomi.animesource.model.Video import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.util.asJsoup import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.lang.Exception class ANIMEWORLD : ConfigurableAnimeSource, ParsedAnimeHttpSource() { override val name = "ANIMEWORLD.tv" override val baseUrl = "https://www.animeworld.tv" override val lang = "it" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient private val preferences: SharedPreferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } // Popular Anime - Same Format as Search override fun popularAnimeSelector(): String = searchAnimeSelector() override fun popularAnimeRequest(page: Int): Request = GET("$baseUrl/filter?sort=6&page=$page") override fun popularAnimeFromElement(element: Element): SAnime = searchAnimeFromElement(element) override fun popularAnimeNextPageSelector(): String = searchAnimeNextPageSelector() // Episodes override fun episodeListParse(response: Response): List<SEpisode> { return super.episodeListParse(response).reversed() } override fun episodeListSelector() = "div.server.active ul.episodes li.episode a" override fun episodeFromElement(element: Element): SEpisode { val episode = SEpisode.create() episode.setUrlWithoutDomain(element.attr("abs:href")) episode.name = "Episode: " + element.text() val epNum = getNumberFromEpsString(element.text()) episode.episode_number = when { (epNum.isNotEmpty()) -> epNum.toFloat() else -> 1F } return episode } private fun getNumberFromEpsString(epsStr: String): String { return epsStr.filter { it.isDigit() } } // Video urls override fun videoListRequest(episode: SEpisode): Request { val iframe = baseUrl + episode.url return GET(iframe) } override fun videoListParse(response: Response): List<Video> { val document = response.asJsoup() return videosFromElement(document) } override fun videoListSelector() = "center a[href*=dood], center a[href*=streamtape], center a[href*=animeworld.biz]" private fun videosFromElement(document: Document): List<Video> { val videoList = mutableListOf<Video>() val elements = document.select(videoListSelector()) for (element in elements) { val url = element.attr("href") val location = element.ownerDocument().location() val videoHeaders = Headers.headersOf("Referer", location) when { url.contains("animeworld.biz") -> { val headers = headers.newBuilder() .set("Referer", url) .set("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:96.0) Gecko/20100101 Firefox/96.0") .set("Accept-Language", "en-US,en;q=0.5") .set("watchsb", "streamsb") .build() val videos = StreamSBExtractor(client).videosFromUrl(url.replace("/d/", "/e/"), headers) videoList.addAll(videos) } url.contains("dood") -> { val video = DoodExtractor(client).videoFromUrl(url.replace("/d/", "/e/")) if (video != null) { videoList.add(video) } } url.contains("streamtape") -> { val video = StreamTapeExtractor(client).videoFromUrl(url.replace("/v/", "/e/")) if (video != null) { videoList.add(video) } } } } return videoList } override fun videoFromElement(element: Element) = throw Exception("not used") override fun videoUrlParse(document: Document) = throw Exception("not used") override fun List<Video>.sort(): List<Video> { val quality = preferences.getString("preferred_quality", null) if (quality != null) { val newList = mutableListOf<Video>() var preferred = 0 for (video in this) { if (video.quality.contains(quality)) { newList.add(preferred, video) preferred++ } else { newList.add(video) } } return newList } return this } // search override fun searchAnimeSelector(): String = "div.film-list div.item div.inner a.poster" override fun searchAnimeFromElement(element: Element): SAnime { val anime = SAnime.create() anime.setUrlWithoutDomain(element.attr("abs:href")) anime.thumbnail_url = element.select("img").attr("src") anime.title = element.select("img").attr("alt") return anime } override fun searchAnimeNextPageSelector(): String = "div.paging-wrapper a#go-next-page" override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request = GET("$baseUrl/filter?${getSearchParameters(filters)}&keyword=$query&page=$page") // Details override fun animeDetailsParse(document: Document): SAnime { val anime = SAnime.create() anime.thumbnail_url = document.select("div.thumb img").first().attr("src") anime.title = document.select("div.c1 h2.title").text() anime.genre = document.select("dd:has(a[href*=language]) a, dd:has(a[href*=genre]) a").joinToString(", ") { it.text() } anime.description = document.select("div.desc").text() anime.author = document.select("dd:has(a[href*=studio]) a").joinToString(", ") { it.text() } anime.status = parseStatus(document.select("dd:has(a[href*=status]) a").text().replace("Status: ", "")) return anime } private fun parseStatus(statusString: String): Int { return when (statusString) { "In corso" -> SAnime.ONGOING "Finito" -> SAnime.COMPLETED else -> SAnime.UNKNOWN } } // Latest - Same format as search override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/updated?page=$page") override fun latestUpdatesSelector(): String = searchAnimeSelector() override fun latestUpdatesNextPageSelector(): String = searchAnimeNextPageSelector() override fun latestUpdatesFromElement(element: Element): SAnime = searchAnimeFromElement(element) // Filters internal class Genre(val id: String, name: String) : AnimeFilter.CheckBox(name) private class GenreList(genres: List<Genre>) : AnimeFilter.Group<Genre>("Generi", genres) private fun getGenres() = listOf( Genre("and", "Mode: AND"), Genre("3", "<NAME>"), Genre("5", "Avanguardia"), Genre("2", "Avventura"), Genre("1", "Azione"), Genre("47", "Bambini"), Genre("4", "Commedia"), Genre("6", "Demoni"), Genre("7", "Drammatico"), Genre("8", "Ecchi"), Genre("9", "Fantasy"), Genre("10", "Gioco"), Genre("11", "Harem"), Genre("43", "Hentai"), Genre("13", "Horror"), Genre("14", "Josei"), Genre("16", "Magia"), Genre("18", "Mecha"), Genre("19", "Militari"), Genre("21", "Mistero"), Genre("20", "Musicale"), Genre("22", "Parodia"), Genre("23", "Polizia"), Genre("24", "Psicologico"), Genre("46", "Romantico"), Genre("26", "Samurai"), Genre("28", "Sci-Fi"), Genre("27", "Scolastico"), Genre("29", "Seinen"), Genre("25", "Sentimentale"), Genre("30", "Shoujo"), Genre("31", "Shoujo Ai"), Genre("32", "Shounen"), Genre("33", "Shounen Ai"), Genre("34", "Slice of Life"), Genre("35", "Spazio"), Genre("37", "Soprannaturale"), Genre("36", "Sport"), Genre("12", "Storico"), Genre("38", "Superpoteri"), Genre("39", "Thriller"), Genre("40", "Vampiri"), Genre("48", "Veicoli"), Genre("41", "Yaoi"), Genre("42", "Yuri") ) internal class Season(val id: String, name: String) : AnimeFilter.CheckBox(name) private class SeasonList(seasons: List<Season>) : AnimeFilter.Group<Season>("Stagioni", seasons) private fun getSeasons() = listOf( Season("winter", "Inverno"), Season("spring", "Primavera"), Season("summer", "Estate"), Season("fall", "Autunno"), Season("unknown", "Sconosciuto"), ) internal class Year(val id: String) : AnimeFilter.CheckBox(id) private class YearList(years: List<Year>) : AnimeFilter.Group<Year>("Anno di Uscita", years) private fun getYears() = listOf( Year("1966"), Year("1967"), Year("1969"), Year("1970"), Year("1973"), Year("1974"), Year("1975"), Year("1977"), Year("1978"), Year("1979"), Year("1980"), Year("1981"), Year("1982"), Year("1983"), Year("1984"), Year("1985"), Year("1986"), Year("1987"), Year("1988"), Year("1989"), Year("1990"), Year("1991"), Year("1992"), Year("1993"), Year("1994"), Year("1995"), Year("1996"), Year("1997"), Year("1998"), Year("1999"), Year("2000"), Year("2001"), Year("2002"), Year("2003"), Year("2004"), Year("2005"), Year("2006"), Year("2007"), Year("2008"), Year("2009"), Year("2010"), Year("2011"), Year("2012"), Year("2013"), Year("2014"), Year("2015"), Year("2016"), Year("2017"), Year("2018"), Year("2019"), Year("2020"), Year("2021"), Year("2022") ) internal class Type(val id: String, name: String) : AnimeFilter.CheckBox(name) private class TypeList(types: List<Type>) : AnimeFilter.Group<Type>("Tipo", types) private fun getTypes() = listOf( Type("0", "Anime"), Type("4", "Movie"), Type("1", "OVA"), Type("2", "ONA"), Type("3", "Special"), Type("5", "Music") ) internal class State(val id: String, name: String) : AnimeFilter.CheckBox(name) private class StateList(states: List<State>) : AnimeFilter.Group<State>("Stato", states) private fun getStates() = listOf( State("0", "In corso"), State("1", "Finito"), State("2", "Non rilasciato"), State("3", "Droppato") ) internal class Studio(val input: String, name: String) : AnimeFilter.Text(name) internal class Sub(val id: String, name: String) : AnimeFilter.CheckBox(name) private class SubList(subs: List<Sub>) : AnimeFilter.Group<Sub>("Sottotitoli", subs) private fun getSubs() = listOf( Sub("0", "Subbato"), Sub("1", "Doppiato") ) internal class Audio(val id: String, name: String) : AnimeFilter.CheckBox(name) private class AudioList(audios: List<Audio>) : AnimeFilter.Group<Audio>("Audio", audios) private fun getAudios() = listOf( Audio("jp", "Giapponese"), Audio("it", "Italiano"), Audio("ch", "Cinese"), Audio("kr", "Coreano"), Audio("en", "Inglese"), ) private class OrderFilter : AnimeFilter.Select<String>( "Ordine", arrayOf( "Standard", "Ultime Aggiunte", "Lista A-Z", "Lista Z-A", "Più Vecchi", "Più Recenti", "Più Visti" ), 0 ) private fun getSearchParameters(filters: AnimeFilterList): String { var totalstring = "" filters.forEach { filter -> when (filter) { is GenreList -> { // ---Genre filter.state.forEach { Genre -> if (Genre.state) { totalstring += if (Genre.id == "and") { "&genre_mode=and" } else { "&genre=" + Genre.id } } } } is SeasonList -> { // ---Season filter.state.forEach { Season -> if (Season.state) { totalstring += "&season=" + Season.id } } } is YearList -> { // ---Year filter.state.forEach { Year -> if (Year.state) { totalstring += "&year=" + Year.id } } } is TypeList -> { // ---Type filter.state.forEach { Type -> if (Type.state) { totalstring += "&type=" + Type.id } } } is StateList -> { // ---State filter.state.forEach { State -> if (State.state) { totalstring += "&status=" + State.id } } } is Studio -> { if (filter.state.isNotEmpty()) { val studios = filter.state.split(",").toTypedArray() for (x in studios.indices) { totalstring += "&studio=" + studios[x] } } } is SubList -> { // ---Subs filter.state.forEach { Sub -> if (Sub.state) { totalstring += "&dub=" + Sub.id } } } is AudioList -> { // ---Audio filter.state.forEach { Audio -> if (Audio.state) { totalstring += "&language=" + Audio.id } } } is OrderFilter -> { if (filter.values[filter.state] == "Standard") totalstring += "&sort=0" if (filter.values[filter.state] == "Ultime Aggiunte") totalstring += "&sort=1" if (filter.values[filter.state] == "Lista A-Z") totalstring += "&sort=2" if (filter.values[filter.state] == "Lista Z-A") totalstring += "&sort=3" if (filter.values[filter.state] == "Più Vecchi") totalstring += "&sort=4" if (filter.values[filter.state] == "Più Recenti") totalstring += "&sort=5" if (filter.values[filter.state] == "Più Visti") totalstring += "&sort=6" } else -> {} } } return totalstring } override fun getFilterList(): AnimeFilterList = AnimeFilterList( GenreList(getGenres()), SeasonList(getSeasons()), YearList(getYears()), TypeList(getTypes()), StateList(getStates()), AnimeFilter.Header("Usa la virgola per separare i diversi studio"), Studio("", "Studio"), SubList(getSubs()), AudioList(getAudios()), OrderFilter() ) // Preferences override fun setupPreferenceScreen(screen: PreferenceScreen) { val videoQualityPref = ListPreference(screen.context).apply { key = "preferred_quality" title = "Preferred quality" entries = arrayOf("1080p", "720p", "480p", "360p", "Doodstream", "StreamTape") entryValues = arrayOf("1080", "720", "480", "360", "Doodstream", "StreamTape") setDefaultValue("1080") summary = "%s" setOnPreferenceChangeListener { _, newValue -> val selected = newValue as String val index = findIndexOfValue(selected) val entry = entryValues[index] as String preferences.edit().putString(key, entry).commit() } } screen.addPreference(videoQualityPref) } }
kotlin
30
0.536714
127
35.685417
480
starcoderdata
<reponame>FrontierRobotics/pathfinder-iic package io.frontierrobotics.i2c import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import io.frontierrobotics.i2c.driver.I2CDriver import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import kotlin.test.assertEquals import kotlin.test.assertFailsWith class I2CBusSpecs : Spek({ describe("an I2C Buss") { val driver = mock<I2CDriver>() val bus = I2CBus(driver, 0x1B) on("sending a command") { it("should send the command over the i2CBus") { val data = I2CData("hello") val device = I2CDevice(0x1C) bus.send(device, data) verify(driver).send(device, data) } } on("sending a command to an internal address") { it("should send the command over the i2CBus") { val data = I2CData("hello") val device = I2CDevice(0x1C, 0x01) bus.send(device, data) verify(driver).send(device, data) } } on("sending a command to a reserved address") { it("should return an error") { val data = I2CData("hello") val device = I2CDevice(0x1B) assertFailsWith<IllegalArgumentException> { bus.send(device, data) } } } on("sending a command to an out-of-bounds address") { it("should return an error") { val data = I2CData("hello") val device = I2CDevice(0x1FF) assertFailsWith<IllegalArgumentException> { bus.send(device, data) } } } on("receiving data") { it("should receive the data over the i2CBus") { val device = I2CDevice(0x1C) val expected = I2CData("123") whenever(driver.receive(device, 3)).thenReturn(expected) val actual = bus.receive(device, 3) verify(driver).receive(device, 3) assertEquals(expected, actual) } } on("receiving a command from an internal address") { it("should receive the data over the i2CBus") { val device = I2CDevice(0x1C, 0x01) val expected = I2CData("123") whenever(driver.receive(device, 3)).thenReturn(expected) val actual = bus.receive(device, 3) verify(driver).receive(device, 3) assertEquals(expected, actual) } } on("receiving a command from a reserved address") { it("should return an error") { val device = I2CDevice(0x1B) assertFailsWith<IllegalArgumentException> { bus.receive(device, 3) } } } on("receiving a command from an out-of-bounds address") { it("should return an error") { val device = I2CDevice(0x1FF) assertFailsWith<IllegalArgumentException> { bus.receive(device, 3) } } } } })
kotlin
33
0.511888
72
27.15748
127
starcoderdata
package tam.howard.appListingCompose.provider.api import okhttp3.Request import okio.Timeout import retrofit2.Call import retrofit2.Callback import retrofit2.Response import tam.howard.appListingCompose.model.core.Result import tam.howard.appListingCompose.model.core.ResultFailure class ResultCall<T>(private val delegate: Call<T>) : Call<Result<T>> { override fun enqueue(callback: Callback<Result<T>>) = delegate.enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { when (response.isSuccessful) { true -> { response.body()?.let { callback.onResponse( this@ResultCall, Response.success(Result.Success(response.code(), it)) ) } ?: callback.onResponse( this@ResultCall, Response.success(Result.Failure(response.code(), ResultFailure.EmptyBody)) ) } else -> { val errorBodyString = response.errorBody()?.string() callback.onResponse( this@ResultCall, Response.success( Result.Failure( response.code(), ResultFailure.ApiError(errorBodyString) ) ) ) } } } override fun onFailure(call: Call<T>, t: Throwable) { callback.onResponse( this@ResultCall, Response.success(Result.Failure(failure = ResultFailure.NetworkFailure(t))) ) } }) override fun clone(): Call<Result<T>> = ResultCall(delegate) override fun execute(): Response<Result<T>> { throw UnsupportedOperationException("ResultCall doesn't support execute") } override fun isExecuted(): Boolean = delegate.isExecuted override fun cancel() = delegate.cancel() override fun isCanceled(): Boolean = delegate.isCanceled override fun request(): Request = delegate.request() override fun timeout(): Timeout = delegate.timeout() }
kotlin
39
0.543647
98
35.171875
64
starcoderdata
package no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl import no.nav.sbl.sosialhjelp_mock_alt.datastore.aareg.AaregService import no.nav.sbl.sosialhjelp_mock_alt.datastore.bostotte.BostotteService import no.nav.sbl.sosialhjelp_mock_alt.datastore.dkif.DkifService import no.nav.sbl.sosialhjelp_mock_alt.datastore.dkif.model.DigitalKontaktinfo import no.nav.sbl.sosialhjelp_mock_alt.datastore.ereg.EregService import no.nav.sbl.sosialhjelp_mock_alt.datastore.fiks.SoknadService import no.nav.sbl.sosialhjelp_mock_alt.datastore.kontonummer.KontonummerService import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.Adressebeskyttelse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.ForenkletBostedsadresse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.Gradering import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.Kjoenn import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlBostedsadresse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlFoedsel import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlFoedselsdato import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlFolkeregisterpersonstatus import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlForelderBarnRelasjon import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlInnsynHentPerson import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlInnsynPerson import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlInnsynPersonResponse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlKjoenn import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlModiaHentPerson import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlModiaPerson import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlModiaPersonResponse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlPersonNavn import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSivilstand import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadAdressebeskyttelse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadAdressebeskyttelseResponse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadBarn import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadBarnResponse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadEktefelle import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadEktefelleResponse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadHentAdressebeskyttelse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadHentBarn import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadHentEktefelle import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadHentPerson import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadPerson import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadPersonNavn import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlSoknadPersonResponse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlStatsborgerskap import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlTelefonnummer import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.PdlVegadresse import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.Personalia import no.nav.sbl.sosialhjelp_mock_alt.datastore.pdl.model.SivilstandType import no.nav.sbl.sosialhjelp_mock_alt.datastore.skatteetaten.SkatteetatenService import no.nav.sbl.sosialhjelp_mock_alt.datastore.utbetaling.UtbetalingService import no.nav.sbl.sosialhjelp_mock_alt.utils.MockAltException import no.nav.sbl.sosialhjelp_mock_alt.utils.fastFnr import no.nav.sbl.sosialhjelp_mock_alt.utils.genererTilfeldigKontonummer import no.nav.sbl.sosialhjelp_mock_alt.utils.genererTilfeldigOrganisasjonsnummer import no.nav.sbl.sosialhjelp_mock_alt.utils.genererTilfeldigPersonnummer import no.nav.sbl.sosialhjelp_mock_alt.utils.logger import no.nav.sbl.sosialhjelp_mock_alt.utils.randomInt import org.springframework.stereotype.Service import java.time.LocalDate @Service class PdlService( val dkifService: DkifService, val eregService: EregService, val aaregService: AaregService, val skatteetatenService: SkatteetatenService, val utbetalingService: UtbetalingService, val bostotteService: BostotteService, val soknadService: SoknadService, val kontonummerService: KontonummerService, val pdlGeografiskTilknytningService: PdlGeografiskTilknytningService, ) { private val personListe: HashMap<String, Personalia> = HashMap() private val ektefelleMap = mutableMapOf<String, PdlSoknadEktefelle>() private val barnMap = mutableMapOf<String, PdlSoknadBarn>() init { opprettBrukerMedAlt(fastFnr, "Standard", "Standardsen", "NOR", 1) opprettBrukerMedAlt( genererTilfeldigPersonnummer(), "Bergen", "Bergenhusen", "NOR", 2, postnummer = "5005", kommuneNummer = "4601", enhetsnummer = "1209" ) opprettBrukerMedAlt(genererTilfeldigPersonnummer(), "Tyske", "Tyskersen", "GER", 3) opprettBrukerMedAlt(genererTilfeldigPersonnummer(), "Admin", "Adminsen", "NOR", 4) val hemmeligBruker = Personalia() .withNavn("Hemmelig", "", "Adressesen") .withAdressebeskyttelse(Gradering.STRENGT_FORTROLIG) .withOpprettetTidspunkt(5) .locked() personListe[hemmeligBruker.fnr] = hemmeligBruker } fun getInnsynResponseFor(ident: String): PdlInnsynPersonResponse { log.info("Henter PDL innsyns data for $ident") val personalia = personListe[ident] var adressebeskyttelseList: List<Adressebeskyttelse> = emptyList() var navnList: List<PdlPersonNavn> = emptyList() if (personalia != null) { adressebeskyttelseList = listOf(Adressebeskyttelse(personalia.adressebeskyttelse)) navnList = listOf(PdlPersonNavn(personalia.navn.fornavn, personalia.navn.mellomnavn, personalia.navn.etternavn)) } return PdlInnsynPersonResponse( errors = null, data = PdlInnsynHentPerson( hentPerson = PdlInnsynPerson( adressebeskyttelse = adressebeskyttelseList, navn = navnList ) ) ) } fun getModiaResponseFor(ident: String): PdlModiaPersonResponse { log.info("Henter PDL modia data for $ident") val personalia = personListe[ident] var navn = PdlPersonNavn("Person", "", "Testperson") val kjoenn = PdlKjoenn(Kjoenn.KVINNE) val foedselsdato = PdlFoedselsdato("1945-10-26") val telefonnummer = PdlTelefonnummer("+47", "11112222", 1) if (personalia != null) { navn = personalia.navn } return PdlModiaPersonResponse( errors = null, data = PdlModiaHentPerson( hentPerson = PdlModiaPerson( navn = listOf(navn), kjoenn = listOf(kjoenn), foedsel = listOf(foedselsdato), telefonnummer = listOf(telefonnummer) ) ) ) } fun getSoknadPersonResponseFor(ident: String): PdlSoknadPersonResponse { log.info("Henter PDL soknad data for (person) $ident") val personalia = personListe[ident] var navn = PdlSoknadPersonNavn("Person", "", "Testperson") var forelderBarnRelasjon: List<PdlForelderBarnRelasjon> = emptyList() var sivilstand = PdlSivilstand(SivilstandType.UGIFT, null) var statsborgerskap = PdlStatsborgerskap("NOR") var bostedsadresse = PdlBostedsadresse(null, defaultAdresse, null, null) if (personalia != null) { navn = PdlSoknadPersonNavn(personalia.navn.fornavn, personalia.navn.mellomnavn, personalia.navn.etternavn) if (personalia.sivilstand.equals("GIFT", true) || personalia.sivilstand.equals("PARTNER", true)) { val ektefelleIdent = genererTilfeldigPersonnummer() sivilstand = PdlSivilstand(SivilstandType.valueOf(personalia.sivilstand), ektefelleIdent) when (personalia.ektefelle) { "EKTEFELLE_SAMME_BOSTED" -> ektefelleMap[ident] = ektefelleSammeBosted "EKTEFELLE_ANNET_BOSTED" -> ektefelleMap[ident] = ektefelleAnnetBosted "EKTEFELLE_MED_ADRESSEBESKYTTELSE" -> ektefelleMap[ident] = ektefelleMedAdressebeskyttelse } } forelderBarnRelasjon = personalia.forelderBarnRelasjon.map { PdlForelderBarnRelasjon(it.ident, it.rolle, it.motrolle) } statsborgerskap = PdlStatsborgerskap(personalia.starsborgerskap) bostedsadresse = PdlBostedsadresse( null, PdlVegadresse( "matrikkelId", personalia.bostedsadresse.adressenavn, personalia.bostedsadresse.husnummer, if (personalia.bostedsadresse.husbokstav.isNullOrBlank()) null else personalia.bostedsadresse.husbokstav, null, personalia.bostedsadresse.postnummer, personalia.bostedsadresse.kommunenummer, null, ), null, null ) } return PdlSoknadPersonResponse( errors = null, data = PdlSoknadHentPerson( hentPerson = PdlSoknadPerson( bostedsadresse = listOf(bostedsadresse), kontaktadresse = emptyList(), oppholdsadresse = emptyList(), forelderBarnRelasjon = forelderBarnRelasjon, navn = listOf(navn), sivilstand = listOf(sivilstand), statsborgerskap = listOf(statsborgerskap) ) ) ) } fun getSoknadEktefelleResponseFor(ident: String): PdlSoknadEktefelleResponse { log.info("Henter PDL soknad data for (ektefelle) $ident") val pdlEktefelle = ektefelleMap[ident] ?: defaultEktefelle() return PdlSoknadEktefelleResponse( errors = null, data = PdlSoknadHentEktefelle( hentPerson = pdlEktefelle ) ) } fun getSoknadBarnResponseFor(ident: String): PdlSoknadBarnResponse { log.info("Henter PDL soknad data for (barn) $ident") val pdlBarn = barnMap[ident] ?: defaultBarn() return PdlSoknadBarnResponse( errors = null, data = PdlSoknadHentBarn( hentPerson = pdlBarn ) ) } fun getSoknadAdressebeskyttelseResponseFor(ident: String): PdlSoknadAdressebeskyttelseResponse { log.info("Henter PDL adressebeskyttelse for $ident") val personalia = personListe[ident] var adressebeskyttelse = Adressebeskyttelse(Gradering.UGRADERT) if (personalia != null) { adressebeskyttelse = Adressebeskyttelse(personalia.adressebeskyttelse) } return PdlSoknadAdressebeskyttelseResponse( errors = null, data = PdlSoknadHentAdressebeskyttelse( hentPerson = PdlSoknadAdressebeskyttelse(adressebeskyttelse = listOf(adressebeskyttelse)) ) ) } // Util: fun leggTilPerson(personalia: Personalia) { if (personListe[personalia.fnr] != null && personListe[personalia.fnr]!!.locked) { throw MockAltException("Ident ${personalia.fnr} is locked! Cannot update!") } personListe[personalia.fnr] = personalia pdlGeografiskTilknytningService.putGeografiskTilknytning(personalia.fnr, personalia.bostedsadresse.kommunenummer) } fun leggTilBarn(fnr: String, pdlBarn: PdlSoknadBarn) { barnMap[fnr] = pdlBarn } fun getPersonalia(ident: String): Personalia { return personListe[ident] ?: throw MockAltException("Ident $ident not found!") } fun getBarn(ident: String): PdlSoknadBarn { return barnMap[ident] ?: throw MockAltException("Barn with ident $ident not found!") } fun veryfyNotLocked(fnr: String) { val personalia = personListe[fnr] if (personalia != null && personalia.locked) { throw MockAltException("Bruker er låst og skal ikke oppdateres!") } } fun getPersonListe(): List<Personalia> { return personListe.values.sortedBy { it.opprettetTidspunkt } } fun finnesPersonMedFnr(fnr: String?): Boolean { return personListe.containsKey(key = fnr) } private fun opprettBrukerMedAlt( brukerFnr: String, fornavn: String, etternavn: String, statsborgerskap: String, position: Long, postnummer: String = "0101", kommuneNummer: String = "0301", enhetsnummer: String = "0315", ) { val barnFnr = genererTilfeldigPersonnummer() val standardBruker = Personalia(fnr = brukerFnr) .withNavn(fornavn, "", etternavn) .withOpprettetTidspunkt(position) .withEktefelle("EKTEFELLE_SAMME_BOSTED") .withSivilstand("GIFT") .withForelderBarnRelasjon(barnFnr) .withBostedsadresse( ForenkletBostedsadresse( adressenavn = "Gateveien", husnummer = 1, postnummer = postnummer, kommunenummer = kommuneNummer ) ) .withStarsborgerskap(statsborgerskap) .locked() personListe[brukerFnr] = standardBruker ektefelleMap[brukerFnr] = ektefelleSammeBosted barnMap[barnFnr] = defaultBarn(etternavn) pdlGeografiskTilknytningService.putGeografiskTilknytning(brukerFnr, standardBruker.bostedsadresse.kommunenummer) dkifService.putDigitalKontaktinfo(brukerFnr, DigitalKontaktinfo(mobiltelefonnummer = randomInt(8).toString())) kontonummerService.putKontonummer(brukerFnr, genererTilfeldigKontonummer()) val organisasjonsnummer = genererTilfeldigOrganisasjonsnummer() eregService.putOrganisasjonNoekkelinfo(organisasjonsnummer, "Arbeidsgiveren AS") aaregService.leggTilEnkeltArbeidsforhold( personalia = standardBruker, startDato = LocalDate.now().minusYears(10), orgnummmer = organisasjonsnummer, ) skatteetatenService.enableAutoGenerationFor(brukerFnr) utbetalingService.enableAutoGenerationFor(brukerFnr) bostotteService.enableAutoGenerationFor(brukerFnr) soknadService.opprettDigisosSak(enhetsnummer, kommuneNummer, brukerFnr, brukerFnr) } companion object { private val log by logger() private val defaultAdresse = PdlVegadresse("matrikkelId", "Gateveien", 1, "A", null, "0101", "0301", "H101") private val annenAdresse = PdlVegadresse("matrikkelId2", "<NAME>", 1, null, null, "0101", "0301", null) private val ektefelleSammeBosted = PdlSoknadEktefelle( adressebeskyttelse = listOf(Adressebeskyttelse(Gradering.UGRADERT)), bostedsadresse = listOf(PdlBostedsadresse(null, defaultAdresse, null, null)), foedsel = listOf(PdlFoedsel(LocalDate.of(1955, 5, 5))), navn = listOf(PdlSoknadPersonNavn("LILLA", "", "EKTEFELLE")) ) private val ektefelleAnnetBosted = PdlSoknadEktefelle( adressebeskyttelse = listOf(Adressebeskyttelse(Gradering.UGRADERT)), bostedsadresse = listOf(PdlBostedsadresse(null, annenAdresse, null, null)), foedsel = listOf(PdlFoedsel(LocalDate.of(1966, 6, 6))), navn = listOf(PdlSoknadPersonNavn("GUL", "", "EKTEFELLE")) ) private val ektefelleMedAdressebeskyttelse = PdlSoknadEktefelle( adressebeskyttelse = listOf(Adressebeskyttelse(Gradering.FORTROLIG)), bostedsadresse = emptyList(), foedsel = emptyList(), navn = emptyList() ) private fun defaultEktefelle() = PdlSoknadEktefelle( adressebeskyttelse = listOf(Adressebeskyttelse(Gradering.UGRADERT)), bostedsadresse = listOf(PdlBostedsadresse(null, defaultAdresse, null, null)), foedsel = listOf(PdlFoedsel(LocalDate.of(1956, 4, 3))), navn = listOf(PdlSoknadPersonNavn("Ektefelle", "", "McEktefelle")) ) private fun defaultBarn(etternavn: String = "McKid") = PdlSoknadBarn( adressebeskyttelse = listOf(Adressebeskyttelse(Gradering.UGRADERT)), bostedsadresse = listOf(PdlBostedsadresse(null, defaultAdresse, null, null)), folkeregisterpersonstatus = listOf(PdlFolkeregisterpersonstatus("bosatt")), foedsel = listOf(PdlFoedsel(LocalDate.now().minusYears(10))), navn = listOf(PdlSoknadPersonNavn("Kid", "", etternavn)) ) } }
kotlin
27
0.685281
131
46.013774
363
starcoderdata
package com.vasu.appcenter import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import com.example.app.adshelper.GiftIconHelper import com.example.app.adshelper.InterstitialAdHelper import com.example.app.adshelper.InterstitialAdHelper.isShowInterstitialAd import com.example.app.adshelper.NativeAdsSize import com.example.app.adshelper.NativeAdvancedModelHelper import com.example.app.base.BaseBindingActivity import com.example.app.base.utils.getDrawableRes import com.example.app.base.utils.gone import com.vasu.appcenter.databinding.ActivityNativeAdsBinding class NativeAdsActivity : BaseBindingActivity<ActivityNativeAdsBinding>() { private var isFirstTime: Boolean = true override fun getActivityContext(): AppCompatActivity { return this@NativeAdsActivity } override fun setBinding(): ActivityNativeAdsBinding { return ActivityNativeAdsBinding.inflate(layoutInflater) } override fun initAds() { super.initAds() InterstitialAdHelper.loadInterstitialAd(fContext = mActivity) NativeAdvancedModelHelper(mActivity).loadNativeAdvancedAd( NativeAdsSize.Big, mBinding.flNativeAdPlaceHolderBig, isAddVideoOptions = intent?.extras?.getBoolean("is_add_video_options") ?: false, isAdLoaded = { if (isFirstTime) { isFirstTime = false NativeAdvancedModelHelper(mActivity).loadNativeAdvancedAd( NativeAdsSize.Medium, mBinding.flNativeAdPlaceHolderMedium, isAddVideoOptions = intent?.extras?.getBoolean("is_add_video_options") ?: false, ) } } ) GiftIconHelper.loadGiftAd( fContext = mActivity, fivGiftIcon = mBinding.layoutHeader.layoutGiftAd.giftAdIcon, fivBlastIcon = mBinding.layoutHeader.layoutGiftAd.giftBlastAdIcon ) } override fun initView() { super.initView() mBinding.layoutHeader.txtHeaderTitle.text = "Native Ads" mBinding.layoutHeader.ivHeaderBack.setImageDrawable(mActivity.getDrawableRes(R.drawable.ic_new_header_back)) mBinding.layoutHeader.ivHeaderRightIcon.gone } override fun initViewListener() { super.initViewListener() setClickListener( mBinding.layoutHeader.ivHeaderBack, mBinding.layoutHeader.ivHeaderRightIcon ) } override fun onClick(v: View) { super.onClick(v) when(v) { mBinding.layoutHeader.ivHeaderBack -> { onBackPressed() } } } override fun onBackPressed() { mActivity.isShowInterstitialAd(isBackAds = true) { _ -> finish() } } }
kotlin
24
0.658961
116
32.177778
90
starcoderdata
<reponame>KisaragiEffective/kisaragilib.kt<filename>src/test/java/com/github/kisaragieffective/kisaragistd/array/Dimensions.kt package com.github.kisaragieffective.kisaragistd.array import kotlin.test.assertTrue fun main() { assertTrue(arrayOf("").dimensions() == 1, "Array<str>.dim == 1") assertTrue(arrayOf(arrayOf("")).dimensions() == 2, "Array<Array<str>>.dim == 2") assertTrue(arrayOf(booleanArrayOf()).dimensions() == 2, "Array<Array<bool>>.dim == 2") } inline fun <E> Array<E>.dimensions(): Int { var o: Any? = this var c = 0 while (o is Array<*>) { c++ o = o[0] } println(o!!::class) return c + when (o) { is ByteArray, is ShortArray, is IntArray, is LongArray, is FloatArray, is DoubleArray, is BooleanArray -> 1 else -> 0 } }
kotlin
19
0.642417
126
31.48
25
starcoderdata
rootProject.name = "make-it-easy-templates"
kotlin
4
0.772727
43
43
1
starcoderdata
package exceptions fun main(args: Array<String>) { try { //Classic Exceptions :) // some code } catch (e : Exception) { println(e.message) } finally { // optional finally block } //throw Exception("Hi There!") U can do like this }
kotlin
13
0.576087
53
20.307692
13
starcoderdata
<gh_stars>0 package com.mokresh.analyticsdashboard.di import org.koin.core.module.Module class AppKoinModules { companion object { fun getModules(): List<Module> { return mutableListOf( appModule, viewModelModule, serviceModule ) } } }
kotlin
13
0.55988
41
18.705882
17
starcoderdata
/*- * ========================LICENSE_START================================= * ids-dataflow-control * %% * Copyright (C) 2018 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.dataflowcontrol import alice.tuprolog.* import com.google.common.cache.CacheBuilder import de.fhg.aisec.ids.api.policy.* import de.fhg.aisec.ids.api.policy.PolicyDecision.Decision import de.fhg.aisec.ids.api.router.RouteManager import de.fhg.aisec.ids.api.router.RouteVerificationProof import de.fhg.aisec.ids.dataflowcontrol.lucon.LuconEngine import de.fhg.aisec.ids.dataflowcontrol.lucon.TuPrologHelper.escape import de.fhg.aisec.ids.dataflowcontrol.lucon.TuPrologHelper.listStream import org.osgi.service.component.ComponentContext import org.osgi.service.component.annotations.* import org.slf4j.LoggerFactory import java.io.File import java.util.* import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit /** * servicefactory=false is the default and actually not required. But we want to make clear that * this is a singleton, i.e. there will only be one instance of PolicyDecisionPoint within the whole * runtime. * * @author <NAME> (<EMAIL>) */ @Component(immediate = true, name = "ids-dataflow-control") class PolicyDecisionPoint : PDP, PAP { // Convenience val for this thread's LuconEngine instance private val engine: LuconEngine get() = threadEngine.get() @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC) @Volatile private var routeManager: RouteManager? = null private val transformationCache = CacheBuilder.newBuilder() .maximumSize(10000) .expireAfterAccess(1, TimeUnit.DAYS) .build<ServiceNode, TransformationDecision>() /** * Creates a query to retrieve policy decision from Prolog knowledge base. * * @param target The target node of the transformation * @param properties The exchange properties */ private fun createDecisionQuery( target: ServiceNode, properties: MutableMap<String, Any>): String { val sb = StringBuilder() sb.append("rule(X), has_target(X, T), ") sb.append("has_endpoint(T, EP), ") sb.append("regex_match(EP, ").append(escape(target.endpoint)).append("), ") // Assert labels for the duration of this query, must be done before receives_label(X) @Suppress("UNCHECKED_CAST") val labels = properties.computeIfAbsent(PDP.LABELS_KEY) { HashSet<String>() } as Set<String> labels.forEach { k -> sb.append("assert(label(").append(k).append(")), ") } sb.append("receives_label(X), ") sb.append("rule_priority(X, P), ") // Removed due to unclear relevance // if (target.capabilties.size + target.properties.size > 0) { // val capProp = LinkedList<String>() // for (cap in target.capabilties) { // capProp.add("has_capability(T, " + escape(cap) + ")") // } // for (prop in target.properties) { // capProp.add("has_property(T, " + escape(prop) + ")") // } // sb.append("(").append(capProp.joinToString(", ")).append("), ") // } sb.append("(has_decision(X, D) ; (has_obligation(X, _O), has_alternativedecision(_O, Alt), ") sb.append("requires_prerequisite(_O, A)))") if (labels.isNotEmpty()) { // Cleanup prolog VM for next run sb.append(", retractall(label(_))") } sb.append(".") return sb.toString() } /** * A transformation query retrieves the set of labels to add and to remove from the Prolog * knowledge base. * * * This method returns the respective query for a specific target. * * @param target The ServiceNode to be processed * @return The resulting Prolog query for the transformation */ private fun createTransformationQuery(target: ServiceNode): String { val sb = StringBuilder() val plEndpoint: String if (target.endpoint != null) { plEndpoint = escape(target.endpoint) // sb.append("dominant_allow_rules(").append(plEndpoint).append(", _T, _), ") } else { throw RuntimeException("No endpoint specified!") } // Removed due to unclear relevance // if (target.capabilties.size + target.properties.size > 0) { // val capProp = LinkedList<String>() // for (cap in target.capabilties) { // capProp.add("has_capability(_T, " + escape(cap) + ")") // } // for (prop in target.properties) { // capProp.add("has_property(_T, " + escape(prop) + ")") // } // sb.append('(').append(capProp.joinToString(", ")).append("),\n") // } sb.append("once(setof(S, action_service(") .append(plEndpoint) .append(", S), SC); SC = []),\n") .append("collect_creates_labels(SC, ACraw), set_of(ACraw, Adds),\n") .append("collect_removes_labels(SC, RCraw), set_of(RCraw, Removes).") return sb.toString() } @Activate @Suppress("UNUSED_PARAMETER") private fun activate(ignored: ComponentContext) { loadPolicies() } fun loadPolicies() { // Try to load existing policies from deploy dir at activation val dir = File(System.getProperty("karaf.base") + File.separator + "deploy") val directoryListing = dir.listFiles() if (directoryListing == null || !dir.isDirectory) { LOG.warn("Unexpected or not running in karaf: Not a directory: " + dir.absolutePath) return } var loaded = false for (f in directoryListing) { if (f.name.endsWith(LUCON_FILE_EXTENSION)) { if (!loaded) { LOG.info("Loading Lucon policy from " + f.absolutePath) loadPolicy(f.readText()) loaded = true } else { LOG.warn("Multiple policy files. Will load only one! " + f.absolutePath) } } } } override fun requestTranformations(lastServiceNode: ServiceNode): TransformationDecision { try { return transformationCache.get( lastServiceNode ) { // Query prolog for labels to remove or add from message val query = this.createTransformationQuery(lastServiceNode) if (LOG.isDebugEnabled) { LOG.debug("Query for uncached label transformation: $query") } val result = TransformationDecision() try { val solveInfo = this.engine.query(query, true) if (solveInfo.isNotEmpty()) { // Get solutions, convert label variables to string and collect in sets val labelsToAdd = result.labelsToAdd val labelsToRemove = result.labelsToRemove solveInfo.forEach { s -> try { val adds = s.getVarValue("Adds").term if (adds.isList) { listStream(adds).forEach { labelsToAdd.add(it.toString()) } } else { throw RuntimeException("\"Adds\" is not a prolog list!") } val removes = s.getVarValue("Removes").term if (removes.isList) { listStream(removes).forEach { labelsToRemove.add(it.toString()) } } else { throw RuntimeException("\"Removes\" is not a prolog list!") } } catch (ignored: NoSolutionException) {} } } LOG.debug("Transformation: {}", result) } catch (e: Throwable) { LOG.error(e.message, e) } result } } catch (ee: ExecutionException) { LOG.error(ee.message, ee) return TransformationDecision() } } override fun requestDecision(req: DecisionRequest): PolicyDecision { val dec = PolicyDecision() LOG.debug( "Decision requested " + req.from.endpoint + " -> " + req.to.endpoint) try { // Query Prolog engine for a policy decision val startTime = System.nanoTime() val query = this.createDecisionQuery(req.to, req.properties) if (LOG.isDebugEnabled) { LOG.debug("Decision query: {}", query) } val solveInfo = this.engine.query(query, true) val time = System.nanoTime() - startTime if (LOG.isInfoEnabled) { LOG.debug("Decision query took {} ms", time / 1e6f) } // If there is no matching rule, deny by default if (solveInfo.isEmpty()) { if (LOG.isDebugEnabled) { LOG.debug("No policy decision found. Returning " + dec.decision.toString()) } dec.reason = "No matching rule" return dec } // Include only solveInfos with highest priority var maxPrio = Integer.MIN_VALUE for (si in solveInfo) { try { val priority = Integer.parseInt(si.getVarValue("P").term.toString()) if (priority > maxPrio) { maxPrio = priority } } catch (e: NumberFormatException) { LOG.warn("Invalid rule priority: " + si.getVarValue("P"), e) } catch (e: NullPointerException) { LOG.warn("Invalid rule priority: " + si.getVarValue("P"), e) } } val applicableSolveInfos = ArrayList<SolveInfo>() for (si in solveInfo) { try { val priority = Integer.parseInt(si.getVarValue("P").term.toString()) if (priority == maxPrio) { applicableSolveInfos.add(si) } } catch (e: NumberFormatException) { LOG.warn("Invalid rule priority: " + si.getVarValue("P"), e) } catch (e: NullPointerException) { LOG.warn("Invalid rule priority: " + si.getVarValue("P"), e) } } // Just for debugging if (LOG.isDebugEnabled) { debug(applicableSolveInfos) } // Collect obligations val obligations = LinkedList<Obligation>() applicableSolveInfos.forEach { s -> try { val rule = s.getVarValue("X") val decision = s.getVarValue("D") if (decision !is Var) { val decString = decision.term.toString() if ("drop" == decString) { dec.reason = rule.term.toString() } else if ("allow" == decString) { dec.reason = rule.term.toString() dec.decision = Decision.ALLOW } } val action = s.getVarValue("A") val altDecision = s.getVarValue("Alt") if (action !is Var) { val o = Obligation() o.action = action.term.toString() if (altDecision !is Var) { val altDecString = altDecision.term.toString() if ("drop" == altDecString) { o.alternativeDecision = Decision.DENY } else if ("allow" == altDecString) { o.alternativeDecision = Decision.ALLOW } } obligations.add(o) } } catch (e: NoSolutionException) { LOG.warn("Unexpected: solution variable not present: " + e.message) dec.reason = "Solution variable not present" } } dec.obligations = obligations } catch (e: NoMoreSolutionException) { LOG.error(e.message, e) dec.reason = "Error: " + e.message } catch (e: MalformedGoalException) { LOG.error(e.message, e) dec.reason = "Error: " + e.message } catch (e: NoSolutionException) { LOG.error(e.message, e) dec.reason = "Error: " + e.message } return dec } /** * Just for debugging: Print query solution to DEBUG out. * * @param solveInfo A list of Prolog solutions */ private fun debug(solveInfo: List<SolveInfo>) { if (!LOG.isTraceEnabled) { return } try { for (i in solveInfo) { if (i.isSuccess) { val vars = i.bindingVars LOG.trace(vars.joinToString(", ") { v -> String.format("%s: %s (%s)", v.name, v.term, if (v.isBound) "bound" else "unbound") }) } } } catch (nse: NoSolutionException) { LOG.trace("No solution found", nse) } } override fun clearAllCaches() { // clear Prolog cache entries try { engine.query("cache_clear(_).", true) LOG.info("Prolog cache_clear(_) successful") } catch (pe: PrologException) { LOG.warn("Prolog cache_clear(_) failed", pe) } // clear transformation cache transformationCache.invalidateAll() } override fun loadPolicy(theory: String?) { // Load policy into engine, possibly overwriting the existing one. this.engine.loadPolicy(theory ?: "") LuconEngine.setDefaultPolicy(theory ?: "") } override fun listRules(): List<String> { return try { val rules = this.engine.query("rule(X).", true) rules.map { it.getVarValue("X").toString() }.toList() } catch (e: PrologException) { LOG.error("Prolog error while retrieving rules " + e.message, e) emptyList() } } override fun getPolicy(): String { return this.engine.theory } override fun verifyRoute(routeId: String): RouteVerificationProof? { val rm = this.routeManager if (rm == null) { LOG.warn("No RouteManager. Cannot verify Camel route $routeId") return null } val routePl = rm.getRouteAsProlog(routeId) return engine.proofInvalidRoute(routeId, routePl) } companion object { private val LOG = LoggerFactory.getLogger(PolicyDecisionPoint::class.java) private const val LUCON_FILE_EXTENSION = ".pl" // Each thread creates a LuconEngine instance to prevent concurrency issues val threadEngine: ThreadLocal<LuconEngine> = ThreadLocal.withInitial { LuconEngine(System.out) } } }
kotlin
40
0.532344
104
39.071253
407
starcoderdata
<gh_stars>0 package com.internshala.bluechat import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class DevicesRecyclerViewAdapter(val mDeviceList: List<DeviceData>, val context: Context) : RecyclerView.Adapter<DevicesRecyclerViewAdapter.VH>() { private var listener: ItemClickListener? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH { val view = LayoutInflater.from(context).inflate(R.layout.recyclerview_single_item, parent, false) return VH(view) } override fun onBindViewHolder(holder: VH, position: Int) { holder?.label?.text = mDeviceList[position].deviceName ?: mDeviceList[position].deviceHardwareAddress } override fun getItemCount(): Int { return mDeviceList.size } inner class VH(itemView: View?) : RecyclerView.ViewHolder(itemView!!){ var label: TextView? = itemView?.findViewById(R.id.largeLabel) init { itemView?.setOnClickListener{ listener?.itemClicked(mDeviceList[adapterPosition]) } } } fun setItemClickListener(listener: ItemClickListener){ this.listener = listener } interface ItemClickListener{ fun itemClicked(deviceData: DeviceData) } }
kotlin
18
0.686689
109
28.541667
48
starcoderdata
package com.lightricity.station.dashboard.ui import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.text.style.RelativeSizeSpan import android.text.style.SuperscriptSpan import android.view.animation.AnimationUtils import android.widget.AdapterView import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.view.GravityCompat import androidx.core.view.isVisible import androidx.lifecycle.Observer import com.google.android.material.snackbar.Snackbar import com.lightricity.station.R import com.lightricity.station.about.ui.AboutActivity import com.lightricity.station.addtag.ui.AddTagActivity import com.lightricity.station.feature.data.FeatureFlag import com.lightricity.station.feature.domain.RuntimeBehavior import com.lightricity.station.network.data.NetworkSyncResultType import com.lightricity.station.network.ui.SignInActivity import com.lightricity.station.settings.ui.AppSettingsActivity import com.lightricity.station.tag.domain.Sensor import com.lightricity.station.tagdetails.ui.TagDetailsActivity import com.lightricity.station.util.PermissionsHelper import com.lightricity.station.util.extensions.* import kotlinx.android.synthetic.main.activity_dashboard.mainDrawerLayout import kotlinx.android.synthetic.main.activity_dashboard.toolbar import kotlinx.android.synthetic.main.content_dashboard.* import kotlinx.android.synthetic.main.navigation_drawer.* import org.kodein.di.KodeinAware import org.kodein.di.android.closestKodein import org.kodein.di.generic.instance import timber.log.Timber import java.util.* import kotlin.collections.MutableList import kotlin.concurrent.scheduleAtFixedRate class DashboardActivity : AppCompatActivity(), KodeinAware { override val kodein by closestKodein() private val viewModel: DashboardActivityViewModel by viewModel() private val runtimeBehavior: RuntimeBehavior by instance() private lateinit var permissionsHelper: PermissionsHelper private var tags: MutableList<Sensor> = arrayListOf() private lateinit var adapter: RuuviTagAdapter private var getTagsTimer :Timer? = null private var signedIn = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_dashboard) setSupportActionBar(toolbar) supportActionBar?.title = null supportActionBar?.setIcon(R.drawable.logo) setupViewModel() setupDrawer() setupListView() permissionsHelper = PermissionsHelper(this) permissionsHelper.requestPermissions() } override fun onResume() { super.onResume() getTagsTimer = Timer("DashboardActivityTimer", false) getTagsTimer?.scheduleAtFixedRate(0, 1000) { viewModel.updateTags() viewModel.updateNetworkStatus() } } override fun onPause() { super.onPause() getTagsTimer?.cancel() } private fun setupViewModel() { viewModel.observeTags.observe( this, Observer { tags.clear() tags.addAll(it) noTagsTextView.isVisible = tags.isEmpty() adapter.notifyDataSetChanged() }) } private fun setupListView() { adapter = RuuviTagAdapter(this@DashboardActivity, tags, viewModel.converter) dashboardListView.adapter = adapter dashboardListView.onItemClickListener = tagClick } private fun setupDrawer() { val drawerToggle = ActionBarDrawerToggle( this, mainDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ) mainDrawerLayout.addDrawerListener(drawerToggle) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setHomeButtonEnabled(true) drawerToggle.syncState() updateMenu(signedIn) navigationView.setNavigationItemSelectedListener { when (it.itemId) { R.id.addNewSensorMenuItem -> AddTagActivity.start(this) R.id.appSettingsMenuItem -> AppSettingsActivity.start(this) R.id.aboutMenuItem -> AboutActivity.start(this) R.id.sendFeedbackMenuItem -> SendFeedback() R.id.getMoreSensorsMenuItem -> OpenUrl(WEB_URL) R.id.loginMenuItem -> login(signedIn) } mainDrawerLayout.closeDrawer(GravityCompat.START) return@setNavigationItemSelectedListener true } syncLayout.setOnClickListener { viewModel.networkDataSync() } viewModel.syncResultObserve.observe(this, Observer {syncResult -> val message = when (syncResult.type) { NetworkSyncResultType.NONE -> "" NetworkSyncResultType.SUCCESS -> getString(R.string.network_sync_result_success) NetworkSyncResultType.EXCEPTION -> getString(R.string.network_sync_result_exception, syncResult.errorMessage) NetworkSyncResultType.NOT_LOGGED -> getString(R.string.network_sync_result_not_logged) } if (message.isNotEmpty()) { Snackbar.make(mainDrawerLayout, message, Snackbar.LENGTH_SHORT).show() viewModel.syncResultShowed() } }) viewModel.syncInProgressObserve.observe(this, Observer { if (it) { Timber.d("Sync in progress") syncNetworkButton.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_indefinitely)) } else { Timber.d("Sync not in progress") syncNetworkButton.clearAnimation() } }) viewModel.userEmail.observe(this, Observer { var user = it if (user.isNullOrEmpty()) { user = getString(R.string.none) signedIn = false } else { signedIn = true } updateMenu(signedIn) loggedUserTextView.text = getString(R.string.network_user, user) }) viewModel.syncStatus.observe(this, Observer {syncStatus-> if (syncStatus.syncInProgress) { syncStatusTextView.text = getString(R.string.connected_reading_info) } else { val lastSyncString = if (syncStatus.lastSync == Long.MIN_VALUE) { getString(R.string.never) } else { Date(syncStatus.lastSync).describingTimeSince(this) } syncStatusTextView.text = getString(R.string.network_synced, lastSyncString) } }) } private fun login(signedIn: Boolean) { if (signedIn == false) { val alertDialog = AlertDialog.Builder(this, R.style.CustomAlertDialog).create() alertDialog.setTitle(getString(R.string.sign_in_benefits_title)) alertDialog.setMessage(getString(R.string.sign_in_benefits_description)) alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.ok) ) { dialog, _ -> dialog.dismiss() } alertDialog.setOnDismissListener { SignInActivity.start(this) } alertDialog.show() } else { val builder = AlertDialog.Builder(this) with(builder) { setMessage(getString(R.string.sign_out_confirm)) setPositiveButton(getString(R.string.yes)) { dialogInterface, i -> viewModel.signOut() } setNegativeButton(getString(R.string.no)) { dialogInterface, _ -> dialogInterface.dismiss() } show() } } } private fun updateMenu(signed: Boolean) { networkLayout.isVisible = runtimeBehavior.isFeatureEnabled(FeatureFlag.RUUVI_NETWORK) val loginMenuItem = navigationView.menu.findItem(R.id.loginMenuItem) loginMenuItem?.let { it.isVisible = runtimeBehavior.isFeatureEnabled(FeatureFlag.RUUVI_NETWORK) it.title = if (signed) { getString(R.string.sign_out) } else { val signInText = getString(R.string.sign_in) val betaText = getString(R.string.beta) val spannable = SpannableString (signInText+betaText) spannable.setSpan(ForegroundColorSpan(Color.RED), signInText.length, signInText.length + betaText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spannable.setSpan(SuperscriptSpan(), signInText.length, signInText.length + betaText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spannable.setSpan(RelativeSizeSpan(0.75f), signInText.length, signInText.length + betaText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) spannable } } } private val tagClick = AdapterView.OnItemClickListener { _, view, _, _ -> val tag = view.tag as Sensor TagDetailsActivity.start(this, tag.id) } companion object { private const val WEB_URL = "https://ruuvi.com" fun start(context: Context) { val intent = Intent(context, DashboardActivity::class.java) context.startActivity(intent) } } }
kotlin
30
0.660768
157
38.440816
245
starcoderdata
<reponame>joost-klitsie/kotlin-styled-material-ui package demo.components import kotlinx.css.* import kotlinx.html.DIV import kotlinx.html.js.onChangeFunction import materialui.components.formcontrol.formControl import materialui.components.input.input import materialui.components.inputadornment.InputAdornmentElementBuilder import materialui.components.inputadornment.enums.InputAdornmentPosition import materialui.components.inputlabel.inputLabel import materialui.components.menuitem.menuItem import materialui.components.textfield.textField import materialui.styles.withStyles import org.w3c.dom.events.Event import react.* import react.dom.div import styled.css import styled.styledDiv import styled.styledH1 val ranges: List<Pair<String, String>> get() = listOf( "0-20" to "0 to 20", "21-50" to "21 to 50", "51-100" to "51 to 100" ) class InputAdornmentsDemo : RComponent<RProps, InputAdornmentsState>() { override fun InputAdornmentsState.init() { amount = "" password = "" weight = "" weightRange = "" showPassword = false } fun handleOnChange(prop: String): (Event) -> Unit = { event -> val value = event.target.asDynamic().value setState { asDynamic()[prop] = value } } fun handleClickShowPassword(): () -> Unit = { setState { showPassword = !state.showPassword } } override fun RBuilder.render() { val rootStyle = props.asDynamic()["classes"]["root"] as String val marginStyle = props.asDynamic()["classes"]["margin"] as String val textFieldStyle = props.asDynamic()["classes"]["textField"] as String div { styledH1 { css.fontWeight = FontWeight.w400 +"Input Adornments" } } styledDiv { css { display = Display.flex justifyContent = JustifyContent.center backgroundColor = Color("#eeeeee") boxSizing = BoxSizing.inherit padding(24.px) } div(classes = rootStyle) { textField { attrs { id = "simple-start-adornment" label { + "With normal TextField" } classes("$marginStyle $textFieldStyle") inputProps { attrs { startAdornment(startAdornment("Kg")) } } } } textField { attrs { select = true label { + "With Select" } classes("$marginStyle $textFieldStyle") inputProps { attrs { startAdornment(startAdornment("Kg")) } } value(state.weightRange) onChangeFunction = handleOnChange("weightRange") } ranges.forEach { menuItem { attrs { key = it.first setProp("value", it.second) } +it.first } } } formControl { attrs { fullWidth = true classes(marginStyle) } inputLabel { attrs { this["htmlFor"] = "adornment-amount" } +"Amount" } input { attrs { id = "adornment-amount" value(state.amount) onChangeFunction = handleOnChange("amount") startAdornment(startAdornment("$")) } } } } } } private fun startAdornment(unit: String): InputAdornmentElementBuilder<DIV>.() -> Unit = { attrs { position = InputAdornmentPosition.start } +unit } companion object { fun render(rBuilder: RBuilder) = with(rBuilder) { styledComponent { } } private val styledComponent = withStyles(InputAdornmentsDemo::class, { "root" { display = Display.flex flexWrap = FlexWrap.wrap boxSizing = BoxSizing.inherit } "margin" { margin(8.px) } "withoutLabel" { marginTop = 24.px } "textField" { flexBasis = 200.px.basis } }) } } external interface InputAdornmentsState : RState { var amount: String var password: String var weight: String var weightRange: String var showPassword: Boolean }
kotlin
40
0.469202
94
30.497006
167
starcoderdata
<reponame>AliusDieMorietur/Cloud_Storage_Client_Android_Kotlin<gh_stars>0 package com.samurainomichi.cloud_storage_client.unit import com.samurainomichi.cloud_storage_client.fakes.FakeServer import com.samurainomichi.cloud_storage_client.network.ConnectionRepository import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.fail import org.junit.Test import java.lang.Exception import java.nio.ByteBuffer class ConnectionRepositoryTest { companion object { private val fakeServer = FakeServer() val repository = ConnectionRepository.getInstance(fakeServer.getDataSource()) } @Test fun tmpAvailableFiles() = runBlocking { val list = repository.tmpAvailableFiles("123321") assertEquals("file1", list[0]) assertEquals("file2", list[1]) } @Test fun tmpAvailableFilesWrongToken() = runBlocking { try { repository.tmpAvailableFiles("123321042") fail("Exception 'No such token' expected") } catch (e: Exception) { assertEquals("No such token", e.message) } } @Test fun auth() = runBlocking { val authToken = repository.authLogin("admin", "<PASSWORD>") assertEquals("789789789", authToken) } @Test fun authWrongPassword() = runBlocking { try { repository.authLogin("admin", "<PASSWORD>") fail("Exception 'Wrong password' expected") } catch (e: Exception) { assertEquals("Username and/or password is incorrect", e.message) } } @Test fun upload_download() = runBlocking { // Upload repository.tmpUploadFilesStart(listOf("File1", "File2")) val buffer = ByteBuffer.wrap(ByteArray(30) { i -> (i % 16).toByte() }) repository.sendBuffer(buffer.asReadOnlyBuffer()) repository.sendBuffer(buffer.asReadOnlyBuffer()) val token = repository.tmpUploadFilesEnd(listOf("File1", "File2")) assertEquals("buffersToken", token) println("Files uploaded") // Download repository.tmpDownloadFiles(token, listOf()) val size = CompletableDeferred<Int>() repository.onBufferReceived.observe { println("Got it") size.complete(it.remaining()) } repository.tmpDownloadFiles(token, listOf()) assertEquals(30, size.await()) println("File downloaded") } }
kotlin
24
0.653998
85
30.987342
79
starcoderdata
/* * Copyright (C) 2014 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.recipes.kt import java.io.File import java.io.IOException import okhttp3.MediaType.Companion.toMediaType import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.asRequestBody class PostMultipart { private val client = OkHttpClient() fun run() { // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("title", "Square Logo") .addFormDataPart("image", "logo-square.png", File("docs/images/logo-square.png").asRequestBody(MEDIA_TYPE_PNG)) .build() val request = Request.Builder() .header("Authorization", "Client-ID $IMGUR_CLIENT_ID") .url("https://api.imgur.com/3/image") .post(requestBody) .build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) throw IOException("Unexpected code $response") println(response.body.string()) } } companion object { /** * The imgur client ID for OkHttp recipes. If you're using imgur for anything other than running * these examples, please request your own client ID! https://api.imgur.com/oauth2 */ private const val IMGUR_CLIENT_ID = "9199fdef135c122" private val MEDIA_TYPE_PNG = "image/png".toMediaType() } } fun main() { PostMultipart().run() }
kotlin
19
0.701449
100
31.857143
63
starcoderdata
<gh_stars>1-10 package com.euapps.googlecaller import android.Manifest import android.app.Activity import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.preference.PreferenceFragment import android.preference.PreferenceManager import android.support.annotation.RequiresApi class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) PreferenceManager.setDefaultValues(this, R.xml.prefs, false) if (savedInstanceState == null) { fragmentManager.beginTransaction().replace(android.R.id.content, SettingsFragment()).commit() } title = "${getString(R.string.app_name)} v${getVersionInfo(this)}" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkPermissions() } } @RequiresApi(Build.VERSION_CODES.M) private fun checkPermissions() { if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE), 0) } else if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.READ_PHONE_STATE), 0) } else if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.READ_CONTACTS), 0) } } class SettingsFragment : PreferenceFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.prefs) } } }
kotlin
24
0.716069
116
41.755556
45
starcoderdata
<gh_stars>1-10 package io.notable.shared.refresh import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import javax.inject.Inject import javax.inject.Singleton @Singleton class RefreshViewManager @Inject constructor( ) { val state: MutableState<RefreshViewState> = mutableStateOf(RefreshViewState()) fun onTriggerEvent(event: RefreshViewEvents) { when (event) { is RefreshViewEvents.DeleteNote -> { state.value = state.value.copy( noteToRemove = event.id ) } is RefreshViewEvents.AddNote -> { state.value = state.value.copy( noteToAdd = event.note ) } is RefreshViewEvents.RefreshDetail -> { state.value = state.value.copy( refreshDetail = event.refresh ) } } } }
kotlin
20
0.575884
82
25.027027
37
starcoderdata
<filename>app/src/main/java/com/guau_guau/guau_guau/ui/base/BaseViewModel.kt package com.guau_guau.guau_guau.ui.base import androidx.lifecycle.ViewModel import com.guau_guau.guau_guau.data.repositories.BaseRepository abstract class BaseViewModel( private val repository: BaseRepository ) : ViewModel() { }
kotlin
11
0.791139
76
27.818182
11
starcoderdata
package net.corda.workbench.cordaNetwork.tasks import net.corda.workbench.commons.taskManager.BaseTask import net.corda.workbench.commons.taskManager.ExecutionContext import net.corda.workbench.commons.taskManager.TaskLogMessage class TestTask : BaseTask() { override fun exec(executionContext: ExecutionContext) { executionContext.messageStream.invoke("executing...") } } class FailingTask : BaseTask() { override fun exec(executionContext: ExecutionContext) { throw RuntimeException("forced an error") } } class TestMessageSink { private val logs = ArrayList<TaskLogMessage>() fun sink(t: TaskLogMessage) { logs.add(t) System.out.println(t) } fun messages(): List<String> { return logs.map { it.message } } }
kotlin
14
0.714646
63
25.433333
30
starcoderdata
package com.akinci.doggoapp.common.repository import com.akinci.doggoapp.common.helper.NetworkResponse import com.akinci.doggoapp.common.network.NetworkChecker import com.akinci.doggoapp.common.network.NetworkState import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import retrofit2.Response import timber.log.Timber import javax.inject.Inject class BaseRepository @Inject constructor( private val networkChecker: NetworkChecker ) { /** Network Service Generic Repository Layer **/ // CallService generify for JSON Responses suspend fun <T> callServiceAsFlow( retrofitServiceAction : suspend () -> Response<T> ) = flow<NetworkResponse<T>> { // emit loading emit(NetworkResponse.Loading()) // check internet connection if (networkChecker.networkState.value == NetworkState.Connected) { // internet connection is established. // invoke service generic part. val response = retrofitServiceAction.invoke() if (response.isSuccessful) { /** 200 -> 299 Error status range **/ response.body()?.let { // successful response. emit(NetworkResponse.Success(data = it)) } ?: run { emit(NetworkResponse.Error(message = "BaseRepository: Service response body is null")) } }else{ /** 400 -> 599 HTTP Error Status Range **/ emit(NetworkResponse.Error(message = "BaseRepository: Service response failed with code: ${response.code()}")) } }else{ // not connected to internet emit(NetworkResponse.Error(message = "BaseRepository: Couldn't reached to server. Please check your internet connection")) } }.catch { e -> Timber.d(e) emit(NetworkResponse.Error(message = "BaseRepository: UnExpected Service Exception")) } }
kotlin
33
0.638706
134
39.408163
49
starcoderdata
package com.r3.corda.lib.reissuance.dummy_flows.dummy.dummyStateRequiringAllParticipantsSignatures import com.r3.corda.lib.reissuance.dummy_flows.AbstractFlowTest import com.r3.corda.lib.reissuance.dummy_states.DummyStateRequiringAllParticipantsSignatures import org.hamcrest.MatcherAssert.* import org.hamcrest.Matchers.* import org.junit.Test class UpdateDummyStateRequiringAllParticipantsSignaturesTest: AbstractFlowTest() { @Test fun `Update DummyStateRequiringAllParticipantsSignatures`() { initialiseParties() createDummyStateRequiringAllParticipantsSignatures(aliceParty) updateDummyStateRequiringAllParticipantsSignatures(aliceNode, bobParty) val dummyStatesRequiringAllParticipantsSignatures = getStateAndRefs<DummyStateRequiringAllParticipantsSignatures>(bobNode) assertThat(dummyStatesRequiringAllParticipantsSignatures, hasSize(1)) val dummyStateRequiringAllParticipantsSignatures = dummyStatesRequiringAllParticipantsSignatures[0].state.data assertThat(dummyStateRequiringAllParticipantsSignatures.other, `is`(acceptorParty)) assertThat(dummyStateRequiringAllParticipantsSignatures.issuer, `is`(issuerParty)) assertThat(dummyStateRequiringAllParticipantsSignatures.owner, `is`(bobParty)) } @Test fun `Update DummyStateRequiringAllParticipantsSignatures many times`() { initialiseParties() createDummyStateRequiringAllParticipantsSignatures(aliceParty) updateDummyStateRequiringAllParticipantsSignatures(aliceNode, bobParty) updateDummyStateRequiringAllParticipantsSignatures(bobNode, charlieParty) updateDummyStateRequiringAllParticipantsSignatures(charlieNode, debbieParty) updateDummyStateRequiringAllParticipantsSignatures(debbieNode, charlieParty) updateDummyStateRequiringAllParticipantsSignatures(charlieNode, bobParty) updateDummyStateRequiringAllParticipantsSignatures(bobNode, aliceParty) val dummyStatesRequiringAllParticipantsSignatures = getStateAndRefs<DummyStateRequiringAllParticipantsSignatures>(aliceNode) assertThat(dummyStatesRequiringAllParticipantsSignatures, hasSize(1)) val dummyStateRequiringAllParticipantsSignatures = dummyStatesRequiringAllParticipantsSignatures[0].state.data assertThat(dummyStateRequiringAllParticipantsSignatures.other, `is`(acceptorParty)) assertThat(dummyStateRequiringAllParticipantsSignatures.issuer, `is`(issuerParty)) assertThat(dummyStateRequiringAllParticipantsSignatures.owner, `is`(aliceParty)) } }
kotlin
14
0.823985
132
56.444444
45
starcoderdata
package com.zeongit.share.model /** * 返回信息 * @author fjj * @param <T> </T> */ class Result<T>(var status: Int = 200, var message: String? = null, var data: T? = null)
kotlin
6
0.623529
88
20.375
8
starcoderdata
package com.alphae.rishi.towatch.Listners import android.support.design.widget.AppBarLayout /** * Created by rishi on 17/3/18. */ abstract class AppBarStateChangeListener : AppBarLayout.OnOffsetChangedListener { private var mCurrentState = State.IDLE enum class State { EXPANDED, COLLAPSED, IDLE } override fun onOffsetChanged(appBarLayout: AppBarLayout, i: Int) { if (i == 0) { if (mCurrentState != State.EXPANDED) { onStateChanged(appBarLayout, State.EXPANDED) } mCurrentState = State.EXPANDED } else if (Math.abs(i) >= appBarLayout.totalScrollRange) { if (mCurrentState != State.COLLAPSED) { onStateChanged(appBarLayout, State.COLLAPSED) } mCurrentState = State.COLLAPSED } else { if (mCurrentState != State.IDLE) { onStateChanged(appBarLayout, State.IDLE) } mCurrentState = State.IDLE } } abstract fun onStateChanged(appBarLayout: AppBarLayout, state: State) }
kotlin
20
0.607207
81
26.775
40
starcoderdata
<reponame>rohankumardubey/kotlin /* * Copyright 2010-2015 JetBrains s.r.o. * * 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.jetbrains.kotlin.checkers import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.util.io.FileUtilRt import org.jetbrains.kotlin.idea.test.PluginTestCaseBase import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.MockLibraryUtil abstract class AbstractJavaAgainstKotlinBinariesCheckerTest : AbstractJavaAgainstKotlinCheckerTest() { override fun setUp() { super.setUp() val testName = getTestName(false) if (KotlinTestUtils.isAllFilesPresentTest(testName)) { return } val libraryName = "libFor" + testName val libraryJar = MockLibraryUtil.compileLibraryToJar( PluginTestCaseBase.getTestDataPathBase() + "/kotlinAndJavaChecker/javaAgainstKotlin/" + getTestName(false) + ".kt", libraryName, false, false, false ) val jarUrl = "jar://" + FileUtilRt.toSystemIndependentName(libraryJar.absolutePath) + "!/" ModuleRootModificationUtil.addModuleLibrary(module, jarUrl) } fun doTest(path: String) { doTest(true, true, path.replace(".kt", ".java")) } }
kotlin
18
0.725446
131
38.844444
45
starcoderdata
/* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.hhs.koto.stg.item import com.badlogic.gdx.graphics.Color import com.hhs.koto.util.A import com.hhs.koto.util.game class GreenItem( x: Float, y: Float, val amount: Long = 5, speed: Float = 2f, angle: Float = 90f, radius: Float = 10f, scaleX: Float = 1f, scaleY: Float = 1f, color: Color = Color.WHITE, ) : BasicItem( x, y, A["item/item.atlas"], if (amount <= 50) "green" else "green_large", 16f, 16f, speed, angle, radius, scaleX = scaleX, scaleY = scaleY, color = color, rotateOnCreation = true, ) { override fun onCollected(collectPositionX: Float, collectPositionY: Float, autoCollected: Boolean) { super.onCollected(collectPositionX, collectPositionY, autoCollected) game.pointValue = (game.pointValue + amount).coerceAtMost(game.maxPointValue) } }
kotlin
13
0.70597
104
31.967213
61
starcoderdata
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.riotx.features.workers.signout import android.app.Activity import android.app.Dialog import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.transition.TransitionManager import butterknife.BindView import butterknife.ButterKnife import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.BottomSheetDialogFragment import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.api.session.crypto.keysbackup.KeysBackupState import im.vector.riotx.R import im.vector.riotx.core.di.DaggerScreenComponent import im.vector.riotx.core.platform.VectorBaseActivity import im.vector.riotx.core.utils.toast import im.vector.riotx.features.crypto.keysbackup.settings.KeysBackupManageActivity import im.vector.riotx.features.crypto.keysbackup.setup.KeysBackupSetupActivity class SignOutBottomSheetDialogFragment : BottomSheetDialogFragment() { lateinit var session: Session lateinit var viewModelFactory: ViewModelProvider.Factory @BindView(R.id.bottom_sheet_signout_warning_text) lateinit var sheetTitle: TextView @BindView(R.id.bottom_sheet_signout_backingup_status_group) lateinit var backingUpStatusGroup: ViewGroup @BindView(R.id.keys_backup_setup) lateinit var setupClickableView: View @BindView(R.id.keys_backup_activate) lateinit var activateClickableView: View @BindView(R.id.keys_backup_dont_want) lateinit var dontWantClickableView: View @BindView(R.id.bottom_sheet_signout_icon_progress_bar) lateinit var backupProgress: ProgressBar @BindView(R.id.bottom_sheet_signout_icon) lateinit var backupCompleteImage: ImageView @BindView(R.id.bottom_sheet_backup_status_text) lateinit var backupStatusTex: TextView @BindView(R.id.bottom_sheet_signout_button) lateinit var signoutClickableView: View @BindView(R.id.root_layout) lateinit var rootLayout: ViewGroup var onSignOut: Runnable? = null companion object { fun newInstance(userId: String) = SignOutBottomSheetDialogFragment() private const val EXPORT_REQ = 0 } init { isCancelable = true } private lateinit var viewModel: SignOutViewModel override fun onAttach(context: Context) { super.onAttach(context) val vectorBaseActivity = activity as VectorBaseActivity val screenComponent = DaggerScreenComponent.factory().create(vectorBaseActivity.getVectorComponent(), vectorBaseActivity) viewModelFactory = screenComponent.viewModelFactory() session = screenComponent.session() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders.of(this, viewModelFactory).get(SignOutViewModel::class.java) viewModel.init(session) setupClickableView.setOnClickListener { context?.let { context -> startActivityForResult(KeysBackupSetupActivity.intent(context, true), EXPORT_REQ) } } activateClickableView.setOnClickListener { context?.let { context -> startActivity(KeysBackupManageActivity.intent(context)) } } signoutClickableView.setOnClickListener { this.onSignOut?.run() } dontWantClickableView.setOnClickListener { _ -> context?.let { AlertDialog.Builder(it) .setTitle(R.string.are_you_sure) .setMessage(R.string.sign_out_bottom_sheet_will_lose_secure_messages) .setPositiveButton(R.string.backup) { _, _ -> when (viewModel.keysBackupState.value) { KeysBackupState.NotTrusted -> { context?.let { context -> startActivity(KeysBackupManageActivity.intent(context)) } } KeysBackupState.Disabled -> { context?.let { context -> startActivityForResult(KeysBackupSetupActivity.intent(context, true), EXPORT_REQ) } } KeysBackupState.BackingUp, KeysBackupState.WillBackUp -> { //keys are already backing up please wait context?.toast(R.string.keys_backup_is_not_finished_please_wait) } else -> { //nop } } } .setNegativeButton(R.string.action_sign_out) { _, _ -> onSignOut?.run() } .show() } } viewModel.keysExportedToFile.observe(this, Observer { val hasExportedToFile = it ?: false if (hasExportedToFile) { //We can allow to sign out sheetTitle.text = getString(R.string.action_sign_out_confirmation_simple) signoutClickableView.isVisible = true dontWantClickableView.isVisible = false setupClickableView.isVisible = false activateClickableView.isVisible = false backingUpStatusGroup.isVisible = false } }) viewModel.keysBackupState.observe(this, Observer { if (viewModel.keysExportedToFile.value == true) { //ignore this return@Observer } TransitionManager.beginDelayedTransition(rootLayout) when (it) { KeysBackupState.ReadyToBackUp -> { signoutClickableView.isVisible = true dontWantClickableView.isVisible = false setupClickableView.isVisible = false activateClickableView.isVisible = false backingUpStatusGroup.isVisible = true backupProgress.isVisible = false backupCompleteImage.isVisible = true backupStatusTex.text = getString(R.string.keys_backup_info_keys_all_backup_up) sheetTitle.text = getString(R.string.action_sign_out_confirmation_simple) } KeysBackupState.BackingUp, KeysBackupState.WillBackUp -> { backingUpStatusGroup.isVisible = true sheetTitle.text = getString(R.string.sign_out_bottom_sheet_warning_backing_up) dontWantClickableView.isVisible = true setupClickableView.isVisible = false activateClickableView.isVisible = false backupProgress.isVisible = true backupCompleteImage.isVisible = false backupStatusTex.text = getString(R.string.sign_out_bottom_sheet_backing_up_keys) } KeysBackupState.NotTrusted -> { backingUpStatusGroup.isVisible = false dontWantClickableView.isVisible = true setupClickableView.isVisible = false activateClickableView.isVisible = true sheetTitle.text = getString(R.string.sign_out_bottom_sheet_warning_backup_not_active) } else -> { backingUpStatusGroup.isVisible = false dontWantClickableView.isVisible = true setupClickableView.isVisible = true activateClickableView.isVisible = false sheetTitle.text = getString(R.string.sign_out_bottom_sheet_warning_no_backup) } } // updateSignOutSection() }) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.bottom_sheet_logout_and_backup, container, false) ButterKnife.bind(this, view) return view } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) //We want to force the bottom sheet initial state to expanded (dialog as? BottomSheetDialog)?.let { bottomSheetDialog -> bottomSheetDialog.setOnShowListener { dialog -> val d = dialog as BottomSheetDialog (d.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as? FrameLayout)?.let { BottomSheetBehavior.from(it).state = BottomSheetBehavior.STATE_EXPANDED } } } return dialog } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { if (requestCode == EXPORT_REQ) { val manualExportDone = data?.getBooleanExtra(KeysBackupSetupActivity.MANUAL_EXPORT, false) viewModel.keysExportedToFile.value = manualExportDone } } } }
kotlin
40
0.61907
129
38.888476
269
starcoderdata
package com.congcoi123.lonely.dragon.configuration import com.tenio.common.utility.MathUtility import java.io.IOException /** * Class to configuration. */ class ParamLoader private constructor() : FileLoaderBase("src/main/resources/params.ini") { companion object { var instance: ParamLoader? = null private set init { try { instance = ParamLoader() } catch (e: IOException) { e.printStackTrace() } } } var NUM_AGENTS: Int = 0 var NUM_OBSTACLES: Int = 0 var MIN_OBSTACLE_RADIUS: Float = 0F var MAX_OBSTACLE_RADIUS: Float = 0F // number of horizontal cells used for spatial partitioning var NUM_CELLS_X: Int = 0 // number of vertical cells used for spatial partitioning var NUM_CELLS_Y: Int = 0 // how many samples the smoother will use to average a value var NUM_SAMPLES_FOR_SMOOTHING: Int = 0 // used to tweak the combined steering force (simply altering the // MaxSteeringForce // will NOT work! This tweaker affects all the steering force multipliers too) var STEERING_FORCE_TWEAKER: Float = 0F var MAX_STEERING_FORCE: Float = 0F var MAX_SPEED: Float = 0F var VEHICLE_MASS: Float = 0F var VEHICLE_SCALE: Float = 0F var MAX_TURN_RATE_PER_SECOND: Float = 0F var SEPARATION_WEIGHT: Float = 0F var ALIGNMENT_WEIGHT: Float = 0F var COHESION_WEIGHT: Float = 0F var OBSTACLE_AVOIDANCE_WEIGHT: Float = 0F var WALL_AVOIDANCE_WEIGHT: Float = 0F var WANDER_WEIGHT: Float = 0F var SEEK_WEIGHT: Float = 0F var FLEE_WEIGHT: Float = 0F var ARRIVE_WEIGHT: Float = 0F var PURSUIT_WEIGHT: Float = 0F var OFFSET_PURSUIT_WEIGHT: Float = 0F var INTERPOSE_WEIGHT: Float = 0F var HIDE_WEIGHT: Float = 0F var EVADE_WEIGHT: Float = 0F var FOLLOW_PATH_WEIGHT: Float = 0F // how close a neighbor must be before an agent perceives it (considers it // to be within its neighborhood) var VIEW_DISTANCE: Float = 0F // used in obstacle avoidance var MIN_DETECTION_BOX_LENGTH: Float = 0F // used in wall avoidance var WALL_DETECTION_FEELER_LENGTH: Float = 0F // these are the probabilities that a steering behavior will be used // when the prioritized dither calculate method is used var PR_WALL_AVOIDANCE: Float = 0F var PR_OBSTACLE_AVOIDANCE: Float = 0F var PR_SEPARATION: Float = 0F var PR_ALIGNMENT: Float = 0F var PR_COHESION: Float = 0F var PR_WANDER: Float = 0F var PR_SEEK: Float = 0F var PR_FLEE: Float = 0F var PR_EVADE: Float = 0F var PR_HIDE: Float = 0F var PR_ARRIVE: Float = 0F init { NUM_AGENTS = nextParameterInt NUM_OBSTACLES = nextParameterInt MIN_OBSTACLE_RADIUS = nextParameterFloat MAX_OBSTACLE_RADIUS = nextParameterFloat NUM_CELLS_X = nextParameterInt NUM_CELLS_Y = nextParameterInt NUM_SAMPLES_FOR_SMOOTHING = nextParameterInt STEERING_FORCE_TWEAKER = nextParameterFloat MAX_STEERING_FORCE = nextParameterFloat * STEERING_FORCE_TWEAKER MAX_SPEED = nextParameterFloat VEHICLE_MASS = nextParameterFloat VEHICLE_SCALE = nextParameterFloat SEPARATION_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER ALIGNMENT_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER COHESION_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER OBSTACLE_AVOIDANCE_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER WALL_AVOIDANCE_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER WANDER_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER SEEK_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER FLEE_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER ARRIVE_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER PURSUIT_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER OFFSET_PURSUIT_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER INTERPOSE_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER HIDE_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER EVADE_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER FOLLOW_PATH_WEIGHT = nextParameterFloat * STEERING_FORCE_TWEAKER VIEW_DISTANCE = nextParameterFloat MIN_DETECTION_BOX_LENGTH = nextParameterFloat WALL_DETECTION_FEELER_LENGTH = nextParameterFloat PR_WALL_AVOIDANCE = nextParameterFloat PR_OBSTACLE_AVOIDANCE = nextParameterFloat PR_SEPARATION = nextParameterFloat PR_ALIGNMENT = nextParameterFloat PR_COHESION = nextParameterFloat PR_WANDER = nextParameterFloat PR_SEEK = nextParameterFloat PR_FLEE = nextParameterFloat PR_EVADE = nextParameterFloat PR_HIDE = nextParameterFloat PR_ARRIVE = nextParameterFloat MAX_TURN_RATE_PER_SECOND = MathUtility.PI } }
kotlin
13
0.680872
91
36.863636
132
starcoderdata
<gh_stars>1-10 package com.gerardbradshaw.exampleapp.squareview import android.os.SystemClock import android.view.MotionEvent import android.view.View import android.widget.FrameLayout import android.widget.ImageView import androidx.test.espresso.Espresso.onView import androidx.test.espresso.UiController import androidx.test.espresso.ViewAction import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.BoundedMatcher import androidx.test.espresso.matcher.ViewMatchers.* import com.gerardbradshaw.exampleapp.R import com.gerardbradshaw.exampleapp.testutil.GlobalTestUtil.isWithinAPercentOf import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.Matchers.allOf object SquareViewAndroidTestUtil { private const val TAG = "SquareViewAndroidTestUt" // -------------------- MOVE THUMB -------------------- fun moveThumbTo(xRatio: Double, yRatio: Double) { onView(allOf(withId(R.id.color_picker_library_large_window), isDisplayed())) .perform(touchEventDownAndUpAction(xRatio, yRatio)) } private fun touchEventDownAndUpAction(xRatio: Double, yRatio: Double): ViewAction? { return object : ViewAction { override fun getConstraints(): Matcher<View> { return isDisplayed() } override fun getDescription(): String { return "Send touch events." } override fun perform(uiController: UiController, view: View) { val viewLocation = IntArray(2) view.getLocationOnScreen(viewLocation) val touchX = ((1.0 - xRatio) * view.width).toFloat() val touchY = (yRatio * view.height).toFloat() val motionEvent = MotionEvent.obtain( SystemClock.uptimeMillis(), SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_DOWN, touchX, touchY, 0) view.dispatchTouchEvent(motionEvent) } } } // -------------------- CHECK THUMB POSITION -------------------- fun checkThumbIsAtRatioPosition(tintRatio: Double, shadeRatio: Double) { onView(allOf(withId(R.id.color_picker_library_large_window_and_thumb_container), isDisplayed())) .check(matches(thumbIsApproximatelyAtRatioPosition(tintRatio, shadeRatio))) } private fun thumbIsApproximatelyAtRatioPosition(tintRatio: Double, shadeRatio: Double): Matcher<View?>? { return object : BoundedMatcher<View?, FrameLayout>(FrameLayout::class.java) { override fun matchesSafely(view: FrameLayout): Boolean { val window: FrameLayout = view.findViewById(R.id.color_picker_library_large_window) val thumb: ImageView = view.findViewById(R.id.color_picker_library_large_thumb) val actualTintRatio = 1.0 - (thumb.x / window.width.toDouble()) val actualShadeRatio = thumb.y / window.height.toDouble() return tintRatio.isWithinAPercentOf(actualTintRatio) && shadeRatio.isWithinAPercentOf(actualShadeRatio) } override fun describeTo(description: Description) { description.appendText("thumb is at ratio position") } } } }
kotlin
23
0.710032
111
35.364706
85
starcoderdata
package com.kyhsgeekcode.filechooser.model import at.pollaknet.api.facile.FacileReflector import at.pollaknet.api.facile.symtab.TypeKind import at.pollaknet.api.facile.symtab.symbols.Type import java.nio.ByteBuffer import java.nio.ByteOrder class FileItemDotNetSymbol(text: String, val reflector: FacileReflector, val type: Type) : FileItem(text) { override fun canExpand(): Boolean = true override fun isRawAvailable(): Boolean = false @ExperimentalUnsignedTypes override fun listSubItems(publisher: (Int, Int) -> Unit): List<FileItem> { val result = ArrayList<FileItem>() val fields = type.fields val methods = type.methods for (field in fields) { val c = field.constant var fieldDesc: String? = field.name + ":" + field.typeRef.name if (c != null) { val kind = c.elementTypeKind val bytes = c.value val value: Any = getValueFromTypeKindAndBytes(bytes, kind) fieldDesc += "(=" fieldDesc += value fieldDesc += ")" } result.add(FileItemFinal(fieldDesc ?: "?")) } for (method in methods) { result.add(FileItemMethod(method.name + method.methodSignature, reflector, method)) } return result } } @ExperimentalUnsignedTypes fun getValueFromTypeKindAndBytes(bytes: ByteArray, kind: Int): Any { val bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) return when (kind) { TypeKind.ELEMENT_TYPE_BOOLEAN -> bytes[0].toInt() != 0 TypeKind.ELEMENT_TYPE_CHAR -> bytes[0].toChar() TypeKind.ELEMENT_TYPE_I -> bb.int TypeKind.ELEMENT_TYPE_I1 -> bb.get() TypeKind.ELEMENT_TYPE_I2 -> bb.short TypeKind.ELEMENT_TYPE_I4 -> bb.int TypeKind.ELEMENT_TYPE_I8 -> bb.long TypeKind.ELEMENT_TYPE_U -> bb.long TypeKind.ELEMENT_TYPE_U1 -> bb.get().toUByte() and 0xFF.toUByte() TypeKind.ELEMENT_TYPE_U2 -> bb.short.toUShort() and 0xFFFF.toUShort() TypeKind.ELEMENT_TYPE_U4 -> bb.int.toUInt() TypeKind.ELEMENT_TYPE_U8 -> bb.long.toULong() TypeKind.ELEMENT_TYPE_R4 -> bb.float TypeKind.ELEMENT_TYPE_R8 -> bb.double TypeKind.ELEMENT_TYPE_STRING -> String(bytes) else -> "Unknown!!!!" } }
kotlin
20
0.612583
107
39.655172
58
starcoderdata
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.statistics import androidx.activity.ComponentActivity import androidx.compose.material.Surface import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.example.android.architecture.blueprints.todoapp.R import com.example.android.architecture.blueprints.todoapp.data.Task import com.example.android.architecture.blueprints.todoapp.data.source.FakeRepository import com.example.android.architecture.blueprints.todoapp.util.saveTaskBlocking import com.google.accompanist.appcompattheme.AppCompatTheme import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Integration test for the statistics screen. */ @RunWith(AndroidJUnit4::class) @MediumTest @ExperimentalCoroutinesApi class StatisticsScreenTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() private val activity get() = composeTestRule.activity @Test fun tasks_showsNonEmptyMessage() { // Given some tasks val repository = FakeRepository().apply { saveTaskBlocking(Task("Title1", "Description1", false)) saveTaskBlocking(Task("Title2", "Description2", true)) } composeTestRule.setContent { AppCompatTheme { Surface { StatisticsScreen( openDrawer = { }, viewModel = StatisticsViewModel(repository) ) } } } val expectedActiveTaskText = activity.getString(R.string.statistics_active_tasks, 50.0f) val expectedCompletedTaskText = activity .getString(R.string.statistics_completed_tasks, 50.0f) // check that both info boxes are displayed and contain the correct info composeTestRule.onNodeWithText(expectedActiveTaskText).assertIsDisplayed() composeTestRule.onNodeWithText(expectedCompletedTaskText).assertIsDisplayed() } }
kotlin
29
0.732729
96
37.72973
74
starcoderdata
package de.groovybyte.gamejam.styxreactor.game.datatransfer import de.groovybyte.gamejam.styxreactor.framework.ClientContext import de.groovybyte.gamejam.styxreactor.game.datatransfer.server2client.ServerMessage class Error( val type: String, val data: Any? = null ) fun ClientContext.sendError(type: String, data: Any? = null) = send( ServerMessage( command = "error", payload = Error( type = type, data = data ) ) )
kotlin
16
0.678351
86
24.526316
19
starcoderdata
<reponame>Victor-Chinewubeze/algorithms-exercism internal fun twofer(name: String = "you"): String { return "One for $name, one for me." }
kotlin
6
0.725352
51
34.75
4
starcoderdata
<reponame>Mandarin-Medien/stopp-corona-de-android package de.schwerin.stoppCoronaDE.screens.routing import android.net.Uri import de.schwerin.stoppCoronaDE.model.repositories.OnboardingRepository import de.schwerin.stoppCoronaDE.skeleton.core.model.helpers.AppDispatchers import de.schwerin.stoppCoronaDE.skeleton.core.screens.base.viewmodel.ScopedViewModel /** * Handles router actions. * * Routing strategies: * 1) deeplinking * - at a later point of time * 2) onboarding on if has not been seen by user yet * 3) else dashboard. */ class RouterViewModel( appDispatchers: AppDispatchers, private val onboardingRepository: OnboardingRepository ) : ScopedViewModel(appDispatchers) { fun route(deepLinkUri: Uri?): RouterAction { return when { onboardingRepository.shouldShowOnboarding -> RouterAction.Onboarding else -> RouterAction.Dashboard } } } sealed class RouterAction { object Onboarding : RouterAction() object Dashboard : RouterAction() }
kotlin
12
0.749027
85
28.371429
35
starcoderdata
<reponame>AbhiyantrikTechnology/DentalHub-Android-App package com.abhiyantrik.dentalhub.models import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize class Screening : Parcelable { var id: String = "" var carries_risk: String = "" var decayed_primary_teeth: Int = 0 var decayed_permanent_teeth: Int = 0 var cavity_permanent_anterior_teeth: Boolean = false var cavity_permanent_posterior_teeth: Boolean = false var reversible_pulpitis: Boolean = false var need_art_filling: Boolean = false var need_sealant: Boolean = false var need_sdf: Boolean = false var need_extraction: Boolean = false var active_infection: Boolean = false }
kotlin
6
0.734752
57
32.571429
21
starcoderdata
package org.hexworks.zircon.internal.tileset.transformer import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.api.tileset.TileTexture import org.hexworks.zircon.api.tileset.TextureTransformer import java.awt.image.BufferedImage class Java2DNoOpTransformer : TextureTransformer<BufferedImage> { override fun transform(texture: TileTexture<BufferedImage>, tile: Tile) = texture }
kotlin
10
0.8325
85
35.363636
11
starcoderdata
package com.example.cryptoapp.data.source import com.example.cryptoapp.network.CryptoService import javax.inject.Inject class HomeRemoteDataSource @Inject constructor(private val cryptoService: CryptoService) : BaseRemoteDataSource() { suspend fun getCryptoCurrencies() = getResult { cryptoService.getCryptoCurrencies() } }
kotlin
13
0.816817
90
36.111111
9
starcoderdata
<gh_stars>1-10 /* * * Created by mahmoud on 12/27/21, 11:33 PM * Copyright (c) 2021 . All rights reserved. * Last modified 12/22/21, 10:24 AM */ package com.mahmoud.dfont.extensions import android.util.Log import android.view.View import androidx.core.content.res.ResourcesCompat import com.mahmoud.dfont.services.ChangeableTypefaceViews import com.mahmoud.dfont.services.DFontSharedPreferences import com.mahmoud.dfont.utils.DFontKeys.DFONT_TAG /** * When this function is called, * - First check if the view hasTypeface using [ChangeableTypefaceViews.hasTypeface] function * - Get typeface from sharedPreferences using [DFontSharedPreferences.getInt] then check if it is * not [ResourcesCompat.ID_NULL] * - Call [ChangeableTypefaceViews.changeTypeface] to change view typeface accirdingly * * @see ChangeableTypefaceViews.hasTypeface * @see DFontSharedPreferences.getInt, * @see ChangeableTypefaceViews.changeTypeface */ fun View.notifyTypefaceChanged() { if (!ChangeableTypefaceViews.hasTypeface(this)) { Log.d(DFONT_TAG, "notifyTypefaceChanged: ${this.javaClass.name} has no typeface.") return } val typeface = DFontSharedPreferences.getFont() if (typeface == ResourcesCompat.ID_NULL) { Log.d(DFONT_TAG, "No typeface stored in DFontSharedPreferences. Call " + "DFontSharedPreferences.saveFont(...) to save your desired font") return } // TODO: check if view typeface is identical to @typeface variable ChangeableTypefaceViews.changeTypeface(this, context, typeface) }
kotlin
16
0.745385
98
32.446809
47
starcoderdata
package br.com.angelorobson.whatsapplinkgenerator.ui.share import org.threeten.bp.LocalDateTime fun getNow(): String { return LocalDateTime.now().toString() }
kotlin
10
0.786585
58
22.571429
7
starcoderdata
package com.lianyi.paimonsnotebook.lib.adapter import android.view.View import android.view.ViewGroup import androidx.viewpager.widget.PagerAdapter //viewpager通用适配器 class PagerAdapter(val pages:List<View>, val titles:List<String>): PagerAdapter(){ override fun getCount(): Int { return pages.size } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view == `object` } override fun instantiateItem(container: ViewGroup, position: Int): Any { container.addView(pages[position]) return pages[position] } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(pages[position]) } override fun getPageTitle(position: Int): CharSequence { return titles[position] } }
kotlin
12
0.698663
82
27.413793
29
starcoderdata
<filename>app/src/main/java/com/breiter/movietowatchapp/ui/screen/search/SearchMovieAdapter.kt package com.breiter.movietowatchapp.ui.screen.search import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.breiter.movietowatchapp.data.domain.Movie import com.breiter.movietowatchapp.databinding.ListItemMovieBinding class SearchMovieAdapter( private val listener: OnClickListener ) : ListAdapter<Movie, SearchMovieAdapter.ViewHolder>(DIFF_CALLBACK) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder.from(parent) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val movieItem = getItem(position) holder.itemView.setOnClickListener { listener.onClick(movieItem) } holder.bind(movieItem) } interface OnClickListener { fun onClick(movieItem: Movie) } //Compare objects companion object { val DIFF_CALLBACK: DiffUtil.ItemCallback<Movie> = object : DiffUtil.ItemCallback<Movie>() { override fun areItemsTheSame(oldItem: Movie, newItem: Movie) = oldItem == newItem override fun areContentsTheSame(oldItem: Movie, newItem: Movie) = oldItem.id == newItem.id } } /** * View Holder for a [Movie] RecyclerView list item. */ class ViewHolder(private val binding: ListItemMovieBinding) : RecyclerView.ViewHolder(binding.root) { fun bind( movieItem: Movie ) { binding.run { movie = movieItem executePendingBindings() } } companion object { fun from(parent: ViewGroup): ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val binding = ListItemMovieBinding.inflate(layoutInflater, parent, false) return ViewHolder(binding) } } } }
kotlin
17
0.650694
94
30.9
70
starcoderdata
package com.jetbrains.edu.learning.stepik.hyperskill.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.jetbrains.edu.learning.EduUtils import com.jetbrains.edu.learning.EduUtilsKt.showPopup import com.jetbrains.edu.learning.courseFormat.CheckStatus.Unchecked import com.jetbrains.edu.learning.courseFormat.tasks.data.DataTask import com.jetbrains.edu.learning.messages.EduCoreBundle import org.jetbrains.annotations.NonNls class DownloadDatasetAction : DownloadDatasetActionBase(EduCoreBundle.lazyMessage("hyperskill.action.download.dataset"), PROCESS_MESSAGE, Unchecked) { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val task = EduUtils.getCurrentTask(project) as? DataTask ?: return if (!checkAuthorized(project, task.course)) return if (!DownloadDataset.lock(project)) { e.dataContext.showPopup(EduCoreBundle.message("hyperskill.download.dataset.already.running")) return } downloadDatasetInBackground(project, task, false) } companion object { @NonNls const val ACTION_ID: String = "Hyperskill.DownloadDataset" @NonNls private const val PROCESS_MESSAGE: String = "Download dataset in progress" } }
kotlin
17
0.78363
122
34.285714
35
starcoderdata
<reponame>tim-patterson/jsonsql<filename>src/main/kotlin/jsonsql/physical/operators/SortOperator.kt package jsonsql.physical.operators import jsonsql.physical.* import jsonsql.query.OrderExpr class SortOperator( private val sortExpressions: List<OrderExpr>, private val source: PhysicalOperator ): PhysicalOperator() { override val columnAliases by lazy { source.columnAliases } override fun data(context: ExecutionContext): ClosableSequence<Tuple> { val compiledSortBy = sortExpressions.map { CompiledOrderByExpr(compileExpression(it.expression, source.columnAliases), if (it.asc) 1 else -1) } val sourceData = source.data(context) return sourceData.sortedWith(Comparator { row1, row2 -> for (orderExpr in compiledSortBy) { val expr = orderExpr.expression val comparison = jsonsql.functions.compareValuesForSort(expr.evaluate(row1), expr.evaluate(row2)) if (comparison != 0) return@Comparator comparison * orderExpr.order } 0 }).withClose { sourceData.close() } } // For explain output override fun toString() = "Sort($sortExpressions)" } private data class CompiledOrderByExpr(val expression: ExpressionExecutor, val order: Int)
kotlin
30
0.683973
113
35.944444
36
starcoderdata
package history import BaseService import org.jetbrains.exposed.sql.Join import org.jetbrains.exposed.sql.ResultRow import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.statements.UpdateBuilder import shared.auth.User import shared.base.GenericItem import shared.base.History import shared.base.InvalidAttributeException class HistoryService : BaseService<HistoryTable, History>( HistoryTable ) { override val HistoryTable.connections: Join? get() = null var retrievedUser: User? = null suspend inline fun <reified T : GenericItem> getFor(typeId: Int?, user: User?) = tryCall { if (typeId == null) throw InvalidAttributeException("typeId") if (user?.uuid == null) throw InvalidAttributeException("user or uuid") table.select { (table.field regexp "${T::class.simpleName} $typeId .*") and (table.updatedBy eq user.uuid!!) }.mapNotNull { retrievedUser = user toItem(it).also { retrievedUser = null } } } suspend inline fun <reified T : GenericItem> getIdsFor(typeId: Int?, user: User?) = getFor<T>(typeId, user)?.map { it.id!! } override suspend fun toItem(row: ResultRow) = History( id = row[table.id], field = row[table.field], oldValue = row[table.oldValue], newValue = row[table.newValue], updatedBy = retrievedUser ?: throw InvalidAttributeException("User"), dateCreated = row[table.dateCreated], dateUpdated = row[table.dateUpdated] ) override fun UpdateBuilder<Int>.toRow(item: History) { this[table.field] = item.field this[table.oldValue] = item.oldValue.toString() this[table.newValue] = item.newValue.toString() this[table.updatedBy] = item.updatedBy.uuid!! } }
kotlin
24
0.656365
105
31.913793
58
starcoderdata
package maryk.core.properties.enum import maryk.core.definitions.PrimitiveType.TypeDefinition import maryk.core.exceptions.DefNotFoundException import maryk.core.exceptions.SerializationException import maryk.core.models.ContextualDataModel import maryk.core.properties.IsPropertyContext import maryk.core.properties.ObjectPropertyDefinitions import maryk.core.properties.definitions.EmbeddedObjectDefinition import maryk.core.properties.definitions.IsValueDefinition import maryk.core.properties.definitions.NumberDefinition import maryk.core.properties.definitions.StringDefinition import maryk.core.properties.definitions.contextual.ContextCollectionTransformerDefinition import maryk.core.properties.definitions.contextual.MultiTypeDefinitionContext import maryk.core.properties.definitions.list import maryk.core.properties.definitions.string import maryk.core.properties.definitions.wrapper.ContextualDefinitionWrapper import maryk.core.properties.types.numeric.UInt32 import maryk.core.query.ContainsDefinitionsContext import maryk.core.values.ObjectValues import maryk.json.IsJsonLikeReader import maryk.json.IsJsonLikeWriter import maryk.json.JsonToken.StartDocument import maryk.json.JsonToken.Value import maryk.lib.exceptions.ParseException import maryk.yaml.IsYamlReader import kotlin.reflect.KClass /** Enum Definitions with a [name] and [cases] with types */ open class MultiTypeEnumDefinition<E : MultiTypeEnum<*>> internal constructor( optionalCases: (() -> Array<E>)?, name: String, reservedIndices: List<UInt>? = null, reservedNames: List<String>? = null, unknownCreator: ((UInt, String) -> E)? = null ) : AbstractIndexedEnumDefinition<E>( optionalCases, name, reservedIndices, reservedNames, unknownCreator ) { override val primitiveType = TypeDefinition // Because of compilation issue in Native this map contains IndexedEnum<E> instead of E as value private val valueByString: Map<String, E> by lazy<Map<String, E>> { mutableMapOf<String, E>().also { output -> for (type in cases()) { output[type.name] = type type.alternativeNames?.forEach { name: String -> if (output.containsKey(name)) throw ParseException("Enum ${this.name} already has a case for $name") output[name] = type } } } } // Because of compilation issue in Native this map contains IndexedEnum<E> instead of E as value private val valueByIndex by lazy { cases().associateBy { it.index } } override val cases get() = optionalCases!! constructor( enumClass: KClass<E>, values: () -> Array<E>, reservedIndices: List<UInt>? = null, reservedNames: List<String>? = null, unknownCreator: ((UInt, String) -> E)? = null ) : this( name = enumClass.simpleName ?: throw DefNotFoundException("No name for enum class"), optionalCases = values, reservedIndices = reservedIndices, reservedNames = reservedNames, unknownCreator = unknownCreator ) internal constructor( name: String, values: () -> Array<E>, reservedIndices: List<UInt>? = null, reservedNames: List<String>? = null, unknownCreator: ((UInt, String) -> E)? = null ) : this( name = name, optionalCases = values, reservedIndices = reservedIndices, reservedNames = reservedNames, unknownCreator = unknownCreator ) internal object Properties : ObjectPropertyDefinitions<MultiTypeEnumDefinition<MultiTypeEnum<*>>>() { val name by string( 1u, MultiTypeEnumDefinition<*>::name ) val cases = ContextualDefinitionWrapper<List<MultiTypeEnum<*>>, Array<MultiTypeEnum<*>>, MultiTypeDefinitionContext, ContextCollectionTransformerDefinition<MultiTypeEnum<*>, List<MultiTypeEnum<*>>, MultiTypeDefinitionContext, ContainsDefinitionsContext>, MultiTypeEnumDefinition<MultiTypeEnum<*>>>( 2u, "cases", definition = ContextCollectionTransformerDefinition( definition = MultiTypeDescriptorListDefinition(), contextTransformer = { context: MultiTypeDefinitionContext? -> context?.definitionsContext } ), toSerializable = { values: Array<MultiTypeEnum<*>>?, _ -> values?.toList() }, fromSerializable = { values -> values?.toTypedArray() }, getter = { it.cases() } ).apply { addSingle(this) } val reservedIndices by list( index = 3u, getter = MultiTypeEnumDefinition<*>::reservedIndices, valueDefinition = NumberDefinition( type = UInt32, minValue = 1u ) ) val reservedNames by list( index = 4u, getter = MultiTypeEnumDefinition<*>::reservedNames, valueDefinition = StringDefinition() ) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is MultiTypeEnumDefinition<*>) return false if (optionalCases != null) { return if (other.optionalCases != null) { other.optionalCases.invoke().contentEquals(optionalCases.invoke()) } else false } if (name != other.name) return false if (reservedIndices != other.reservedIndices) return false if (reservedNames != other.reservedNames) return false return true } override fun hashCode(): Int { var result = optionalCases?.invoke().hashCode() result = 31 * result + name.hashCode() result = 31 * result + reservedIndices.hashCode() result = 31 * result + reservedNames.hashCode() return result } override fun enumTypeIsCompatible(storedEnum: E, newEnum: E, addIncompatibilityReason: ((String) -> Unit)?): Boolean { return newEnum.definition!!.compatibleWith(storedEnum.definition!!, addIncompatibilityReason) } internal object Model : ContextualDataModel<MultiTypeEnumDefinition<MultiTypeEnum<*>>, Properties, ContainsDefinitionsContext, MultiTypeDefinitionContext>( properties = Properties, contextTransformer = { MultiTypeDefinitionContext(it) } ) { override fun invoke(values: ObjectValues<MultiTypeEnumDefinition<MultiTypeEnum<*>>, Properties>): MultiTypeEnumDefinition<MultiTypeEnum<*>> { return MultiTypeEnumDefinition( name = values(1u), optionalCases = values<Array<MultiTypeEnum<*>>?>(2u)?.let { { it } }, reservedIndices = values(3u), reservedNames = values(4u), unknownCreator = { index, name -> MultiTypeEnum.invoke(index, name, null) } ) } override fun writeJson( values: ObjectValues<MultiTypeEnumDefinition<MultiTypeEnum<*>>, Properties>, writer: IsJsonLikeWriter, context: MultiTypeDefinitionContext? ) { throw SerializationException("Cannot write definitions from Values") } override fun writeJson( obj: MultiTypeEnumDefinition<MultiTypeEnum<*>>, writer: IsJsonLikeWriter, context: MultiTypeDefinitionContext? ) { if (context?.definitionsContext?.typeEnums?.containsKey(obj.name) == true) { // Write a single string name if no options was defined val value = Properties.name.getPropertyAndSerialize(obj, context) ?: throw ParseException("Missing requests in Requests") Properties.name.writeJsonValue(value, writer, context) Properties.name.capture(context, value) } else { // Only skip when DefinitionsContext was set when { context?.definitionsContext != null && context.definitionsContext.currentDefinitionName == obj.name -> { super.writeJson(obj, writer, context, skip = listOf(Properties.name)) context.definitionsContext.currentDefinitionName = "" } else -> { super.writeJson(obj, writer, context) } } } } override fun readJson( reader: IsJsonLikeReader, context: MultiTypeDefinitionContext? ): ObjectValues<MultiTypeEnumDefinition<MultiTypeEnum<*>>, Properties> { if (reader.currentToken == StartDocument) { reader.nextToken() } return if (reader.currentToken is Value<*>) { val value = Properties.name.readJson(reader, context) Properties.name.capture(context, value) this.values { mapNonNulls( name withSerializable value ) } } else { super.readJson(reader, context) } } override fun readJsonToMap(reader: IsJsonLikeReader, context: MultiTypeDefinitionContext?) = context?.definitionsContext?.currentDefinitionName.let { name -> when (name) { null, "" -> super.readJsonToMap(reader, context) else -> { context?.definitionsContext?.currentDefinitionName = "" super.readJsonToMap(reader, context).also { it[Properties.name.index] = name } } } } } } /** * Definition for Multi type descriptor List property. * Overrides ListDefinition so it can write special Yaml notation with complex field names. */ private class MultiTypeDescriptorListDefinition : maryk.core.properties.definitions.IsListDefinition<MultiTypeEnum<*>, IsPropertyContext> { override val required: Boolean = true override val final: Boolean = false override val minSize: UInt? = null override val maxSize: UInt? = null override val default: List<MultiTypeEnum<*>>? = null override val valueDefinition: IsValueDefinition<MultiTypeEnum<*>, IsPropertyContext> = EmbeddedObjectDefinition( dataModel = { MultiTypeEnum.Model } ) /** Write [value] to JSON [writer] with [context] */ override fun writeJsonValue( value: List<MultiTypeEnum<*>>, writer: IsJsonLikeWriter, context: IsPropertyContext? ) { if (writer is maryk.yaml.YamlWriter) { writer.writeStartObject() for (it in value) { this.valueDefinition.writeJsonValue(it, writer, context) } writer.writeEndObject() } else { writer.writeStartArray() for (it in value) { this.valueDefinition.writeJsonValue(it, writer, context) } writer.writeEndArray() } } /** Read Collection from JSON [reader] within optional [context] */ override fun readJson(reader: IsJsonLikeReader, context: IsPropertyContext?): List<MultiTypeEnum<*>> { val collection: MutableList<MultiTypeEnum<*>> = newMutableCollection(context) if (reader is IsYamlReader) { if (reader.currentToken !is maryk.json.JsonToken.StartObject) { throw ParseException("YAML definition map should be an Object") } while (reader.nextToken() !== maryk.json.JsonToken.EndObject) { collection.add( valueDefinition.readJson(reader, context) ) } } else { if (reader.currentToken !is maryk.json.JsonToken.StartArray) { throw ParseException("JSON value should be an Array") } while (reader.nextToken() !== maryk.json.JsonToken.EndArray) { collection.add( valueDefinition.readJson(reader, context) ) } } return collection } }
kotlin
34
0.615018
306
39.168831
308
starcoderdata
<gh_stars>1-10 // Automatically generated - do not modify! package org.w3c.dom.events inline val Event.Companion.ABORT: EventType<Event> get() = EventType("abort") inline val Event.Companion.REMOVE: EventType<Event> get() = EventType("remove") inline val Event.Companion.ENDED: EventType<Event> get() = EventType("ended") inline val Event.Companion.PROCESS_OR_ERROR: EventType<Event> get() = EventType("processorerror") inline val Event.Companion.STATE_CHANGE: EventType<Event> get() = EventType("statechange") inline val Event.Companion.FULLSCREEN_CHANGE: EventType<Event> get() = EventType("fullscreenchange") inline val Event.Companion.FULLSCREEN_ERROR: EventType<Event> get() = EventType("fullscreenerror") inline val Event.Companion.POINTER_LOCK_CHANGE: EventType<Event> get() = EventType("pointerlockchange") inline val Event.Companion.POINTER_LOCK_ERROR: EventType<Event> get() = EventType("pointerlockerror") inline val Event.Companion.READY_STATE_CHANGE: EventType<Event> get() = EventType("readystatechange") inline val Event.Companion.VISIBILITY_CHANGE: EventType<Event> get() = EventType("visibilitychange") inline val Event.Companion.ERROR: EventType<Event> get() = EventType("error") inline val Event.Companion.OPEN: EventType<Event> get() = EventType("open") inline val Event.Companion.LOADING: EventType<Event> get() = EventType("loading") inline val Event.Companion.LOADING_DONE: EventType<Event> get() = EventType("loadingdone") inline val Event.Companion.LOADING_ERROR: EventType<Event> get() = EventType("loadingerror") inline val Event.Companion.CAN_PLAY: EventType<Event> get() = EventType("canplay") inline val Event.Companion.CAN_PLAY_THROUGH: EventType<Event> get() = EventType("canplaythrough") inline val Event.Companion.CHANGE: EventType<Event> get() = EventType("change") inline val Event.Companion.CLOSE: EventType<Event> get() = EventType("close") inline val Event.Companion.CUE_CHANGE: EventType<Event> get() = EventType("cuechange") inline val Event.Companion.DURATION_CHANGE: EventType<Event> get() = EventType("durationchange") inline val Event.Companion.EMPTIED: EventType<Event> get() = EventType("emptied") inline val Event.Companion.INPUT: EventType<Event> get() = EventType("input") inline val Event.Companion.INVALID: EventType<Event> get() = EventType("invalid") inline val Event.Companion.LOAD: EventType<Event> get() = EventType("load") inline val Event.Companion.LOADED_DATA: EventType<Event> get() = EventType("loadeddata") inline val Event.Companion.LOADED_METADATA: EventType<Event> get() = EventType("loadedmetadata") inline val Event.Companion.LOAD_START: EventType<Event> get() = EventType("loadstart") inline val Event.Companion.PAUSE: EventType<Event> get() = EventType("pause") inline val Event.Companion.PLAY: EventType<Event> get() = EventType("play") inline val Event.Companion.PLAYING: EventType<Event> get() = EventType("playing") inline val Event.Companion.RATE_CHANGE: EventType<Event> get() = EventType("ratechange") inline val Event.Companion.RESET: EventType<Event> get() = EventType("reset") inline val Event.Companion.SCROLL: EventType<Event> get() = EventType("scroll") inline val Event.Companion.SEEKED: EventType<Event> get() = EventType("seeked") inline val Event.Companion.SEEKING: EventType<Event> get() = EventType("seeking") inline val Event.Companion.SELECT: EventType<Event> get() = EventType("select") inline val Event.Companion.SELECTION_CHANGE: EventType<Event> get() = EventType("selectionchange") inline val Event.Companion.SELECT_START: EventType<Event> get() = EventType("selectstart") inline val Event.Companion.STALLED: EventType<Event> get() = EventType("stalled") inline val Event.Companion.SUSPEND: EventType<Event> get() = EventType("suspend") inline val Event.Companion.TIME_UPDATE: EventType<Event> get() = EventType("timeupdate") inline val Event.Companion.TOGGLE: EventType<Event> get() = EventType("toggle") inline val Event.Companion.VOLUME_CHANGE: EventType<Event> get() = EventType("volumechange") inline val Event.Companion.WAITING: EventType<Event> get() = EventType("waiting") inline val Event.Companion.WEBKIT_ANIMATION_END: EventType<Event> get() = EventType("webkitanimationend") inline val Event.Companion.WEBKIT_ANIMATION_ITERATION: EventType<Event> get() = EventType("webkitanimationiteration") inline val Event.Companion.WEBKIT_ANIMATION_START: EventType<Event> get() = EventType("webkitanimationstart") inline val Event.Companion.WEBKIT_TRANSITION_END: EventType<Event> get() = EventType("webkittransitionend") inline val Event.Companion.ORIENTATION_CHANGE: EventType<Event> get() = EventType("orientationchange") inline val Event.Companion.WAITING_FOR_KEY: EventType<Event> get() = EventType("waitingforkey") inline val Event.Companion.ENTER_PICTURE_IN_PICTURE: EventType<Event> get() = EventType("enterpictureinpicture") inline val Event.Companion.LEAVE_PICTURE_IN_PICTURE: EventType<Event> get() = EventType("leavepictureinpicture") inline val Event.Companion.BLOCKED: EventType<Event> get() = EventType("blocked") inline val Event.Companion.SUCCESS: EventType<Event> get() = EventType("success") inline val Event.Companion.COMPLETE: EventType<Event> get() = EventType("complete") inline val Event.Companion.DEVICE_CHANGE: EventType<Event> get() = EventType("devicechange") inline val Event.Companion.KEY_STATUSES_CHANGE: EventType<Event> get() = EventType("keystatuseschange") inline val Event.Companion.RESUME: EventType<Event> get() = EventType("resume") inline val Event.Companion.START: EventType<Event> get() = EventType("start") inline val Event.Companion.STOP: EventType<Event> get() = EventType("stop") inline val Event.Companion.SOURCE_CLOSE: EventType<Event> get() = EventType("sourceclose") inline val Event.Companion.SOURCE_ENDED: EventType<Event> get() = EventType("sourceended") inline val Event.Companion.SOURCE_OPEN: EventType<Event> get() = EventType("sourceopen") inline val Event.Companion.MUTE: EventType<Event> get() = EventType("mute") inline val Event.Companion.UNMUTE: EventType<Event> get() = EventType("unmute") inline val Event.Companion.CLICK: EventType<Event> get() = EventType("click") inline val Event.Companion.SHOW: EventType<Event> get() = EventType("show") inline val Event.Companion.PAYMENT_METHOD_CHANGE: EventType<Event> get() = EventType("paymentmethodchange") inline val Event.Companion.RESOURCE_TIMING_BUFFER_FULL: EventType<Event> get() = EventType("resourcetimingbufferfull") inline val Event.Companion.RESIZE: EventType<Event> get() = EventType("resize") inline val Event.Companion.BUFFERED_AMOUNT_LOW: EventType<Event> get() = EventType("bufferedamountlow") inline val Event.Companion.CONNECTION_STATE_CHANGE: EventType<Event> get() = EventType("connectionstatechange") inline val Event.Companion.ICE_CANDIDATE_ERROR: EventType<Event> get() = EventType("icecandidateerror") inline val Event.Companion.ICE_CONNECTION_STATE_CHANGE: EventType<Event> get() = EventType("iceconnectionstatechange") inline val Event.Companion.ICE_GATHERING_STATE_CHANGE: EventType<Event> get() = EventType("icegatheringstatechange") inline val Event.Companion.NEGOTIATION_NEEDED: EventType<Event> get() = EventType("negotiationneeded") inline val Event.Companion.SIGNALING_STATE_CHANGE: EventType<Event> get() = EventType("signalingstatechange") inline val Event.Companion.CONNECT: EventType<Event> get() = EventType("connect") inline val Event.Companion.CONNECTING: EventType<Event> get() = EventType("connecting") inline val Event.Companion.DISCONNECT: EventType<Event> get() = EventType("disconnect") inline val Event.Companion.CONTROLLER_CHANGE: EventType<Event> get() = EventType("controllerchange") inline val Event.Companion.UPDATE_FOUND: EventType<Event> get() = EventType("updatefound") inline val Event.Companion.UPDATE: EventType<Event> get() = EventType("update") inline val Event.Companion.UPDATE_END: EventType<Event> get() = EventType("updateend") inline val Event.Companion.UPDATE_START: EventType<Event> get() = EventType("updatestart") inline val Event.Companion.ADD_SOURCE_BUFFER: EventType<Event> get() = EventType("addsourcebuffer") inline val Event.Companion.REMOVE_SOURCE_BUFFER: EventType<Event> get() = EventType("removesourcebuffer") inline val Event.Companion.VOICES_CHANGED: EventType<Event> get() = EventType("voiceschanged") inline val Event.Companion.ENTER: EventType<Event> get() = EventType("enter") inline val Event.Companion.EXIT: EventType<Event> get() = EventType("exit") inline val Event.Companion.AFTER_PRINT: EventType<Event> get() = EventType("afterprint") inline val Event.Companion.BEFORE_PRINT: EventType<Event> get() = EventType("beforeprint") inline val Event.Companion.LANGUAGE_CHANGE: EventType<Event> get() = EventType("languagechange") inline val Event.Companion.OFFLINE: EventType<Event> get() = EventType("offline") inline val Event.Companion.ONLINE: EventType<Event> get() = EventType("online") inline val Event.Companion.UNLOAD: EventType<Event> get() = EventType("unload") inline val Event.Companion.WEBKIT_FULLSCREEN_CHANGE: EventType<Event> get() = EventType("webkitfullscreenchange")
kotlin
7
0.740702
72
30.800664
301
starcoderdata
<filename>app/src/main/java/com/arch/template/base/BaseViewModel.kt<gh_stars>1-10 package com.arch.template.base import androidx.lifecycle.ViewModel import com.arch.error.mappers.ExceptionMappers import com.arch.error.presenters.SnackBarDuration import com.arch.error.presenters.ToastDuration import com.arch.template.errors.handler.AndroidExceptionHandlerBinder import com.arch.template.errors.handler.AndroidExceptionHandlerBinderImpl import com.arch.template.errors.presenters.* import com.arch.template.utils.MyAppLogger abstract class BaseViewModel : ViewModel() { val exceptionHandler: AndroidExceptionHandlerBinder val snackBarErrorPresenter by lazy { SnackBarAndroidErrorPresenter( duration = SnackBarDuration.SHORT ) } val toastErrorPresenter by lazy { ToastAndroidErrorPresenter( duration = ToastDuration.LONG ) } val alertErrorPresenter by lazy { AlertAndroidErrorPresenter() } init { exceptionHandler = AndroidExceptionHandlerBinderImpl( androidErrorPresenter = SelectorAndroidErrorPresenter { throwable -> getSelectorPresenter(throwable) ?: toastErrorPresenter }, exceptionMapper = ExceptionMappers.throwableMapper(), onCatch = { MyAppLogger.d("Got exception: $it") } ) } open fun getSelectorPresenter(throwable: Throwable): AndroidErrorPresenter<String>? { return toastErrorPresenter } }
kotlin
20
0.693038
89
32.369565
46
starcoderdata
<filename>Android Kotlin/KotlinFunny/app/src/main/kotlin/ru/guar7387/kotlinfunny/features/rangeswhen.kt package ru.guar7387.kotlinfunny.features public fun range1() { for (i in 1..100) { print(i) } for (i in 1.0..6.7 step 0.1) { print(i) } for (i in 100 downTo 1) { print(i) } } public fun range2() { val a = 1.0 .. 2.5 assert(1.8 in a) assert("ab" in "aa".."bb") } public fun funny() { 100.times() { print("A") } } public fun when1() { val a = 5 when (a) { 1 -> print("a is 1") in 2..4 -> print(10) else -> print("failed") } } public fun when2(): Int = when ("5") { "a" -> 0 "5" -> 1 else -> 10 }
kotlin
13
0.501362
103
14.291667
48
starcoderdata
<filename>util-validation/src/main/kotlin/com/tailoredapps/androidutil/validation/Rule.kt /* * Copyright 2019 <NAME> & <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.tailoredapps.androidutil.validation import androidx.annotation.StringRes /** * Extendable set of Rules that can be used to validate a property. */ interface Rule<T : Any> { @get:StringRes val errorMessage: Int fun validate(input: T?): Boolean } class NotNullRule<T : Any>(@StringRes override val errorMessage: Int) : Rule<T> { override fun validate(input: T?) = input != null } class NotEmptyRule(@StringRes override val errorMessage: Int) : Rule<String> { override fun validate(input: String?) = input != null && input.isNotEmpty() } class EqualRule(private val other: () -> String?, @StringRes override val errorMessage: Int) : Rule<String> { override fun validate(input: String?) = input == other.invoke() } open class RegexRule(private val pattern: String, @StringRes override val errorMessage: Int) : Rule<String> { override fun validate(input: String?) = input != null && pattern.toRegex().matches(input) } class MinLengthRule(private val length: Int, @StringRes override val errorMessage: Int) : Rule<String> { override fun validate(input: String?): Boolean = input != null && input.length >= length } class MaxLengthRule(private val length: Int, @StringRes override val errorMessage: Int) : Rule<String> { override fun validate(input: String?): Boolean = input != null && input.length <= length } class AtLeastOneUpperCaseLetterRule(@StringRes override val errorMessage: Int) : Rule<String> { override fun validate(input: String?) = input != null && input.any { it.isUpperCase() } } class AtLeastOneLowerCaseLetterRule(@StringRes override val errorMessage: Int) : Rule<String> { override fun validate(input: String?) = input != null && input.any { it.isLowerCase() } } class AtLeastOneDigitRule(@StringRes override val errorMessage: Int) : Rule<String> { override fun validate(input: String?) = input != null && input.any { it.isDigit() } } class EmailRule(@StringRes errorMessage: Int) : RegexRule( "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" + "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" + "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" + "z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" + "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" + "9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" + "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", errorMessage )
kotlin
14
0.63571
97
38.75
84
starcoderdata
package io.github.shadow578.yodel.db import android.content.Context import androidx.room.* import io.github.shadow578.yodel.db.model.* import io.github.shadow578.yodel.util.storage.decodeToFile /** * the tracks database */ @TypeConverters(DBTypeConverters::class) @Database( entities = [ TrackInfo::class ], version = 7 ) abstract class TracksDB : RoomDatabase() { /** * mark all tracks db that no longer exist (or are not accessible) in the file system as [TrackStatus.FileDeleted] * * @param ctx the context to get the files in * @return the number of removed tracks */ fun markDeletedTracks(ctx: Context): Int { // get all tracks that are (supposedly) downloaded val supposedlyDownloadedTracks = tracks().downloaded // check on every track if the downloaded file still exists var count = 0 for (track in supposedlyDownloadedTracks) { // get file for this track val trackFile = track.audioFileKey.decodeToFile(ctx) // if the file could not be decoded, // the file cannot be read OR it does not exist // assume it was removed if (trackFile != null && trackFile.canRead() && trackFile.exists() ) { // file still there, do no more continue } // mark as deleted track track.status = TrackStatus.FileDeleted tracks().update(track) count++ } return count } /** * @return the tracks DAO */ abstract fun tracks(): TracksDao companion object { /** * database name */ private const val DB_NAME = "tracks" /** * the instance singleton */ private lateinit var instance: TracksDB /** * initialize the database * * @param ctx the context to work in * @return the freshly initialized instance */ fun get(ctx: Context): TracksDB { if (!this::instance.isInitialized) { // have to initialize db instance = Room.databaseBuilder( ctx, TracksDB::class.java, DB_NAME ) .fallbackToDestructiveMigration() .build() } return instance } } }
kotlin
22
0.542285
118
26.428571
91
starcoderdata
<reponame>ChristopherME/movies-android<filename>core/network/src/main/java/com/christopher_elias/network/models/exception/NetworkMiddlewareFailure.kt package com.christopher_elias.network.models.exception import com.christopher_elias.functional_programming.Failure /* * Created by <NAME> on 22/04/2021 * <EMAIL> * * Lima, Peru. */ class NetworkMiddlewareFailure( val middleWareExceptionMessage: String, ) : Failure.CustomFailure() object TimeOut : Failure.CustomFailure() object NetworkConnectionLostSuddenly : Failure.CustomFailure() object SSLError : Failure.CustomFailure() /** * If your service return some custom error use this with the given attars you expect. */ data class ServiceBodyFailure( val internalCode: Int, val internalMessage: String? ) : Failure.CustomFailure()
kotlin
12
0.781908
149
26.827586
29
starcoderdata
package org.cafejojo.schaapi.miningpipeline import mu.KLogging import org.cafejojo.schaapi.models.Node import java.io.File /** * CSV writer that writes the desired data to separate CSV files under a data directory. * * @param output file to which to write the output */ class CsvWriter<N : Node>(output: File) { companion object : KLogging() private val dataFile: File = output.resolve("data/").apply { mkdirs() } /** * Writes graph sizes to file. * * @param graphs graphs whose node counts will be written to file */ fun writeGraphSizes(graphs: List<N>) = writeToFile("graphSize.csv", graphs, { graph: N -> graph.count() }, "graph_size") /** * Writes pattern lengths to file. * * @param patterns patterns whose lengths will be written to file */ fun writePatternLengths(patterns: Iterable<Pattern<N>>) = writeToFile("patterns.csv", patterns, { pattern: Pattern<N> -> pattern.size }, "pattern_length") /** * Writes filtered pattern lengths to file. * * @param patterns patterns whose lengths will be written to file */ fun writeFilteredPatternLengths(patterns: Iterable<Pattern<N>>) = writeToFile("filteredPatterns.csv", patterns, { pattern: Pattern<N> -> pattern.size }, "pattern_length") private fun <P> writeToFile(output: String, items: Iterable<P>, mapToInt: (P) -> Int, type: String) = File(dataFile, output).writer().use { fileWriter -> fileWriter.write("$type,count\n") items .groupBy(mapToInt) .toSortedMap() .forEach { fileWriter.write("${it.key},${it.value.size}\n") } } }
kotlin
25
0.635937
112
33.755102
49
starcoderdata