path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/pt/pro/alarm/decline/FragmentSingleClick.kt
OmAr-Kader
674,357,483
false
{"Kotlin": 2780433}
package com.pt.pro.alarm.decline import com.pt.common.global.* import com.pt.common.global.AlarmSack import com.pt.pro.alarm.interfaces.AlarmDismiss import com.pt.pro.databinding.FragmentSingleClickBinding import com.pt.common.mutual.life.GlobalSimpleFragment import com.pt.common.stable.launchImdMain class FragmentSingleClick : GlobalSimpleFragment<FragmentSingleClickBinding>(), DismissListener { override var alarm: AlarmSack? = null override var colorImage: Int = 0 override var alarmDismiss: AlarmDismiss? = null override var test: Boolean = false override val android.view.LayoutInflater.creBin: android.view.ViewGroup?.() -> android.view.View @com.pt.common.global.UiAnn get() = { FragmentSingleClickBinding.inflate(this@creBin, this, false).also { @com.pt.common.global.ViewAnn binder = it it.subMainClick.orientation = rec.linDirection }.root } @com.pt.common.global.UiAnn override fun FragmentSingleClickBinding.onViewCreated() { launchImdMain { com.pt.common.stable.justCoroutineMain { snoozeButton.setOnClickListener(this@FragmentSingleClick) dismissFrame.setOnClickListener(this@FragmentSingleClick) if (ctx.is24Hour) { clockAmPm.justGone() } content.startRippleAnimation() } com.pt.common.stable.justCoroutineMain { com.pt.common.stable.catchy(null) { if (isV_O) { try { androidx.core.content.res.ResourcesCompat.getFont( ctx, com.pt.pro.R.font.widget_font_clock ) } catch (_: android.content.res.Resources.NotFoundException) { null } } else null }?.let { clockTime.apply { typeface = it } clockAmPm.apply { typeface = it } } } com.pt.common.stable.justCoroutineMain { if (test && !nightRider) { ctx.fetchColor(com.pt.pro.R.color.bbo).let { clockTime.setTextColor(it) clockAmPm.setTextColor(it) textLabel.setTextColor(it) textRepeating.setTextColor(it) } } } } } @com.pt.common.global.UiAnn override fun FragmentSingleClickBinding.onClick(v: android.view.View) { if (v == dismissFrame) { alarmDismiss?.doDismiss() requireActivity().supportFragmentManager.popBackStack() } else { alarmDismiss?.doSnooze() } } override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { super.onConfigurationChanged(newConfig) binding.subMainClick.orientation = newConfig.linConDirection } override fun onDestroyView() { binder?.content?.stopRippleAnimation() alarmDismiss = null alarm = null binder = null super.onDestroyView() } }
0
Kotlin
0
0
fe57fe5a4029119ac287ab8d3d4b5ccfc05af3a0
3,427
PT-All-Pro
Apache License 2.0
runtime/src/main/java/ir/logicbase/mockfit/MockFitInterceptor.kt
javaherisaber
309,365,464
false
{"Kotlin": 22073}
package ir.logicbase.mockfit import okhttp3.* import java.io.IOException /** * Provide network response from json mock in local device * You should remove `Base Url` and `Query parameters` from [apiIncludeIntoMock] or [apiExcludeFromMock] * If your request contains `Path parameters` eg. {product_id}, replace it with {#} * * @property bodyFactory interface to access InputStream for file operations * @property logger interface to log messages * @property baseUrl url of your remote data source * @property requestPathToMockPathRule generated map in MockFitConfig file * @property mockFilesPath path to access mock files * @property mockFitEnable master setting to enable or disable this interceptor * @property apiEnableMock if enabled it will proceed triggering mock response * @property apiIncludeIntoMock include specific endpoint into mock * @property apiExcludeFromMock exclude specific endpoint from being mocked * @property apiResponseLatency simulate latency while sending response to outer layer */ @Suppress("HardCodedStringLiteral") public class MockFitInterceptor constructor( private val bodyFactory: BodyFactory, private val logger: Logger, private val baseUrl: String, private val requestPathToMockPathRule: Array<MockPathRule>, private val mockFilesPath: String = "", private val mockFitEnable: Boolean = true, private val apiEnableMock: Boolean = true, private val apiIncludeIntoMock: Array<String> = arrayOf(), private val apiExcludeFromMock: Array<String> = arrayOf(), private val apiResponseLatency: Long = API_DEFAULT_LATENCY ) : Interceptor { @Suppress("DefaultLocale") @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() if (!mockFitEnable) { return chain.proceed(request) } val url = request.url().toString() val route = url.replace(baseUrl, "") // remove base url .removeQueryParams() .replaceUrlDynamicPath() // replace dynamic path (eg. 3,5,7) with {#} // for separate same route with different query and response val queries = request.url().query()?.split("&") ?: listOf() // example requestPath -> [DELETE] shops/{#}/social-accounts/{#} val requestMethod = request.method().toUpperCase() val apiMockPathRule = MockPathRule(request.method().toUpperCase(), route, "", arrayOf(), arrayOf()) var canProceedWithMock = apiEnableMock // can we use mock or proceed with network api // check if requestPath is included for (item in apiIncludeIntoMock) { val mockPath = item.replaceEndpointDynamicPath() if (mockPath == apiMockPathRule.route) { canProceedWithMock = true break } } // check if requestPath is excluded for (item in apiExcludeFromMock) { if (item.replaceEndpointDynamicPath() == apiMockPathRule.route) { canProceedWithMock = false break } } if (canProceedWithMock) { // same path but query is different val currentApiPathRule = requestPathToMockPathRule.lastOrNull { // remove values and just check query key presence to accept mock json val removeValueForExcludedQueries = it.excludeQueries.any { q -> q.contains("{#}")} val removeValueForIncludedQueries = it.includeQueries.any { q -> q.contains("{#}")} val eligibleQueries = queries.filter { query -> if (removeValueForExcludedQueries) !it.excludeQueries.contains(query.replaceUrlDynamicPath()) else !it.excludeQueries.contains(query) } it.method == apiMockPathRule.method && it.route == apiMockPathRule.route && it.includeQueries.all { query -> eligibleQueries.contains(query) if (removeValueForIncludedQueries) eligibleQueries.contains(query.replaceUrlDynamicPath()) else eligibleQueries.contains(query) } } val json = getMockJsonOrNull(currentApiPathRule) return json?.let { // json is found logger.log(TAG, "--> Mocking [$requestMethod] $url") val contentType = MediaType.parse(RESPONSE_MEDIA_TYPE) val responseBody = ResponseBody.create(contentType, it) Thread.sleep(apiResponseLatency) Response.Builder() .body(responseBody) .request(request) .message(RESPONSE_MESSAGE) .protocol(Protocol.HTTP_1_1) .code(RESPONSE_CODE) .build() } ?: run { // no json found, proceed request from remote data source chain.proceed(request) } } else { return chain.proceed(request) } } /** * read mock json or if exception occur's return null * * @param rule of api path * @return json in string object */ @Throws(IOException::class) private fun getMockJsonOrNull(rule: MockPathRule?): String? { if (rule == null) return null val eligible = requestPathToMockPathRule.firstOrNull() { it == rule } val fileName = eligible?.responseFile ?: return null val path = if (mockFilesPath.isEmpty()) fileName else "$mockFilesPath/$fileName" return bodyFactory.create(path) .bufferedReader() .use { it.readText() } } private companion object { private const val TAG = "MockFit" private const val API_DEFAULT_LATENCY = 150L private const val RESPONSE_MEDIA_TYPE = "application/json" private const val RESPONSE_MESSAGE = "OK" private const val RESPONSE_CODE = 200 } }
2
Kotlin
5
35
c5fa61ca551e22bae4900105e80ccfd854e94b4a
6,168
MockFit
Apache License 2.0
gmaven/src/main/kotlin/ru/rzn/gmyasoedov/gmaven/project/externalSystem/service/MavenAttachSourcesProvider.kt
grisha9
586,299,688
false
null
package ru.rzn.gmyasoedov.gmaven.project.providers import com.intellij.codeInsight.AttachSourcesProvider import com.intellij.codeInsight.AttachSourcesProvider.AttachSourcesAction import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.jarFinder.InternetAttachSourceProvider import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode import com.intellij.openapi.externalSystem.service.notification.ExternalSystemNotificationManager import com.intellij.openapi.externalSystem.service.notification.NotificationCategory import com.intellij.openapi.externalSystem.service.notification.NotificationData import com.intellij.openapi.externalSystem.service.notification.NotificationSource import com.intellij.openapi.externalSystem.task.TaskCallback import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.util.ActionCallback import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiFile import org.jetbrains.annotations.Nls import ru.rzn.gmyasoedov.gmaven.GMavenConstants.SYSTEM_ID import ru.rzn.gmyasoedov.gmaven.bundle.GBundle import ru.rzn.gmyasoedov.gmaven.util.getLocalRepoPath import ru.rzn.gmyasoedov.gmaven.utils.MavenArtifactUtil import ru.rzn.gmyasoedov.gmaven.utils.MavenLog import java.io.File import java.io.IOException import java.nio.file.Path import kotlin.io.path.exists class MavenAttachSourcesProvider : AttachSourcesProvider { override fun getActions( orderEntries: List<LibraryOrderEntry>, psiFile: PsiFile ): Collection<AttachSourcesAction> { if (getModules(orderEntries).isEmpty()) return listOf() return listOf(DownloadSourceAction(orderEntries, psiFile)) } } internal class DownloadSourceAction( private val orderEntries: List<LibraryOrderEntry>, private val psiFile: PsiFile ) : AttachSourcesAction { override fun getName(): String { return GBundle.message("gmaven.action.download.sources") } override fun getBusyText(): String { return GBundle.message("gmaven.action.download.sources.busy.text") } override fun perform(orderEntriesContainingFile: List<LibraryOrderEntry>): ActionCallback { val modulesMap = getModules(orderEntries) if (modulesMap.isEmpty()) { return ActionCallback.REJECTED } val (libraryOrderEntry, module) = modulesMap.entries.iterator().next() val libraryName = libraryOrderEntry.libraryName ?: return ActionCallback.REJECTED val artifactCoordinates = StringUtil.trimStart(libraryName, SYSTEM_ID.readableName + ": ") if (StringUtil.equals(libraryName, artifactCoordinates)) { return ActionCallback.REJECTED } val externalProjectPath = ExternalSystemApiUtil.getExternalRootProjectPath(module) ?: return ActionCallback.REJECTED return downloadSources(psiFile, artifactCoordinates, externalProjectPath) } private fun downloadSources( psiFile: PsiFile, artifactCoordinates: String, externalProjectPath: String ): ActionCallback { val split = artifactCoordinates.split(":") if (split.size < 3) return ActionCallback.REJECTED val project = psiFile.project val localRepoPath = getLocalRepoPath(project, externalProjectPath) ?: return ActionCallback.REJECTED val artifactNioPath = MavenArtifactUtil .getArtifactNioPath(Path.of(localRepoPath), split[0], split[1], split[2], "jar", "sources") if (artifactNioPath.exists()) { attachSources(artifactNioPath.toFile(), orderEntries) return ActionCallback.DONE } val settings = ExternalSystemTaskExecutionSettings() val env = HashMap<String, String>(settings.env) env["includeGroupIds"] = split[0] env["includeArtifactIds"] = split[1] settings.executionName = name settings.externalProjectPath = externalProjectPath settings.taskNames = listOf("dependency:sources") settings.env = env settings.externalSystemIdString = SYSTEM_ID.id val resultWrapper = ActionCallback() ExternalSystemUtil.runTask( settings, DefaultRunExecutor.EXECUTOR_ID, project, SYSTEM_ID, object : TaskCallback { override fun onSuccess() { val sourceJar: File try { sourceJar = artifactNioPath.toFile() if (!sourceJar.exists()) { resultWrapper.setRejected() errorNotification("file not found $sourceJar", project) return } } catch (e: IOException) { MavenLog.LOG.warn(e) resultWrapper.setRejected() errorNotification(e.localizedMessage, project) return } attachSources(sourceJar, orderEntries) resultWrapper.setDone() } override fun onFailure() { resultWrapper.setRejected() val message = GBundle.message( "gmaven.action.notifications.sources.download.failed.content", artifactCoordinates ) errorNotification(message, project) } }, ProgressExecutionMode.IN_BACKGROUND_ASYNC, true ) return resultWrapper } private fun errorNotification( message: @Nls String, project: Project ) { val title = GBundle.message("gmaven.action.notifications.sources.download.failed.title") val notification = NotificationData(title, message, NotificationCategory.ERROR, NotificationSource.TASK_EXECUTION) notification.isBalloonNotification = true ExternalSystemNotificationManager.getInstance(project) .showNotification(SYSTEM_ID, notification) } private fun attachSources(sourcesJar: File, orderEntries: List<LibraryOrderEntry>) { ApplicationManager.getApplication() .invokeLater { InternetAttachSourceProvider.attachSourceJar(sourcesJar, orderEntries.mapNotNull { it.library }) } } } private fun getModules(libraryOrderEntries: List<LibraryOrderEntry>): Map<LibraryOrderEntry, Module> { val result: MutableMap<LibraryOrderEntry, Module> = HashMap() for (entry in libraryOrderEntries) { val module = entry.ownerModule if (ExternalSystemApiUtil.isExternalSystemAwareModule(SYSTEM_ID, module)) { result[entry] = module } } return result }
5
null
0
12
d99dd67633a801b8fc09269def1564682a74ebcb
7,127
gmaven-plugin
Apache License 2.0
core/src/main/kotlin/pages/utils.kt
kamilok1965
351,889,705
false
{"Gradle Kotlin DSL": 49, "Java Properties": 1, "Markdown": 144, "Shell": 8, "Text": 2, "Ignore List": 5, "Batchfile": 8, "Git Attributes": 1, "XML": 11, "Kotlin": 671, "JAR Manifest": 1, "INI": 27, "Java": 34, "HTML": 43, "JSON with Comments": 1, "JSON": 2, "JavaScript": 13, "TSX": 8, "SCSS": 5, "SVG": 9, "CSS": 14, "YAML": 5, "Gradle": 4, "Maven POM": 1}
package org.jetbrains.dokka.pages import kotlin.reflect.KClass inline fun <reified T : ContentNode, R : ContentNode> R.mapTransform(noinline operation: (T) -> T): R = mapTransform(T::class, operation) @PublishedApi @Suppress("UNCHECKED_CAST") internal fun <T : ContentNode, R : ContentNode> R.mapTransform(type: KClass<T>, operation: (T) -> T): R { if (this::class == type) { return operation(this as T) as R } val new = when (this) { is ContentGroup -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentHeader -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentCodeBlock -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentCodeInline -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentTable -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentList -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentDivergentGroup -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentDivergentInstance -> this.copy( before = before?.mapTransform(type, operation), divergent = divergent.mapTransform(type, operation), after = after?.mapTransform(type, operation) ) is PlatformHintedContent -> this.copy(inner.mapTransform(type, operation)) else -> this } return new as R }
1
null
1
1
7c036dff0d40b1ea8bca8ee5aea5a211d4f090af
1,470
dokka
Apache License 2.0
core/src/main/kotlin/pages/utils.kt
kamilok1965
351,889,705
false
{"Gradle Kotlin DSL": 49, "Java Properties": 1, "Markdown": 144, "Shell": 8, "Text": 2, "Ignore List": 5, "Batchfile": 8, "Git Attributes": 1, "XML": 11, "Kotlin": 671, "JAR Manifest": 1, "INI": 27, "Java": 34, "HTML": 43, "JSON with Comments": 1, "JSON": 2, "JavaScript": 13, "TSX": 8, "SCSS": 5, "SVG": 9, "CSS": 14, "YAML": 5, "Gradle": 4, "Maven POM": 1}
package org.jetbrains.dokka.pages import kotlin.reflect.KClass inline fun <reified T : ContentNode, R : ContentNode> R.mapTransform(noinline operation: (T) -> T): R = mapTransform(T::class, operation) @PublishedApi @Suppress("UNCHECKED_CAST") internal fun <T : ContentNode, R : ContentNode> R.mapTransform(type: KClass<T>, operation: (T) -> T): R { if (this::class == type) { return operation(this as T) as R } val new = when (this) { is ContentGroup -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentHeader -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentCodeBlock -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentCodeInline -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentTable -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentList -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentDivergentGroup -> this.copy(children.map { it.mapTransform(type, operation) }) is ContentDivergentInstance -> this.copy( before = before?.mapTransform(type, operation), divergent = divergent.mapTransform(type, operation), after = after?.mapTransform(type, operation) ) is PlatformHintedContent -> this.copy(inner.mapTransform(type, operation)) else -> this } return new as R }
1
null
1
1
7c036dff0d40b1ea8bca8ee5aea5a211d4f090af
1,470
dokka
Apache License 2.0
app/src/main/java/com/airlift/codingchallenge/base/viewmodel/BaseViewModel.kt
syedtehrimabbas
410,497,630
false
{"Kotlin": 91296}
package com.airlift.codingchallenge.base.viewmodel import android.os.Bundle import androidx.annotation.CallSuper import androidx.databinding.Bindable import androidx.databinding.Observable import androidx.databinding.PropertyChangeRegistry import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.ViewModel /** * Created by <NAME> * */ abstract class BaseViewModel : ViewModel(), Observable, LifecycleObserver { @Transient private var mCallbacks: PropertyChangeRegistry? = null private var isFirstTimeUiCreate = true override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback) { synchronized(this) { if (mCallbacks == null) { mCallbacks = PropertyChangeRegistry() } } mCallbacks!!.add(callback) } override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback) { synchronized(this) { if (mCallbacks == null) { return } } mCallbacks!!.remove(callback) } /** * Notifies listeners that all properties of this instance have changed. */ fun notifyChange() { synchronized(this) { if (mCallbacks == null) { return } } mCallbacks!!.notifyCallbacks(this, 0, null) } /** * Notifies listeners that a specific property has changed. The getter for the property * that changes should be marked with [Bindable] to generate a field in * `BR` to be used as `fieldId`. * * @param fieldId The generated BR id for the Bindable field. */ fun notifyPropertyChanged(fieldId: Int) { synchronized(this) { if (mCallbacks == null) { return } } mCallbacks?.notifyCallbacks(this, fieldId, null) } /** * called after fragment / activity is created with input bundle arguments * * @param bundle argument data */ @CallSuper open fun onCreate(bundle: Bundle?) { if (isFirstTimeUiCreate) { onFirsTimeUiCreate(bundle) isFirstTimeUiCreate = false } } /** * Called when UI create for first time only, since activity / fragment might be rotated, * we don't need to re-init data, because view model will survive, data aren't destroyed * * @param bundle */ open fun onFirsTimeUiCreate(bundle: Bundle?) {} }
0
Kotlin
0
1
3e5fc8c66ebe873d2f421ba392c883df796c5bb3
2,509
airlift-codding-challenge
MIT License
samples/default-bff-server-web/src/main/kotlin/sample/config/DefaultSecurityConfig.kt
Snapwise
589,004,796
false
null
/* * * * Copyright 2022 the original author or authors. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * 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 sample.config import com.snapwise.security.bff.authorization.web.oauth2.BffOAuth2AuthenticationToken import org.slf4j.LoggerFactory import org.springframework.boot.web.servlet.FilterRegistrationBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.Ordered import org.springframework.security.config.annotation.ObjectPostProcessor import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter import org.springframework.security.web.SecurityFilterChain import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.UrlBasedCorsConfigurationSource import org.springframework.web.filter.CorsFilter import sample.authentication.SampleOAuth2AuthenticationSuccessHandler import sample.oauth2.login.authorization.SampleHttpSessionOAuth2AuthorizationRequestRepository import sample.oauth2.login.endpoint.SampleOAuth2AccessTokenResponseClient import sample.services.OAuth2UserService @EnableWebSecurity(debug = true) @Configuration(proxyBeanMethods = false) class DefaultSecurityConfig { private val logger = LoggerFactory.getLogger(javaClass) private fun createAuthenticationResult(authenticationResult: OAuth2LoginAuthenticationToken): BffOAuth2AuthenticationToken { logger.info("createAuthenticationResult -> $authenticationResult") return BffOAuth2AuthenticationToken( authenticationResult.principal, authenticationResult.authorities, authenticationResult.clientRegistration.registrationId ) } @Bean fun corsFilterRegistrationBean(): FilterRegistrationBean<*> { val source = UrlBasedCorsConfigurationSource() val publicConfig = CorsConfiguration() publicConfig.applyPermitDefaultValues() publicConfig.allowCredentials = false publicConfig.allowedOrigins = listOf("*") publicConfig.allowedHeaders = listOf("*") publicConfig.allowedMethods = listOf("*") publicConfig.exposedHeaders = listOf("content-length") publicConfig.maxAge = 3600L source.registerCorsConfiguration("/**", publicConfig) val bean: FilterRegistrationBean<*> = FilterRegistrationBean(CorsFilter(source)) bean.order = Ordered.HIGHEST_PRECEDENCE return bean } @Bean @Throws(Exception::class) fun defaultSecurityFilterChain( http: HttpSecurity, oAuth2UserService: OAuth2UserService, oAuth2AccessTokenResponseClient: SampleOAuth2AccessTokenResponseClient, httpSessionOAuth2AuthorizationRequestRepository: SampleHttpSessionOAuth2AuthorizationRequestRepository, oAuth2AuthenticationSuccessHandler: SampleOAuth2AuthenticationSuccessHandler, ): SecurityFilterChain { http.authorizeHttpRequests { authorize -> authorize .requestMatchers("/actuator/**").permitAll() .anyRequest().authenticated() }.oauth2Login { oAuth2LoginConfigurer -> oAuth2LoginConfigurer.authorizationEndpoint { it.authorizationRequestRepository(httpSessionOAuth2AuthorizationRequestRepository) } oAuth2LoginConfigurer.redirectionEndpoint { it.baseUri("/oauth2/callback/*") } oAuth2LoginConfigurer.userInfoEndpoint { it.userService(oAuth2UserService) } oAuth2LoginConfigurer.tokenEndpoint { it.accessTokenResponseClient(oAuth2AccessTokenResponseClient) } oAuth2LoginConfigurer.successHandler(oAuth2AuthenticationSuccessHandler) oAuth2LoginConfigurer.addObjectPostProcessor(object: ObjectPostProcessor<OAuth2LoginAuthenticationFilter> { override fun <O : OAuth2LoginAuthenticationFilter> postProcess(filter: O): O { filter.setAuthenticationResultConverter(::createAuthenticationResult) return filter } }) } return http.build() } }
0
Kotlin
0
0
ce96348ab150c25410b37340cbcd662b6759da6c
5,026
spring-bff-authorization
Apache License 2.0
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/solid/DollarSign.kt
DevSrSouza
311,134,756
false
null
package compose.icons.fontawesomeicons.solid import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Butt import androidx.compose.ui.graphics.StrokeJoin.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.fontawesomeicons.SolidGroup public val SolidGroup.DollarSign: ImageVector get() { if (_dollarSign != null) { return _dollarSign!! } _dollarSign = Builder(name = "DollarSign", defaultWidth = 288.0.dp, defaultHeight = 512.0.dp, viewportWidth = 288.0f, viewportHeight = 512.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(209.2f, 233.4f) lineToRelative(-108.0f, -31.6f) curveTo(88.7f, 198.2f, 80.0f, 186.5f, 80.0f, 173.5f) curveToRelative(0.0f, -16.3f, 13.2f, -29.5f, 29.5f, -29.5f) horizontalLineToRelative(66.3f) curveToRelative(12.2f, 0.0f, 24.2f, 3.7f, 34.2f, 10.5f) curveToRelative(6.1f, 4.1f, 14.3f, 3.1f, 19.5f, -2.0f) lineToRelative(34.8f, -34.0f) curveToRelative(7.1f, -6.9f, 6.1f, -18.4f, -1.8f, -24.5f) curveTo(238.0f, 74.8f, 207.4f, 64.1f, 176.0f, 64.0f) verticalLineTo(16.0f) curveToRelative(0.0f, -8.8f, -7.2f, -16.0f, -16.0f, -16.0f) horizontalLineToRelative(-32.0f) curveToRelative(-8.8f, 0.0f, -16.0f, 7.2f, -16.0f, 16.0f) verticalLineToRelative(48.0f) horizontalLineToRelative(-2.5f) curveTo(45.8f, 64.0f, -5.4f, 118.7f, 0.5f, 183.6f) curveToRelative(4.2f, 46.1f, 39.4f, 83.6f, 83.8f, 96.6f) lineToRelative(102.5f, 30.0f) curveToRelative(12.5f, 3.7f, 21.2f, 15.3f, 21.2f, 28.3f) curveToRelative(0.0f, 16.3f, -13.2f, 29.5f, -29.5f, 29.5f) horizontalLineToRelative(-66.3f) curveTo(100.0f, 368.0f, 88.0f, 364.3f, 78.0f, 357.5f) curveToRelative(-6.1f, -4.1f, -14.3f, -3.1f, -19.5f, 2.0f) lineToRelative(-34.8f, 34.0f) curveToRelative(-7.1f, 6.9f, -6.1f, 18.4f, 1.8f, 24.5f) curveToRelative(24.5f, 19.2f, 55.1f, 29.9f, 86.5f, 30.0f) verticalLineToRelative(48.0f) curveToRelative(0.0f, 8.8f, 7.2f, 16.0f, 16.0f, 16.0f) horizontalLineToRelative(32.0f) curveToRelative(8.8f, 0.0f, 16.0f, -7.2f, 16.0f, -16.0f) verticalLineToRelative(-48.2f) curveToRelative(46.6f, -0.9f, 90.3f, -28.6f, 105.7f, -72.7f) curveToRelative(21.5f, -61.6f, -14.6f, -124.8f, -72.5f, -141.7f) close() } } .build() return _dollarSign!! } private var _dollarSign: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
3,340
compose-icons
MIT License
bson/src/main/kotlin/BsonDocumentLike.kt
cufyorg
502,485,629
false
null
/* * Copyright 2022-2023 cufy.org and meemer.com * * 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.cufy.bson import kotlinx.datetime.Instant import kotlin.reflect.KCallable /* ============= ------------------ ============= */ /** * A map containing only items of type [BsonElement]. * * @since 2.0.0 */ typealias BsonDocumentLike = Map<String, BsonElement> /** * A mutable map containing only items of type [BsonElement]. * * TODO: change to MutableMap<String, BsonElement> when context receivers are stable. * * @since 2.0.0 */ typealias MutableBsonDocumentLike = IMutableBsonDocumentLike /** * A block of code building a bson document. * * @since 2.0.0 */ typealias BsonDocumentBlock = MutableBsonDocumentLike.() -> Unit /* ============= ------------------ ============= */ /** * Construct a new mutable bson map from this map. * * This function will be obsolete once kotlin * context receivers is stable. * * @see toMutableMap * @since 2.0.0 */ fun Map<String, BsonElement>.toMutableBsonDocument(): MutableBsonDocumentLike { return toMutableMap().asMutableBsonDocument() } /** * Obtain a mutable bson map backed by this map. * * This function will be obsolete once kotlin * context receivers is stable. * * @since 2.0.0 */ fun MutableMap<String, BsonElement>.asMutableBsonDocument(): MutableBsonDocumentLike { val content = this return object : MutableBsonDocumentLike, MutableMap<String, BsonElement> by content { override fun equals(other: Any?) = content == other override fun hashCode() = content.hashCode() override fun toString() = content.entries.joinToString(",", "{", "}") { """"${it.key}":${it.value}""" } } } /* ============= ------------------ ============= */ /** * Return an empty new [MutableBsonDocumentLike]. * * This function will be obsolete once kotlin * context receivers is stable. * * @see mutableMapOf * @since 2.0.0 */ fun mutableBsonDocumentOf(): MutableBsonDocumentLike { return mutableMapOf<String, BsonElement>() .asMutableBsonDocument() } /** * Returns a new [MutableBsonDocumentLike] with the given pairs. * * This function will be obsolete once kotlin * context receivers is stable. * * @see mutableMapOf * @since 2.0.0 */ fun mutableBsonDocumentOf(vararg pairs: Pair<String, BsonElement>): MutableBsonDocumentLike { return mutableMapOf(*pairs) .asMutableBsonDocument() } /* ============= ------------------ ============= */ /** * An interface allowing custom receivers for * [by][IMutableBsonDocumentLike.by]. * * This interface will be useless after context * receivers is released for production. * This interface will be removed gradually after * context receivers is released for production. * * @author LSafer * @since 2.0.0 */ interface MutableBsonMapField<T> { /** * The name of the field. */ val name: String /** * Encode the given [value] to a bson value. */ fun encode(value: T): BsonElement? } /** * A builder building a [BsonDocument]. * * This interface will be removed and its functions will be * extensions of [MutableBsonDocumentLike] once kotlin context * receivers is stable. * * @author LSafer * @since 2.0.0 */ @DeprecatedWithContextParameters interface IMutableBsonDocumentLike : BsonDocumentLike, MutableMap<String, BsonElement> { /* ============= ------------------ ============= */ /** * Static (pure) utility function to prettify * creating arrays within the dsl. * * Usage: * ``` * BsonDocument { * "name" by array { * by(100L) * by("item") * /* ... */ * } * } * ``` * * @return an array built with the given [block]. * @since 2.0.0 */ @BsonMarker2 fun array(block: BsonArrayBlock) = BsonArray(block) /** * Static (pure) utility function to prettify * creating arrays within the dsl. * * Usage: * ``` * BsonDocument { * "name" by array( * 100L.bson, * "item".bson, * /* ... */ * ) * } * ``` * * @return an array with the given [elements]. * @since 2.0.0 */ @BsonMarker2 fun array(vararg elements: BsonElement) = BsonArray(*elements) /* ============= ------------------ ============= */ /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. */ @BsonMarker2 infix fun String.by(value: BsonElement?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. */ @BsonMarker2 infix fun KCallable<*>.by(value: BsonElement?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: BsonElement?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. */ @BsonMarker2 infix fun String.by(value: BsonDocument?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. */ @BsonMarker2 infix fun KCallable<*>.by(value: BsonDocument?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: BsonDocument?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. */ @BsonMarker2 infix fun String.by(value: BsonArray?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. */ @BsonMarker2 infix fun KCallable<*>.by(value: BsonArray?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: BsonArray?) { name by value } /* ============= ------------------ ============= */ /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDocument]. */ @BsonMarker2 infix fun String.by(value: Map<String, BsonElement>?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.toBsonDocument() } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDocument]. */ @BsonMarker2 infix fun KCallable<*>.by(value: Map<String, BsonElement>?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDocument]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: Map<String, BsonElement>?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonArray]. */ @BsonMarker2 infix fun String.by(value: List<BsonElement>?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.toBsonArray() } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonArray]. */ @BsonMarker2 infix fun KCallable<*>.by(value: List<BsonElement>?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonArray]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: List<BsonElement>?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonString]. */ @BsonMarker2 infix fun String.by(value: String?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.bson } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonString]. */ @BsonMarker2 infix fun KCallable<*>.by(value: String?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonString]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: String?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonObjectId]. */ @BsonMarker2 infix fun String.by(value: ObjectId?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.bson } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonObjectId]. */ @BsonMarker2 infix fun KCallable<*>.by(value: ObjectId?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonObjectId]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: ObjectId?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped using [ID.bson]. * */ @BsonMarker2 infix fun String.by(value: AnyID?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.bson } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped using [ID.bson]. */ @BsonMarker2 infix fun KCallable<*>.by(value: AnyID?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped using [ID.bson]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: AnyID?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped using [BsonArray] and [ID.bson]. */ @Suppress("INAPPLICABLE_JVM_NAME") @JvmName("byIDList") @BsonMarker2 infix fun String.by(value: List<AnyID>?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.map { it.bson }.toBsonArray() } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped using [BsonArray] and [ID.bson]. */ @Suppress("INAPPLICABLE_JVM_NAME") @JvmName("byIDList") @BsonMarker2 infix fun KCallable<*>.by(value: List<AnyID>?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped using [BsonArray] and [ID.bson]. */ @Suppress("INAPPLICABLE_JVM_NAME") @JvmName("byIDList") @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: List<AnyID>?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDecimal128]. */ @BsonMarker2 infix fun String.by(value: Decimal128?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.bson } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDecimal128]. */ @BsonMarker2 infix fun KCallable<*>.by(value: Decimal128?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDecimal128]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: Decimal128?) { name by value } // /** // * Set the field with the name [this] to the given [value]. // * // * If [value] is null then [BsonNull] will be set instead. // * // * The given [value] will be wrapped with [BsonDecimal128]. // */ // @BsonConstructorMarker // infix fun String.by(value: BigDecimal?) { // value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } // this@IMutableBsonDocumentLike[this] = value.bson // } // // /** // * Set the field with the name [this] to the given [value]. // * // * If [value] is null then [BsonNull] will be set instead. // * // * The given [value] will be wrapped with [BsonDecimal128]. // */ // @BsonConstructorMarker // infix fun KCallable<*>.by(value: BigDecimal?) { // name by value // } // // /** // * Set the field with the name [this] to the given [value]. // * // * If [value] is null then [BsonNull] will be set instead. // * // * The given [value] will be wrapped with [BsonDecimal128]. // */ // @BsonConstructorMarker // infix fun MutableBsonMapField<*>.byname(value: BigDecimal?) { // name by value // } // /** // * Set the field with the name [this] to the given [value]. // * // * If [value] is null then [BsonNull] will be set instead. // * // * The given [value] will be wrapped with [BsonDateTime]. // */ // @BsonConstructorMarker // infix fun String.by(value: Date?) { // value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } // this@IMutableBsonDocumentLike[this] = value.bson // } // // /** // * Set the field with the name [this] to the given [value]. // * // * If [value] is null then [BsonNull] will be set instead. // * // * The given [value] will be wrapped with [BsonDateTime]. // */ // @BsonConstructorMarker // infix fun KCallable<*>.by(value: Date?) { // name by value // } // // /** // * Set the field with the name [this] to the given [value]. // * // * If [value] is null then [BsonNull] will be set instead. // * // * The given [value] will be wrapped with [BsonDateTime]. // */ // @BsonConstructorMarker // infix fun MutableBsonMapField<*>.byname(value: Date?) { // name by value // } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDateTime]. */ @BsonMarker2 infix fun String.by(value: Instant?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.bson } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDateTime]. */ @BsonMarker2 infix fun KCallable<*>.by(value: Instant?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDateTime]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: Instant?) { name by value } /* ============= ------------------ ============= */ /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonBoolean]. */ @BsonMarker2 infix fun String.by(value: Boolean?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.bson } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonBoolean]. */ @BsonMarker2 infix fun KCallable<*>.by(value: Boolean?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonBoolean]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: Boolean?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonInt32]. */ @BsonMarker2 infix fun String.by(value: Int?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.bson } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonInt32]. */ @BsonMarker2 infix fun KCallable<*>.by(value: Int?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonInt32]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: Int?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonInt64]. */ @BsonMarker2 infix fun String.by(value: Long?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.bson } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonInt64]. */ @BsonMarker2 infix fun KCallable<*>.by(value: Long?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonInt64]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: Long?) { name by value } // /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDouble]. */ @BsonMarker2 infix fun String.by(value: Double?) { value ?: return run { this@IMutableBsonDocumentLike[this] = null.bson } this@IMutableBsonDocumentLike[this] = value.bson } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDouble]. */ @BsonMarker2 infix fun KCallable<*>.by(value: Double?) { name by value } /** * Set the field with the name [this] to the given [value]. * * If [value] is null then [BsonNull] will be set instead. * * The given [value] will be wrapped with [BsonDouble]. */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(value: Double?) { name by value } /* ============= ------------------ ============= */ /** * Set the field with the name [this] to the value from invoking the given [block] */ @BsonMarker2 infix fun String.by(block: BsonDocumentBlock) { this@IMutableBsonDocumentLike[this] = BsonDocument(block) } /** * Set the field with the name [this] to the value from invoking the given [block] */ @BsonMarker2 infix fun KCallable<*>.by(block: BsonDocumentBlock) { name by block } /** * Set the field with the name [this] to the value from invoking the given [block] */ @BsonMarker2 infix fun MutableBsonMapField<*>.byname(block: BsonDocumentBlock) { name by block } /* ============= ------------------ ============= */ /** * Set the field represented by the [receiver][this] to the given [value]. */ @BsonMarker2 infix fun <T> MutableBsonMapField<T>.by(value: T) { this@IMutableBsonDocumentLike[name] = encode(value) ?: null.bson } /* ============= ------------------ ============= */ /** * Put all the mappings in the given [map]. */ @BsonMarker2 fun byAll(map: Map<String, BsonElement>) { this@IMutableBsonDocumentLike += map } /* ============= ------------------ ============= */ } /* ============= ------------------ ============= */
3
null
1
4
8882b0225b2ffba13ffd1216dd7a4d2c7450df01
24,598
monkt
Apache License 2.0
multisrc/overrides/mangathemesia/sushiscan/src/SushiScan.kt
Ashuyomi
604,291,847
false
null
package eu.kanade.tachiyomi.extension.fr.sushiscan import eu.kanade.tachiyomi.multisrc.mangathemesia.MangaThemesia import eu.kanade.tachiyomi.source.model.SManga import java.text.SimpleDateFormat import java.util.Locale class SushiScan : MangaThemesia("Sushi-Scan", "https://sushiscan.net", "fr", dateFormat = SimpleDateFormat("MMMM dd, yyyy", Locale.FRENCH)) { override val altNamePrefix = "Nom alternatif : " override val seriesAuthorSelector = ".infotable tr:contains(Auteur) td:last-child" override val seriesStatusSelector = ".infotable tr:contains(Statut) td:last-child" override fun String?.parseStatus(): Int = when { this == null -> SManga.UNKNOWN this.contains("En Cours", ignoreCase = true) -> SManga.ONGOING this.contains("Terminé", ignoreCase = true) -> SManga.COMPLETED else -> SManga.UNKNOWN } }
1
Kotlin
0
1
976bd8290e42196b6ae27df538666e2bd7e91a56
865
Ashuyomi-extensions
Apache License 2.0
src/main/kotlin/com/yg/gqlwfdl/services/DataLoaderPrimerEntityCreationListener.kt
roadSurfer
141,256,296
true
{"Java Properties": 3, "Gradle": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 42, "Java": 87, "GraphQL": 1, "XML": 1, "HTML": 1}
package com.yg.gqlwfdl.services import com.yg.gqlwfdl.RequestContext import com.yg.gqlwfdl.dataaccess.EntityCreationListener import com.yg.gqlwfdl.dataloaders.DataLoaderType /** * A listener which hears when entities are created (typically after being queried for, from the database). Caches the * entities into their relevant data loaders to make them available to subsequent parts of the same GraphQL request. */ class DataLoaderPrimerEntityCreationListener(private val requestContext: RequestContext) : EntityCreationListener { override fun onEntityCreated(entity: Entity<out Any>) { cachers[entity.javaClass]?.cache(requestContext, entity) } } /** * An object responsible for caching [TEntity] objects into a data loader of the specified [dataLoaderType]. * * @property dataLoaderType The type of data loader which this object caches entities into. * @property entityClass The [Class] of [TEntity]. */ private class EntityCacher<TId, TEntity : Entity<out TId>>( private val dataLoaderType: DataLoaderType, val entityClass: Class<TEntity>) { /** * Caches the passed in entity into the [requestContext]'s data loader. */ fun cache(requestContext: RequestContext, entity: Any) { // Can safely cast here as this private function is only called from one single place, where type checking has // implicitly already been done. @Suppress("UNCHECKED_CAST") requestContext.dataLoader<TId, TEntity>(dataLoaderType).prime(entity as TEntity) } } /** * A map of all the known entity cachers. Keyed on the class of the [Entity] being cached, where the value is the * [EntityCacher] itself. When requesting an object from this map, if a non-null value is returned for a given class, * then the returned value can be safely cast to that class. */ private val cachers: Map<Class<out Entity<*>>, EntityCacher<out Any, *>> = listOf( EntityCacher(DataLoaderType.CUSTOMER, Customer::class.java), EntityCacher(DataLoaderType.COMPANY, Company::class.java), EntityCacher(DataLoaderType.COMPANY_PARTNERSHIP, CompanyPartnership::class.java), EntityCacher(DataLoaderType.PRICING_DETAILS, PricingDetails::class.java) ).map { it.entityClass to it }.toMap()
0
Java
0
0
80cddae002f6bd7130a73e9352beb4d7fcad79ba
2,266
graphql-webflux-dataloader
MIT License
app/src/main/java/com/rogertalk/roger/ui/screens/AttachmentsActivity.kt
rogertalk
207,123,525
false
{"Gradle": 4, "Java Properties": 3, "Markdown": 7, "Text": 6, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "XML": 157, "Proguard": 2, "Kotlin": 408, "Java": 2, "JSON": 1, "Makefile": 2, "C": 105, "C++": 11}
package com.rogertalk.roger.ui.screens import android.Manifest import android.animation.AnimatorSet import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.text.SpannableString import android.text.style.UnderlineSpan import android.view.WindowManager import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.GlideDrawable import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.karumi.dexter.Dexter import com.karumi.dexter.PermissionToken import com.karumi.dexter.listener.PermissionDeniedResponse import com.karumi.dexter.listener.PermissionGrantedResponse import com.karumi.dexter.listener.PermissionRequest import com.karumi.dexter.listener.single.DialogOnDeniedPermissionListener import com.karumi.dexter.listener.single.PermissionListener import com.rogertalk.kotlinjubatus.beGone import com.rogertalk.kotlinjubatus.makeVisible import com.rogertalk.roger.R import com.rogertalk.roger.event.broadcasts.audio.AudioAmplitudeEvent import com.rogertalk.roger.event.broadcasts.audio.AudioCommandEvent import com.rogertalk.roger.event.broadcasts.audio.AudioServiceStateEvent import com.rogertalk.roger.manager.EventTrackingManager import com.rogertalk.roger.manager.EventTrackingManager.RecordingReason.TAP_MIC_ATTACHMENTS import com.rogertalk.roger.manager.GlobalManager import com.rogertalk.roger.manager.StreamManager import com.rogertalk.roger.manager.audio.PlaybackStateManager import com.rogertalk.roger.models.data.AttachmentType import com.rogertalk.roger.models.data.AudioCommand import com.rogertalk.roger.models.data.StreamStatus import com.rogertalk.roger.models.data.VisualizerType import com.rogertalk.roger.models.json.Stream import com.rogertalk.roger.network.request.AttachmentLinkRequest import com.rogertalk.roger.network.request.StreamStatusRequest import com.rogertalk.roger.repo.PrefRepo import com.rogertalk.roger.repo.StreamCacheRepo import com.rogertalk.roger.ui.cta.doneToast import com.rogertalk.roger.ui.dialog.AttachmentDialogs import com.rogertalk.roger.ui.screens.base.EventAppCompatActivity import com.rogertalk.roger.ui.screens.behaviors.WhiteToolbar import com.rogertalk.roger.utils.android.ShareUtils import com.rogertalk.roger.utils.constant.AttachmentConstants.ATTACHMENT_PHOTO_HEIGHT import com.rogertalk.roger.utils.constant.AttachmentConstants.ATTACHMENT_PHOTO_WIDTH import com.rogertalk.roger.utils.constant.MaterialIcon import com.rogertalk.roger.utils.constant.NO_ID import com.rogertalk.roger.utils.extensions.hasWriteToExternalStoragePermission import com.rogertalk.roger.utils.extensions.postEvent import com.rogertalk.roger.utils.extensions.stringResource import com.rogertalk.roger.utils.log.logDebug import com.rogertalk.roger.utils.log.logError import com.theartofdev.edmodo.cropper.CropImage import kotlinx.android.synthetic.main.attachments_screen.* import kotlinx.android.synthetic.main.transparent_toolbar.* import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode.MAIN import org.jetbrains.anko.toast import kotlin.LazyThreadSafetyMode.NONE class AttachmentsActivity : EventAppCompatActivity(true), WhiteToolbar, RequestListener<String, GlideDrawable>, PermissionListener { override val _toolbar: Toolbar get() = toolbar override val _context: AppCompatActivity get() = this override val _toolbarRightActionAnimation: AnimatorSet? get() = null companion object { private val EXTRA_STREAM_ID = "streamId" private val EXTRA_CAME_FROM_NOTIFICATION = "cameFromNotification" fun start(context: Context, streamId: Long, cameFromNotification: Boolean = false): Intent { val startIntent = Intent(context, AttachmentsActivity::class.java) startIntent.putExtra(EXTRA_STREAM_ID, streamId) startIntent.putExtra(EXTRA_CAME_FROM_NOTIFICATION, cameFromNotification) return startIntent } } private val streamId: Long by lazy(NONE) { intent.getLongExtra(EXTRA_STREAM_ID, NO_ID) } private val cameFromNotification: Boolean by lazy(NONE) { intent.getBooleanExtra(EXTRA_STREAM_ID, false) } // Playback and Recording Audio Visualizer values private var audioLevel = 0.0 private var audioLevelPrevious = 0.0 // // OVERRIDE METHODS // override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (streamId == NO_ID) { logError { "StreamID was wrong!" } finish() return } if (StreamManager.selectedStreamId != streamId) { // Pre-select new stream if possible val stream = StreamCacheRepo.getStream(streamId) if (stream == null) { logError { "Stream is different and cannot be found in cache!" } finish() return } // Select this Stream as the new one in focus StreamManager.selectedStreamId = streamId } setContentView(R.layout.attachments_screen) setupUI() // Don't show CTA on empty attachments anymore PrefRepo.didSeeAttachmentsScreen = true // Mark this attachment as seen GlobalManager.addToSeenAttachments(streamId) // Track flow initialized by notification if (cameFromNotification) { EventTrackingManager.notificationPressed(EventTrackingManager.NotificationType.ATTACHMENTS) } } override fun onResume() { super.onResume() updateAudioState() } override fun onException(e: Exception?, model: String?, target: Target<GlideDrawable>?, isFirstResource: Boolean): Boolean { toast(R.string.ob_failed_request) return false } override fun onResourceReady(resource: GlideDrawable?, model: String?, target: Target<GlideDrawable>?, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean { loadingImageProgress.beGone(true) return false } override fun onPermissionGranted(response: PermissionGrantedResponse?) { val permissionName = response?.permissionName ?: "" logDebug { "Enabled permission: $permissionName" } if (hasWriteToExternalStoragePermission()) { // Just got the permission, show dialog now setAttachmentPhoto() } } override fun onPermissionRationaleShouldBeShown(permission: PermissionRequest?, token: PermissionToken?) { token?.continuePermissionRequest() } override fun onPermissionDenied(response: PermissionDeniedResponse?) { val permissionName = response?.permissionName ?: "" val permanentlyDenied = response?.isPermanentlyDenied ?: true logDebug { "Denied permission: $permissionName, permanently: $permanentlyDenied" } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == AppCompatActivity.RESULT_OK) { val imageUri = CropImage.getPickImageResultUri(this, data) imageUri?.let { startActivity(ImageCropActivity.startToShare(this, it, streamId)) // End this activity finish() } } } // // PUBLIC METHODS // fun setAttachmentPhoto() { if (hasWriteToExternalStoragePermission()) { choosePhoto() } else { // Request needed permission first requestStoragePermissions() } } fun setAttachmentLink(stream: Stream, clipboardLink: String) { // Track link attachment sent EventTrackingManager.setAttachmentLink() AttachmentLinkRequest(stream.id, clipboardLink).enqueueRequest() doneToast() finish() } // // PRIVATE METHODS // fun scaleRecordingVisualizer(scaleLevel: Float) { recordingVisualizer.scaleX = scaleLevel recordingVisualizer.scaleY = scaleLevel } private fun resetAudioLevel() { audioLevelPrevious = 0.0 audioLevel = 0.0 recordingVisualizer.beGone() } private fun redrawVisualizer(visualizerType: VisualizerType) { if (visualizerType == visualizerType) { val recordingLevel = { // Smooth out changes in the audio level if (audioLevel < audioLevelPrevious) { (audioLevelPrevious * 5 + audioLevel) / 6 } else { audioLevel } }() audioLevelPrevious = recordingLevel val visualizerScale = (1 + recordingLevel / Math.sqrt(recordingLevel + 0.01f)).toFloat() scaleRecordingVisualizer(visualizerScale) } } private fun startRecordingAction() { val stream = StreamManager.selectedStream ?: return // Keep screen on while recording window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) // Reset visualizer recordingVisualizer.makeVisible() recordingVisualizer.scaleX = 1f recordingVisualizer.scaleY = 1f EventTrackingManager.recordingStart(TAP_MIC_ATTACHMENTS) postEvent(AudioCommandEvent(AudioCommand.RECORD)) } private fun choosePhoto() { CropImage.startPickImageActivity(this) } private fun requestStoragePermissions() { val dialogPermissionListener = DialogOnDeniedPermissionListener.Builder .withContext(this) .withTitle(R.string.perm_storage_title) .withMessage(R.string.perm_storage_description) .withButtonText(android.R.string.ok) .withIcon(R.mipmap.ic_launcher) .build() if (!Dexter.isRequestOngoing()) { Dexter.checkPermission(dialogPermissionListener, Manifest.permission.WRITE_EXTERNAL_STORAGE) } } private fun setupUI() { val stream = StreamCacheRepo.getStream(streamId) if (stream == null) { logError { "" } finish() return } // Toolbar setupToolbar("") rightTopButton.beGone() toolbarHasBackAction { handleBackPressed() } displayAttachment(stream) // Button actions replaceButton.setOnClickListener { newAttachmentPressed() } recordingButton.setToggleAction { recordingButtonPressed() } } private fun displayAttachment(stream: Stream) { val attachmentLink = stream.attachmentLink if (attachmentLink == null) { // There is no attachment yet, hide recording button recordingButton.beGone() // And display send attachment button replaceButton.makeVisible() return } // Hide main UI button replaceButton.beGone() // Show replace action at top setRightActionIcon(MaterialIcon.ATTACH_FILE) setRightActionContentDescription(R.string.attachments_replace) rightTopLabel.text = R.string.attachments_replace.stringResource() rightTopLabel.makeVisible(true) rightTopButton.makeVisible(true) rightTopLabel.setOnClickListener { newAttachmentPressed() } rightTopButton.setOnClickListener { newAttachmentPressed() } StreamStatusRequest(stream.id, StreamStatus.VIEWING_ATTACHMENT).enqueueRequest() when (stream.attachmentType) { AttachmentType.IMAGE -> { EventTrackingManager.seenAttachment(true) renderImage(attachmentLink) } AttachmentType.LINK -> { EventTrackingManager.seenAttachment(false) renderLink(attachmentLink) } } } private fun recordingButtonPressed() { if (PlaybackStateManager.recording) { postEvent(AudioCommandEvent(AudioCommand.STOP_RECORDING, recordingStopReason = TAP_MIC_ATTACHMENTS)) } else { PlaybackStateManager.currentStream = StreamCacheRepo.getStream(streamId) startRecordingAction() } } private fun newAttachmentPressed() { val stream = StreamCacheRepo.getStream(streamId) ?: return AttachmentDialogs.attachmentOptions(this, stream) } private fun renderImage(imageURL: String) { emptyMessageContainer.beGone() loadingImageProgress.makeVisible(true) Glide.with(this) .load(imageURL) .dontTransform() .override(ATTACHMENT_PHOTO_WIDTH, ATTACHMENT_PHOTO_HEIGHT) .listener(this) .into(attachmentImage) } private fun renderLink(linkURL: String) { // Display link and icon val content = SpannableString(linkURL) content.setSpan(UnderlineSpan(), 0, content.length, 0) descriptionLabel.text = content attachmentIcon.text = MaterialIcon.LINK.text // Make it clickable descriptionLabel.setOnClickListener { ShareUtils.openExternalLink(this, linkURL) } } private fun handleBackPressed() { finish() } private fun updateAudioState() { if (!PlaybackStateManager.recording) { recordingButton.displayAsNotRecording() resetAudioLevel() } } // // EVENT METHODS // @Subscribe(threadMode = MAIN) fun onAudioServiceState(event: AudioServiceStateEvent) { logDebug { "AudioEvent. new: ${event.newState}, old: ${event.oldState}" } updateAudioState() } @Subscribe(threadMode = MAIN) fun onAudioAmplitude(event: AudioAmplitudeEvent) { // Convert into our own leveling metric audioLevel = Math.pow(10.0, event.amplitude / 40) redrawVisualizer(event.visualizerType) } }
0
C
0
1
55c9922947311d9d8a1e930463b9ac2a1332e006
14,394
roger-android
MIT License
meteor-viewmodel/src/commonMain/kotlin/io/spherelabs/meteorviewmodel/core/AtomicExtension.kt
getspherelabs
646,328,849
false
{"Kotlin": 68656}
package io.spherelabs.meteorviewmodel.core public inline val Boolean.toInt: Int get() = if (this) 1 else 0
13
Kotlin
3
41
c2406b12c08ab20485130d00b82ef181ebd0a890
108
meteor-kmp
Apache License 2.0
metronome-android/app/src/test/java/com/jedparsons/metronome/storage/FakeRhythmStore.kt
jedp
496,303,738
false
{"Kotlin": 38641, "Swift": 17862, "C++": 3314, "CMake": 1613}
package com.jedparsons.metronome.storage import com.jedparsons.metronome.model.RhythmModel import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext class FakeRhythmStore( private val context: CoroutineContext ) : RhythmStore { private var rhythmModel: RhythmModel = RhythmModel() fun setNextData(rhythmModel: RhythmModel) { this.rhythmModel = rhythmModel } override suspend fun save(rhythmModel: RhythmModel) { withContext(context) { this@FakeRhythmStore.rhythmModel = rhythmModel } } override suspend fun load(): RhythmModel { return withContext(context) { rhythmModel.copy() } } }
0
Kotlin
0
0
7def45961f3597bb55584f67043b69ea8bc798e6
660
asymmetronome
MIT License
app/src/main/java/com/nemo/tmdb/view/MainActivity.kt
zipecki
268,357,859
false
null
package com.nemo.tmdb.view import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.os.Bundle import android.support.v4.app.FragmentTransaction import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.AdapterView.OnItemClickListener import android.widget.ArrayAdapter import android.widget.ListView import com.jakewharton.rxbinding2.widget.RxTextView import com.nemo.tmdb.R import com.nemo.tmdb.model.MoviesResponse import com.nemo.tmdb.network.ApiClient import com.nemo.tmdb.utils.Utils import com.nemo.tmdb.viewmodel.ActivityViewModel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.observers.DisposableObserver import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_main.* import java.util.* import java.util.concurrent.TimeUnit class MainActivity : AppCompatActivity() { var arrayAdapter: ArrayAdapter<String>? = null var mainViewModel : ActivityViewModel? = null; var moviesList : List<MoviesResponse.Movie>? = null private val mCompositeDisposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mainViewModel = ViewModelProviders.of(this).get(ActivityViewModel::class.java) mainViewModel?.retrieveAllFavsFromDb() arrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1) val listView = findViewById<View>(R.id.search_results) as ListView listView.adapter = arrayAdapter listView.onItemClickListener = OnItemClickListener { parent, view, position, id -> Log.d("Activity", "Lista click, pos = "+position.toString()) var movieSel : MoviesResponse.Movie = moviesList!!.get(position) mainViewModel!!.setCurrMovie(movieSel) goToDetails() } supportFragmentManager .beginTransaction() .add(R.id.fragment, MoviesListFragment(), "movieList") .commit() RxTextView.textChanges(search_text) .doOnNext { text: CharSequence? -> clearSearchResults() } .filter { text: CharSequence -> text.length >= 3 } .debounce(300, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe { text: CharSequence? -> updateSearchResults(text!!) } search_text.setVisibility(View.VISIBLE) search_results.setVisibility(View.GONE) } fun clearSearchResults() { arrayAdapter?.clear() } open fun updateSearchResults(text: CharSequence) { search_results.setVisibility(View.VISIBLE) mCompositeDisposable.add(ApiClient.create().searchMovies(Utils.getApiKey(), text.toString()) .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribeWith(object : DisposableObserver<MoviesResponse.Movies>() { override fun onNext(t: MoviesResponse.Movies) { moviesList = t.results val list: MutableList<String> = ArrayList() if (moviesList != null) { for (movie in moviesList!!) { list.add(movie.title!!) } arrayAdapter?.clear() arrayAdapter?.addAll(list) } } override fun onError(e: Throwable) { Log.e("MainActivity", e.message) } override fun onComplete() { Log.d("MainActivity", "Search completed") } })) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_settings -> goToDetails() else -> super.onOptionsItemSelected(item) } return true } override fun onBackPressed() { val movieFrag: Movie2Fragment? = getSupportFragmentManager().findFragmentByTag("movieDetail") as Movie2Fragment? if (movieFrag != null && movieFrag.isVisible()) { getSupportFragmentManager() .beginTransaction() .replace(R.id.fragment, MoviesListFragment(), "movieList") .setTransition(FragmentTransaction.TRANSIT_ENTER_MASK) .commit() search_text.setVisibility(View.VISIBLE) search_results.setVisibility(View.GONE) } else { super.onBackPressed() } } fun getViewModel() : ActivityViewModel { return mainViewModel!! } fun goToDetails() { search_text.setVisibility(View.GONE) search_results.setVisibility(View.GONE) getSupportFragmentManager() .beginTransaction() .replace(R.id.fragment, Movie2Fragment(), "movieDetail") .setTransition(FragmentTransaction.TRANSIT_ENTER_MASK) .commit() val trans: FragmentTransaction = getSupportFragmentManager().beginTransaction() val listFrag: MoviesListFragment = getSupportFragmentManager().findFragmentByTag("movieList") as MoviesListFragment trans.remove(listFrag).commit() search_text.setVisibility(View.GONE) search_results.setVisibility(View.GONE) // hide keyboard val inputMethodManager = (this as Context).getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0) } }
0
Kotlin
0
0
563b34017fbe2517d39c669db855ace3f518de15
6,121
TMDB_test
Apache License 2.0
src/main/kotlin/com/dannbrown/astrosync/AstroSyncMod.kt
danbrown
815,159,851
false
{"Kotlin": 20041, "Java": 822}
package com.dannbrown.astrosync import com.dannbrown.astrosync.core.FileUtils import com.dannbrown.astrosync.core.NetworkUtils import com.dannbrown.astrosync.core.UnzipUtils import com.dannbrown.astrosync.core.VersionUtils import net.minecraft.client.Minecraft import net.minecraftforge.fml.ModLoadingContext import net.minecraftforge.fml.common.Mod import net.minecraftforge.fml.config.ModConfig import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent import org.apache.logging.log4j.Level import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import thedarkcolour.kotlinforforge.forge.MOD_BUS import thedarkcolour.kotlinforforge.forge.runForDist @Mod(AstroSyncMod.MOD_ID) object AstroSyncMod { const val MOD_ID = "astrosync" const val NAME = "Astro Sync" @JvmField var needsUpdate: Boolean = false @JvmField var screenShown: Boolean = false @JvmField var newVersion: String = "" @JvmField var versionDownloaded: Boolean = false // the logger for our mod val LOGGER: Logger = LogManager.getLogger(MOD_ID) init { ModLoadingContext.get() .registerConfig(ModConfig.Type.COMMON, AstroSyncConfig.SPEC, "$MOD_ID-common.toml") val obj = runForDist( clientTarget = { MOD_BUS.addListener(::onClientSetup) Minecraft.getInstance() }, serverTarget = { MOD_BUS.addListener(::onServerSetup) "test" }) println(obj) } /** * This is used for initializing client specific * things such as renderers and keymaps * Fired on the mod specific event bus. */ private fun onClientSetup(event: FMLClientSetupEvent) { LOGGER.log(Level.INFO, "Initializing client...") checkForUpdates() } /** * Fired on the global Forge bus. */ private fun onServerSetup(event: FMLDedicatedServerSetupEvent) { LOGGER.log(Level.INFO, "${NAME} was loaded on the server, doing nothing.") } private fun checkForUpdates() { // if no repo name is set, return if (AstroSyncConfig.RepoName.get().isEmpty() || AstroSyncConfig.RepoOwner.get().isEmpty()) { LOGGER.log(Level.ERROR, "Repo name or owner not set, cannot check for updates") return } // Check if the version is updated val latestRelease = NetworkUtils.fetchLatestRelease() if (latestRelease != null) { val releaseVersion = VersionUtils.getReleaseVersion(latestRelease) val needsUpdate = VersionUtils.isVersionUpdated(AstroSyncConfig.RepoName.get(), releaseVersion) this.needsUpdate = needsUpdate if(!needsUpdate) { LOGGER.log(Level.INFO, "No new version available") FileUtils.cleanTempFolder() return } // Version from API is higher than the current version, update LOGGER.log(Level.INFO, "New version available: $releaseVersion") this.newVersion = releaseVersion // Get the download URL for the new version val downloadUrl = NetworkUtils.getReleaseDownloadUrl(latestRelease, AstroSyncConfig.RepoName.get(), releaseVersion) // if download url does not exist, return if (downloadUrl == null) { LOGGER.log(Level.ERROR, "Download URL not found") return } // Download the new version zip file FileUtils.downloadZipFile(downloadUrl) // Get folders from new version zip val zipPath = FileUtils.TEMP_PATH?.resolve(FileUtils.TEMP_ZIP_NAME) // if zipPath does not exist, return if (zipPath == null) { LOGGER.log(Level.ERROR, "Zip file not found") return } val folders = UnzipUtils.listZipFolders(zipPath.toPath()) if(folders.isEmpty()) { LOGGER.log(Level.ERROR, "Stop: The modpack zip file was empty or corrupted.") return } // Delete old version folders FileUtils.deleteOldVersionFolders(folders) // Extract new version folders if(FileUtils.PATH == null) { LOGGER.log(Level.ERROR, "Minecraft path not found") return } LOGGER.log(Level.INFO, "Extracting new version files...") UnzipUtils.unzip(zipPath.toPath(), FileUtils.PATH) LOGGER.log(Level.INFO, "New version extracted successfully") // Update version file FileUtils.upsertVersionFile(AstroSyncConfig.RepoName.get(), releaseVersion) LOGGER.log(Level.INFO, "Version file updated to $releaseVersion") // Clean up temp folder FileUtils.cleanTempFolder() this.versionDownloaded = true } } }
1
Kotlin
1
1
dc398f7caa7ab315dec3cda9e3b36297ed9a32c0
5,063
astro-sync
MIT License
src/xqt-kotlinx-json-rpc/commonTest/xqt/kotlinx/rpc/json/test/serialization/types/JsonIntOrString.kt
rhdunn
600,018,019
false
null
// Copyright (C) 2022-2023 <NAME>. SPDX-License-Identifier: Apache-2.0 package xqt.kotlinx.rpc.json.test.serialization.types import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonPrimitive import xqt.kotlinx.rpc.json.serialization.UnsupportedKindTypeException import xqt.kotlinx.rpc.json.serialization.jsonArrayOf import xqt.kotlinx.rpc.json.serialization.jsonObjectOf import xqt.kotlinx.rpc.json.serialization.types.JsonIntOrString import xqt.kotlinx.test.DisplayName import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails @DisplayName("The JSON integer|string type") class TheJsonIntOrStringType { private fun integer(value: Int): JsonIntOrString = JsonIntOrString.IntegerValue(value) private fun string(value: String): JsonIntOrString = JsonIntOrString.StringValue(value) @Test @DisplayName("can serialize to JSON") fun can_serialize_to_json() { assertEquals("1234", JsonIntOrString.serializeToJson(integer(1234)).toString()) assertEquals("-2147483648", JsonIntOrString.serializeToJson(integer(Int.MIN_VALUE)).toString()) assertEquals("2147483647", JsonIntOrString.serializeToJson(integer(Int.MAX_VALUE)).toString()) assertEquals("\"1234\"", JsonIntOrString.serializeToJson(string("1234")).toString()) assertEquals("\"abcdef\"", JsonIntOrString.serializeToJson(string("abcdef")).toString()) } @Test @DisplayName("can deserialize from JSON") fun can_deserialize_from_json() { assertEquals(integer(1234), JsonIntOrString.deserialize(JsonPrimitive(1234))) assertEquals(integer(Int.MIN_VALUE), JsonIntOrString.deserialize(JsonPrimitive(Int.MIN_VALUE))) assertEquals(integer(Int.MAX_VALUE), JsonIntOrString.deserialize(JsonPrimitive(Int.MAX_VALUE))) assertEquals(string("-2147483649"), JsonIntOrString.deserialize(JsonPrimitive(Int.MIN_VALUE.toLong() - 1))) assertEquals(string("2147483648"), JsonIntOrString.deserialize(JsonPrimitive(Int.MAX_VALUE.toLong() + 1))) assertEquals(string("1234"), JsonIntOrString.deserialize(JsonPrimitive("1234"))) assertEquals(string("abcdef"), JsonIntOrString.deserialize(JsonPrimitive("abcdef"))) } @Test @DisplayName("throws an error if the kind type is not supported") fun throws_an_error_if_the_kind_type_is_not_supported() { val e1 = assertFails { JsonIntOrString.deserialize(jsonObjectOf()) } assertEquals(UnsupportedKindTypeException::class, e1::class) assertEquals("Unsupported kind type 'object'", e1.message) val e2 = assertFails { JsonIntOrString.deserialize(jsonArrayOf()) } assertEquals(UnsupportedKindTypeException::class, e2::class) assertEquals("Unsupported kind type 'array'", e2.message) val e3 = assertFails { JsonIntOrString.deserialize(JsonNull) } assertEquals(UnsupportedKindTypeException::class, e3::class) assertEquals("Unsupported kind type 'null'", e3.message) val e4 = assertFails { JsonIntOrString.deserialize(JsonPrimitive(true)) } assertEquals(UnsupportedKindTypeException::class, e4::class) assertEquals("Unsupported kind type 'boolean'", e4.message) val e5 = assertFails { JsonIntOrString.deserialize(JsonPrimitive(1.2)) } assertEquals(UnsupportedKindTypeException::class, e5::class) assertEquals("Unsupported kind type 'decimal'", e5.message) } }
0
Kotlin
1
2
3b4d8bc55ce2945c8b9f2e68db4857a65285e4dd
3,456
xqt-kotlinx-json-rpc
Apache License 2.0
kotlin-electron/src/jsMain/generated/electron/TouchBarColorPickerConstructorOptions.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package electron typealias TouchBarColorPickerConstructorOptions = electron.core.TouchBarColorPickerConstructorOptions
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
174
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/missnalgas/phr2/phrase/Phrase.kt
MissNalgas
293,782,626
false
null
package com.missnalgas.phr2.phrase object Phrase { var title = "No connection" var content = "It seems like we had some troubles connecting to the server." var author = "MSSN" override fun toString() = title }
0
Kotlin
0
0
b7a517a74fe859d496e6db04a20313f343e00002
226
Leaves
MIT License
app/src/main/java/com/howettl/mvvm/data/model/Employnees.kt
yoonusc
469,022,636
false
null
package com.howettl.mvvm.data.model import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverter import androidx.room.TypeConverters import com.howettl.mvvm.data.typeConverter.DataConverter @Entity data class Employeesd(@field:PrimaryKey val id: Int, val name: String, val username: String, val email: String, val img: String, val phone: String, val website: String, @TypeConverters(DataConverter::class) val address:Address,@TypeConverters(DataConverter::class) val company:Company )
0
Kotlin
0
0
48186f29f791cab7ac753b9015c729181e336d25
522
employe-test-eapp
MIT License
compiler/testData/codegen/box/objects/nestedDerivedClassCallsProtectedFromCompanion.kt
JakeWharton
99,388,807
false
null
// IGNORE_BACKEND_FIR: JVM_IR open class A { companion object { protected fun foo() = "OK" } class B : A() { fun bar() = foo() } } fun box() = A.B().bar()
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
188
kotlin
Apache License 2.0
app/src/main/java/io/horizontalsystems/bankwallet/modules/metricchart/CoinTvlChartService.kt
horizontalsystems
142,825,178
false
null
package io.horizontalsystems.bankwallet.modules.metricchart import io.horizontalsystems.bankwallet.modules.chart.AbstractChartService import io.horizontalsystems.bankwallet.modules.chart.ChartPointsWrapper import io.horizontalsystems.chartview.models.ChartPoint import io.horizontalsystems.core.ICurrencyManager import io.horizontalsystems.core.entities.Currency import io.horizontalsystems.marketkit2.MarketKit import io.horizontalsystems.marketkit2.models.HsTimePeriod import io.reactivex.Single class CoinTvlChartService( override val currencyManager: ICurrencyManager, private val marketKit: MarketKit, private val coinUid: String, ) : AbstractChartService() { override val initialChartInterval = HsTimePeriod.Month1 override val chartIntervals = HsTimePeriod.values().toList() override fun getItems( chartInterval: HsTimePeriod, currency: Currency ): Single<ChartPointsWrapper> = try { marketKit.marketInfoTvlSingle(coinUid, currency.code, chartInterval) .map { info -> info.map { ChartPoint(it.value.toFloat(), it.timestamp) } } .map { ChartPointsWrapper(chartInterval, it) } } catch (e: Exception) { Single.error(e) } }
168
null
364
895
218cd81423c570cdd92b1d5161a600d07c35c232
1,252
unstoppable-wallet-android
MIT License
utilities/src/main/kotlin/extensions/Pair.kt
rstockbridge
225,212,001
false
null
@file:Suppress("unused", "MemberVisibilityCanBePrivate") package extensions fun <T, U> Pair<T, U>.flip(): Pair<U, T> = second to first fun <T : Comparable<T>> Pair<T, T>.max(): T = maxOf(first, second) fun <T : Comparable<T>> Pair<T, T>.min(): T = minOf(first, second) fun <T> Pair<T, T>.valuesMatch(): Boolean = first == second
0
Kotlin
0
0
bcd6daf81787ed9a1d90afaa9646b1c513505d75
334
AdventOfCode2019
MIT License
config.gradle.kt
pokercc
305,630,470
false
null
android { compileSdkVersion 29 buildToolsVersion "29.0.3" defaultConfig { minSdkVersion 21 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles "consumer-rules.pro" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile ('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { targetCompatibility = JavaVersion.VERSION_1_8 sourceCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" } } //compileKotlin { // kotlinOptions { // apiVersion = '1.3' // } //}
11
null
43
9
f0c611b66439a51c01729d02312747de03fa41e9
780
BoxShadowLayout
MIT License
src/test/kotlin/mobi/hsz/idea/gitignore/actions/CloseIgnoredEditorsActionTest.kt
JetBrains
20,956,093
false
{"Kotlin": 294248, "Lex": 2221, "HTML": 433}
// Copyright 2000-2020 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 mobi.hsz.idea.gitignore.actions import mobi.hsz.idea.gitignore.Common class CloseIgnoredEditorsActionTest : Common<Any?>() { fun testCloseIgnoredEditorsActionInvocation() { val action = CloseIgnoredEditorsAction() myFixture.testAction(action).apply { assertEquals("Close Ignored", text) assertNull(description) assertFalse("Action is not visible if there is no Ignore file context", isEnabledAndVisible) } } }
11
Kotlin
176
1,289
59781e4c143913f4a880b21632de1a3b12ea55ae
632
idea-gitignore
Apache License 2.0
app/src/main/java/online/muhammadali/todolist/feature_auth/presentation/screens/SignUpScreen.kt
MuhammadAli251018
698,671,373
false
{"Kotlin": 98643}
package online.muhammadali.todolist.feature_auth.presentation.screens import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import online.muhammadali.todolist.R import online.muhammadali.todolist.common.presentation.components.DividerWithText import online.muhammadali.todolist.common.presentation.components.FilledTextButton import online.muhammadali.todolist.common.presentation.components.HorizontalSpace import online.muhammadali.todolist.common.presentation.components.PasswordTextField import online.muhammadali.todolist.common.presentation.components.StrokeButtonWithIcon import online.muhammadali.todolist.common.presentation.components.TextFieldIcon import online.muhammadali.todolist.common.presentation.components.TextFieldWithIcon import online.muhammadali.todolist.common.presentation.components.VerticalSpace import online.muhammadali.todolist.common.presentation.theme.TodoListTheme import online.muhammadali.todolist.feature_auth.presentation.viewmodel.SignUpViewModel // TODO CREATE SCREEN TO RECEIVE VERIFICATION CODE @Composable fun SignUpScreen( viewModel: SignUpViewModel, navHostController: NavHostController ) { val name by viewModel.fullNameState.collectAsStateWithLifecycle() val email by viewModel.emailState.collectAsStateWithLifecycle() val password by viewModel.passwordState.collectAsStateWithLifecycle() val showPassword by viewModel.showPasswordState.collectAsStateWithLifecycle() val passwordLabel by viewModel.passwordLabelState.collectAsStateWithLifecycle() val emailLabel by viewModel.emailLabelState.collectAsStateWithLifecycle() val nameLabel by viewModel.nameLabelState.collectAsStateWithLifecycle() val nameLabelColor by viewModel.nameLabelColorState.collectAsStateWithLifecycle() val emailLabelColor by viewModel.emailLabelColorState.collectAsStateWithLifecycle() val passwordLabelColor by viewModel.passwordLabelColorState.collectAsStateWithLifecycle() SignUpScreen( fullName = name, email = email, password = password, showPassword = showPassword, nameLabel = nameLabel, emailLabel = emailLabel, passwordLabel = passwordLabel, nameLabelColor = nameLabelColor, emailLabelColor = emailLabelColor, passwordLabelColor = passwordLabelColor, navHostController = navHostController, onEmailChange = viewModel::onEmailChange, onNameChange = viewModel::onNameChange, onPasswordChange = viewModel::onPasswordChange, onForgotPasswordClicked = viewModel::onForgotPasswordClicked, onCreateAccountClicked = viewModel::onCreateAccountClicked, onSignWithGoogleClicked = viewModel::onSignWithGoogleClicked, onLogInClicked = viewModel::onLogInClicked, onShowPasswordClicked = viewModel::onShowPasswordClicked ) } @Composable fun SignUpScreen ( // states that depends on data from view model fullName: String, email: String, password: String, // states that depends on ui state showPassword: Boolean, nameLabel: String, emailLabel: String, passwordLabel: String, nameLabelColor: Color, emailLabelColor: Color, passwordLabelColor: Color, navHostController: NavHostController, onEmailChange: (String) -> Unit, onNameChange: (String) -> Unit, onPasswordChange: (String) -> Unit, onForgotPasswordClicked: () -> Unit, onCreateAccountClicked: () -> Unit, onSignWithGoogleClicked: () -> Unit, onLogInClicked: () -> Unit, onShowPasswordClicked: () -> Unit ) { Column( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background), horizontalAlignment = Alignment.CenterHorizontally ) { VerticalSpace(height = 40.dp) Image( painter = painterResource(id = R.drawable.ic_done), contentDescription = "Done Logo" ) VerticalSpace(height = 40.dp) Text( modifier = Modifier .padding(horizontal = 30.dp) .align(Alignment.Start), text = "Create your account", color = Color.White, fontSize = 30.sp ) VerticalSpace(height = 20.dp) TextFieldWithIcon( modifier = Modifier .padding(horizontal = 30.dp), label = nameLabel/*"Full Name"*/, labelTextColor = nameLabelColor, text = fullName, textFontSize = 18.sp, labelFontSize = 16.sp, leadingIcon = TextFieldIcon( painter = painterResource(id = R.drawable.user), description = "Full Name", onClick = {} ), keyboardOptions = KeyboardOptions (keyboardType = KeyboardType.Email ), onValueChange = onNameChange ) VerticalSpace(height = 20.dp) TextFieldWithIcon( modifier = Modifier .padding(horizontal = 30.dp), label = emailLabel/*"Email"*/, labelTextColor = emailLabelColor, text = email, textFontSize = 18.sp, labelFontSize = 16.sp, leadingIcon = TextFieldIcon( painter = painterResource(id = R.drawable.usertag), description = "Email", onClick = {} ), keyboardOptions = KeyboardOptions (keyboardType = KeyboardType.Email ), onValueChange = onEmailChange ) VerticalSpace(height = 20.dp) PasswordTextField( modifier = Modifier .padding(horizontal = 30.dp), label = passwordLabel/*"Password"*/, labelTextColor = passwordLabelColor, text = password, textFontSize = 18.sp, labelFontSize = 16.sp, showPassword = showPassword, onShowPasswordClicked = onShowPasswordClicked, onValueChange = onPasswordChange ) VerticalSpace(height = 20.dp) Text( modifier = Modifier .padding(horizontal = 30.dp) .align(Alignment.End) .clickable(onClick = onForgotPasswordClicked), text = "Forgot Password?", color = Color.White ) VerticalSpace(height = 20.dp) FilledTextButton( modifier = Modifier .padding(horizontal = 30.dp) .fillMaxWidth(), text = "Create Account", textSize = 18.sp, onClick = onCreateAccountClicked ) VerticalSpace(height = 30.dp) DividerWithText( modifier = Modifier.fillMaxWidth(), width = 1.dp, color = Color.White.copy(alpha = 0.7f ), text = "Or continue with", textSize = 14.sp, textColor = Color.White, textWeight = FontWeight.Normal, innerPadding = PaddingValues(horizontal = 30.dp) ) VerticalSpace(height = 30.dp) StrokeButtonWithIcon( modifier = Modifier .padding(horizontal = 30.dp) .fillMaxWidth(), text = "Google", textSize = 18.sp, iconDescription = "Google", icon = painterResource(id = R.drawable.google), iconSize = 25.dp, iconColor = Color.White, onClick = onSignWithGoogleClicked ) VerticalSpace(height = 20.dp) Row { Text( text = "Don't have account", color = Color.White ) HorizontalSpace(width = 5.dp) Text( modifier = Modifier .clickable ( onClick = { onLogInClicked() navHostController.navigate(AuthScreen.LogIn.rout) } ), text = "LogIn", color = MaterialTheme.colorScheme.primary ) } } } @Preview @Composable fun SignUpScreenPreview() { TodoListTheme { } }
0
Kotlin
0
0
7afa8a4be8e9759fab774d45a20af28531584fcc
9,403
Todo-List
MIT License
src/all/wpcomics/src/eu/kanade/tachiyomi/extension/all/wpcomics/WPComicsFactory.kt
MadonnaBalena-Team
272,300,322
true
{"Kotlin": 2418188, "Shell": 1729, "Java": 608}
package eu.kanade.tachiyomi.extension.all.wpcomics import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceFactory import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.util.asJsoup import java.text.SimpleDateFormat import java.util.Locale import okhttp3.HttpUrl import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element class WPComicsFactory : SourceFactory { override fun createSources(): List<Source> = listOf( ManhuaPlus(), ManhuaES(), MangaSum(), XoxoComics(), NhatTruyen(), NetTruyen() ) } private class ManhuaPlus : WPComics("Manhua Plus", "https://manhuaplus.com", "en") { override val pageListSelector: String = "div.chapter-detail img, ${super.pageListSelector}" } private class ManhuaES : WPComics("Manhua ES", "https://manhuaes.com", "en", SimpleDateFormat("HH:mm - dd/MM/yyyy Z", Locale.US), "+0700") { override val popularPath = "category-comics/manga" override fun popularMangaFromElement(element: Element): SManga { return SManga.create().apply { element.select("div.overlay a:has(h2)").let { title = it.text() setUrlWithoutDomain(it.attr("href")) } thumbnail_url = element.select("img").firstOrNull()?.attr("abs:src") } } override val pageListSelector = "div.chapter-detail img" } private class MangaSum : WPComics("MangaSum", "https://mangasum.com", "en", SimpleDateFormat("MM/dd/yy", Locale.US), null) { override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = GET("$baseUrl/genres?keyword=$query&page=$page", headers) } private class XoxoComics : WPComics("XOXO Comics", "https://xoxocomics.com", "en", SimpleDateFormat("MM/dd/yy", Locale.US), null) { override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/comic-updates?page=$page", headers) override fun latestUpdatesSelector() = "li.row" override fun latestUpdatesFromElement(element: Element): SManga { return SManga.create().apply { element.select("h3 a").let { title = it.text() setUrlWithoutDomain(it.attr("href")) } thumbnail_url = element.select("img").attr("data-original") } } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { return GET("$baseUrl/search?keyword=$query&page=$page", headers) } override fun chapterListParse(response: Response): List<SChapter> { val chapters = mutableListOf<SChapter>() // recursively add chapters from paginated chapter list fun parseChapters(document: Document) { document.select(chapterListSelector()).map { chapters.add(chapterFromElement(it)) } document.select("ul.pagination a[rel=next]").firstOrNull()?.let { a -> parseChapters(client.newCall(GET(a.attr("abs:href"), headers)).execute().asJsoup()) } } parseChapters(response.asJsoup()) return chapters } override fun pageListRequest(chapter: SChapter): Request = GET(baseUrl + "${chapter.url}/all") } private class NhatTruyen : WPComics("NhatTruyen", "http://nhattruyen.com", "vi", SimpleDateFormat("dd/MM/yy", Locale.getDefault()), null) { override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = GET("$baseUrl/the-loai?keyword=$query&page=$page", headers) override fun imageRequest(page: Page): Request = GET(page.imageUrl!!, headersBuilder().add("Referer", baseUrl).build()) } private class NetTruyen : WPComics("NetTruyen", "http://www.nettruyen.com", "vi", SimpleDateFormat("dd/MM/yy", Locale.getDefault()), null) { override fun imageRequest(page: Page): Request = GET(page.imageUrl!!, headersBuilder().add("Referer", baseUrl).build()) // search and filters taken from old extension (1.2.5) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { var url = HttpUrl.parse("$baseUrl/tim-truyen?")!!.newBuilder() (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is Genre -> { url = if (filter.state == 0) url else HttpUrl.parse(url.toString() .replace("tim-truyen?", "tim-truyen/${getGenreList().map { it.first }[filter.state]}?"))!! .newBuilder() } is Status -> { url.addQueryParameter("status", if (filter.state == 0) "hajau" else filter.state.toString()) url.addQueryParameter("sort", "0") } } } url.addQueryParameter("keyword", query) return GET(url.toString(), headers) } private fun getStatusList() = arrayOf("Tất cả", "Đang tiến hành", "Đã hoàn thành", "Tạm ngừng") private class Status(status: Array<String>) : Filter.Select<String>("Status", status) private class Genre(genreList: Array<String>) : Filter.Select<String>("Thể loại", genreList) override fun getFilterList() = FilterList( Status(getStatusList()), Genre(getGenreList().map { it.second }.toTypedArray()) ) private fun getGenreList() = arrayOf( "tim-truyen" to "Tất cả", "action" to "Action", "adult" to "Adult", "adventure" to "Adventure", "anime" to "Anime", "chuyen-sinh" to "Chuyển Sinh", "comedy" to "Comedy", "comic" to "Comic", "cooking" to "Cooking", "co-dai" to "Cổ Đại", "doujinshi" to "Doujinshi", "drama" to "Drama", "dam-my" to "Đam Mỹ", "ecchi" to "Ecchi", "fantasy" to "Fantasy", "gender-bender" to "Gender Bender", "harem" to "Harem", "historical" to "Historical", "horror" to "Horror", "josei" to "Josei", "live-action" to "Live action", "manga" to "Manga", "manhua" to "Manhua", "manhwa" to "Manhwa", "martial-arts" to "Martial Arts", "mature" to "Mature", "mecha" to "Mecha", "mystery" to "Mystery", "ngon-tinh" to "Ngôn Tình", "one-shot" to "One shot", "psychological" to "Psychological", "romance" to "Romance", "school-life" to "School Life", "sci-fi" to "Sci-fi", "seinen" to "Seinen", "shoujo" to "Shoujo", "shoujo-ai" to "Shoujo Ai", "shounen" to "Shounen", "shounen-ai" to "Shounen Ai", "slice-of-life" to "Slice of Life", "smut" to "Smut", "soft-yaoi" to "Soft Yaoi", "soft-yuri" to "Soft Yuri", "sports" to "Sports", "supernatural" to "Supernatural", "thieu-nhi" to "Thiếu Nhi", "tragedy" to "Tragedy", "trinh-tham" to "Trinh Thám", "truyen-scan" to "Truyện scan", "truyen-mau" to "Truyện Màu", "webtoon" to "Webtoon", "xuyen-khong" to "Xuyên Không" ) }
0
Kotlin
0
0
5fa94719627fce5d7ea10db3e4ebaa23d35ccb43
7,443
tachiyomi-extensions
Apache License 2.0
src/all/wpcomics/src/eu/kanade/tachiyomi/extension/all/wpcomics/WPComicsFactory.kt
MadonnaBalena-Team
272,300,322
true
{"Kotlin": 2418188, "Shell": 1729, "Java": 608}
package eu.kanade.tachiyomi.extension.all.wpcomics import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceFactory import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.util.asJsoup import java.text.SimpleDateFormat import java.util.Locale import okhttp3.HttpUrl import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element class WPComicsFactory : SourceFactory { override fun createSources(): List<Source> = listOf( ManhuaPlus(), ManhuaES(), MangaSum(), XoxoComics(), NhatTruyen(), NetTruyen() ) } private class ManhuaPlus : WPComics("Manhua Plus", "https://manhuaplus.com", "en") { override val pageListSelector: String = "div.chapter-detail img, ${super.pageListSelector}" } private class ManhuaES : WPComics("Manhua ES", "https://manhuaes.com", "en", SimpleDateFormat("HH:mm - dd/MM/yyyy Z", Locale.US), "+0700") { override val popularPath = "category-comics/manga" override fun popularMangaFromElement(element: Element): SManga { return SManga.create().apply { element.select("div.overlay a:has(h2)").let { title = it.text() setUrlWithoutDomain(it.attr("href")) } thumbnail_url = element.select("img").firstOrNull()?.attr("abs:src") } } override val pageListSelector = "div.chapter-detail img" } private class MangaSum : WPComics("MangaSum", "https://mangasum.com", "en", SimpleDateFormat("MM/dd/yy", Locale.US), null) { override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = GET("$baseUrl/genres?keyword=$query&page=$page", headers) } private class XoxoComics : WPComics("XOXO Comics", "https://xoxocomics.com", "en", SimpleDateFormat("MM/dd/yy", Locale.US), null) { override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/comic-updates?page=$page", headers) override fun latestUpdatesSelector() = "li.row" override fun latestUpdatesFromElement(element: Element): SManga { return SManga.create().apply { element.select("h3 a").let { title = it.text() setUrlWithoutDomain(it.attr("href")) } thumbnail_url = element.select("img").attr("data-original") } } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { return GET("$baseUrl/search?keyword=$query&page=$page", headers) } override fun chapterListParse(response: Response): List<SChapter> { val chapters = mutableListOf<SChapter>() // recursively add chapters from paginated chapter list fun parseChapters(document: Document) { document.select(chapterListSelector()).map { chapters.add(chapterFromElement(it)) } document.select("ul.pagination a[rel=next]").firstOrNull()?.let { a -> parseChapters(client.newCall(GET(a.attr("abs:href"), headers)).execute().asJsoup()) } } parseChapters(response.asJsoup()) return chapters } override fun pageListRequest(chapter: SChapter): Request = GET(baseUrl + "${chapter.url}/all") } private class NhatTruyen : WPComics("NhatTruyen", "http://nhattruyen.com", "vi", SimpleDateFormat("dd/MM/yy", Locale.getDefault()), null) { override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request = GET("$baseUrl/the-loai?keyword=$query&page=$page", headers) override fun imageRequest(page: Page): Request = GET(page.imageUrl!!, headersBuilder().add("Referer", baseUrl).build()) } private class NetTruyen : WPComics("NetTruyen", "http://www.nettruyen.com", "vi", SimpleDateFormat("dd/MM/yy", Locale.getDefault()), null) { override fun imageRequest(page: Page): Request = GET(page.imageUrl!!, headersBuilder().add("Referer", baseUrl).build()) // search and filters taken from old extension (1.2.5) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { var url = HttpUrl.parse("$baseUrl/tim-truyen?")!!.newBuilder() (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is Genre -> { url = if (filter.state == 0) url else HttpUrl.parse(url.toString() .replace("tim-truyen?", "tim-truyen/${getGenreList().map { it.first }[filter.state]}?"))!! .newBuilder() } is Status -> { url.addQueryParameter("status", if (filter.state == 0) "hajau" else filter.state.toString()) url.addQueryParameter("sort", "0") } } } url.addQueryParameter("keyword", query) return GET(url.toString(), headers) } private fun getStatusList() = arrayOf("Tất cả", "Đang tiến hành", "Đã hoàn thành", "Tạm ngừng") private class Status(status: Array<String>) : Filter.Select<String>("Status", status) private class Genre(genreList: Array<String>) : Filter.Select<String>("Thể loại", genreList) override fun getFilterList() = FilterList( Status(getStatusList()), Genre(getGenreList().map { it.second }.toTypedArray()) ) private fun getGenreList() = arrayOf( "tim-truyen" to "Tất cả", "action" to "Action", "adult" to "Adult", "adventure" to "Adventure", "anime" to "Anime", "chuyen-sinh" to "Chuyển Sinh", "comedy" to "Comedy", "comic" to "Comic", "cooking" to "Cooking", "co-dai" to "Cổ Đại", "doujinshi" to "Doujinshi", "drama" to "Drama", "dam-my" to "Đam Mỹ", "ecchi" to "Ecchi", "fantasy" to "Fantasy", "gender-bender" to "Gender Bender", "harem" to "Harem", "historical" to "Historical", "horror" to "Horror", "josei" to "Josei", "live-action" to "Live action", "manga" to "Manga", "manhua" to "Manhua", "manhwa" to "Manhwa", "martial-arts" to "Martial Arts", "mature" to "Mature", "mecha" to "Mecha", "mystery" to "Mystery", "ngon-tinh" to "Ngôn Tình", "one-shot" to "One shot", "psychological" to "Psychological", "romance" to "Romance", "school-life" to "School Life", "sci-fi" to "Sci-fi", "seinen" to "Seinen", "shoujo" to "Shoujo", "shoujo-ai" to "Shoujo Ai", "shounen" to "Shounen", "shounen-ai" to "Shounen Ai", "slice-of-life" to "Slice of Life", "smut" to "Smut", "soft-yaoi" to "Soft Yaoi", "soft-yuri" to "Soft Yuri", "sports" to "Sports", "supernatural" to "Supernatural", "thieu-nhi" to "Thiếu Nhi", "tragedy" to "Tragedy", "trinh-tham" to "Trinh Thám", "truyen-scan" to "Truyện scan", "truyen-mau" to "Truyện Màu", "webtoon" to "Webtoon", "xuyen-khong" to "Xuyên Không" ) }
0
Kotlin
0
0
5fa94719627fce5d7ea10db3e4ebaa23d35ccb43
7,443
tachiyomi-extensions
Apache License 2.0
module/module-database-core/src/main/kotlin/taboolib/module/database/QueryTask.kt
TabooLib
120,413,612
false
null
package taboolib.module.database import java.sql.ResultSet /** * TabooLib * taboolib.module.database.QueryTask * * @author sky * @since 2021/6/23 2:11 下午 */ open class QueryTask(val future: Future<ResultSet>) { open fun run(): Int { return future.call { fetchSize } } open fun find(): Boolean { return future.call { next() } } open fun <T> first(call: ResultSet.() -> T): T { return future.call { next() call(this) } } open fun <T> firstOrNull(call: ResultSet.() -> T): T? { return future.call { if (next()) { call(this) } else { null } } } open fun <T> map(call: ResultSet.() -> T): List<T> { return future.call { val arr = arrayListOf<T>() while (next()) { arr += call(this) } arr } } open fun <T> mapNotNull(call: ResultSet.() -> T?): List<T> { return future.call { val arr = arrayListOf<T>() while (next()) { call(this)?.also { t -> arr += t } } arr } } open fun forEach(call: ResultSet.() -> Unit) { future.call { while (next()) { call(this) } } } }
13
Kotlin
81
229
065c8de7033a3073181476fd1ec6f1e830ff9983
1,381
taboolib
MIT License
module/module-database-core/src/main/kotlin/taboolib/module/database/QueryTask.kt
TabooLib
120,413,612
false
null
package taboolib.module.database import java.sql.ResultSet /** * TabooLib * taboolib.module.database.QueryTask * * @author sky * @since 2021/6/23 2:11 下午 */ open class QueryTask(val future: Future<ResultSet>) { open fun run(): Int { return future.call { fetchSize } } open fun find(): Boolean { return future.call { next() } } open fun <T> first(call: ResultSet.() -> T): T { return future.call { next() call(this) } } open fun <T> firstOrNull(call: ResultSet.() -> T): T? { return future.call { if (next()) { call(this) } else { null } } } open fun <T> map(call: ResultSet.() -> T): List<T> { return future.call { val arr = arrayListOf<T>() while (next()) { arr += call(this) } arr } } open fun <T> mapNotNull(call: ResultSet.() -> T?): List<T> { return future.call { val arr = arrayListOf<T>() while (next()) { call(this)?.also { t -> arr += t } } arr } } open fun forEach(call: ResultSet.() -> Unit) { future.call { while (next()) { call(this) } } } }
13
Kotlin
81
229
065c8de7033a3073181476fd1ec6f1e830ff9983
1,381
taboolib
MIT License
platform/backend/core/src/main/kotlin/io/hamal/core/component/Converter.kt
hamal-io
622,870,037
false
{"Kotlin": 1744717, "C": 1398401, "TypeScript": 54320, "C++": 40651, "Lua": 36419, "Makefile": 11728, "Java": 7564, "CMake": 2881, "JavaScript": 1532, "HTML": 694, "Shell": 456, "CSS": 118}
package io.hamal.core.component import io.hamal.lib.common.SnowflakeId import io.hamal.lib.common.domain.DomainId import io.hamal.lib.common.domain.Limit import io.hamal.lib.domain.ReqId import io.hamal.lib.domain.vo.* import org.springframework.core.convert.converter.Converter import kotlin.reflect.KClass object LimitConverter : Converter<String, Limit> { override fun convert(source: String) = Limit(source.toInt()) } object CorrelationIdConverter : Converter<String, CorrelationId> { override fun convert(source: String) = CorrelationId(source) } object TopicNameConverter : Converter<String, TopicName> { override fun convert(source: String) = TopicName(source) } object AccountIdConverter : DomainIdConverter<AccountId>(AccountId::class, ::AccountId) object ExecIdConverter : DomainIdConverter<ExecId>(ExecId::class, ::ExecId) object ExecLogIdConverter : DomainIdConverter<ExecLogId>(ExecLogId::class, ::ExecLogId) object FuncIdConverter : DomainIdConverter<FuncId>(FuncId::class, ::FuncId) object GroupIdConverter : DomainIdConverter<GroupId>(GroupId::class, ::GroupId) object NamespaceIdConverter : DomainIdConverter<NamespaceId>(NamespaceId::class, ::NamespaceId) object ReqIdConverter : DomainIdConverter<ReqId>(ReqId::class, ::ReqId) object TopicIdConverter : DomainIdConverter<TopicId>(TopicId::class, ::TopicId) object TopicEntryIdConverter : DomainIdConverter<TopicEntryId>(TopicEntryId::class, ::TopicEntryId) object TriggerIdConverter : DomainIdConverter<TriggerId>(TriggerId::class, ::TriggerId) sealed class DomainIdConverter<ID : DomainId>( val clazz: KClass<ID>, val ctor: (SnowflakeId) -> ID, ) : Converter<String, ID> { override fun convert(source: String): ID { return ctor(SnowflakeId(source)) } }
6
Kotlin
0
0
fd06bf799f18db2d425b7084abf15b741fa9878e
1,766
hamal
Creative Commons Zero v1.0 Universal
features/login/impl/src/test/kotlin/io/element/android/features/login/impl/error/ErrorFormatterTest.kt
element-hq
546,522,002
false
{"Kotlin": 8692554, "Python": 57175, "Shell": 39911, "JavaScript": 20399, "Java": 9607, "HTML": 9416, "CSS": 2519, "Ruby": 44}
/* * Copyright (c) 2023 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 io.element.android.features.login.impl.error import com.google.common.truth.Truth.assertThat import io.element.android.features.login.impl.R import io.element.android.libraries.matrix.api.auth.AuthenticationException import io.element.android.libraries.ui.strings.CommonStrings import org.junit.Test class ErrorFormatterTests { // region loginError @Test fun `loginError - invalid unknown error returns unknown error message`() { val error = Throwable("Some unknown error") assertThat(loginError(error)).isEqualTo(CommonStrings.error_unknown) } @Test fun `loginError - invalid auth error returns unknown error message`() { val error = AuthenticationException.SlidingSyncNotAvailable("Some message. Also contains M_FORBIDDEN, but won't be parsed") assertThat(loginError(error)).isEqualTo(CommonStrings.error_unknown) } @Test fun `loginError - unknown error returns unknown error message`() { val error = AuthenticationException.Generic("M_UNKNOWN") assertThat(loginError(error)).isEqualTo(CommonStrings.error_unknown) } @Test fun `loginError - forbidden error returns incorrect credentials message`() { val error = AuthenticationException.Generic("M_FORBIDDEN") assertThat(loginError(error)).isEqualTo(R.string.screen_login_error_invalid_credentials) } @Test fun `loginError - user_deactivated error returns deactivated account message`() { val error = AuthenticationException.Generic("M_USER_DEACTIVATED") assertThat(loginError(error)).isEqualTo(R.string.screen_login_error_deactivated_account) } // endregion loginError }
9
Kotlin
65
955
31d0621fa15fe153bfd36104e560c9703eabe917
2,290
element-x-android
Apache License 2.0
litho-compiler-plugin/compiler/src/main/kotlin/com/facebook/litho/LithoCodeAnalysisExtension.kt
facebook
80,179,724
false
{"Kotlin": 5825848, "Java": 5578851, "C++": 616537, "Starlark": 198527, "JavaScript": 29060, "C": 25074, "Shell": 8243, "CSS": 5558, "CMake": 4783, "Objective-C": 4012}
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation import org.jetbrains.kotlin.com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingTrace import org.jetbrains.kotlin.resolve.extensions.AnalysisHandlerExtension class LithoCodeAnalysisExtension( private val reporter: (String, CompilerMessageSourceLocation) -> Unit ) : AnalysisHandlerExtension { override fun analysisCompleted( project: Project, module: ModuleDescriptor, bindingTrace: BindingTrace, files: Collection<KtFile> ): AnalysisResult? { files.forEach { file -> val visitor = LithoFileVisitor(file, bindingTrace.bindingContext) { message, location -> reporter("Litho: $message", location) } visitor.visitKtElement(file) } return null } }
88
Kotlin
765
7,703
8bde23649ae0b1c594b9bdfcb4668feb7d8a80c0
1,640
litho
Apache License 2.0
infrastructure/src/main/kotlin/com/lukinhasssss/admin/catalogo/infrastructure/utils/metrics/Metric.kt
Lukinhasssss
551,493,782
false
{"Kotlin": 834862, "Dockerfile": 2158}
package com.lukinhasssss.admin.catalogo.infrastructure.utils.metrics import io.micrometer.core.instrument.MeterRegistry import io.micrometer.core.instrument.Timer import org.springframework.stereotype.Component import java.util.concurrent.TimeUnit import kotlin.system.measureTimeMillis @Component class Metric(private val meterRegistry: MeterRegistry) { fun <T> measureExecutionTime(processName: String, block: () -> T): T { val timer: Timer = meterRegistry.timer("metric_name") val result: T val duration = measureTimeMillis { result = block() } timer.record(duration, TimeUnit.MILLISECONDS) println(processName) return result } }
0
Kotlin
0
5
6bb44dcd8445d1ab7e159d7b50deef8034f4cfb0
717
admin-catalogo-de-videos-kotlin
MIT License
config/src/test/kotlin/org/springframework/security/config/web/servlet/headers/XssProtectionConfigDslTests.kt
lenxin
310,797,201
true
{"INI": 18, "Shell": 7, "Batchfile": 1, "Java": 2837, "SQL": 14, "HTML": 34, "CSS": 17, "Gradle Kotlin DSL": 2, "Kotlin": 138, "Java Server Pages": 49, "Java Properties": 14, "JavaScript": 15, "Python": 1, "PLSQL": 1, "Markdown": 4, "Ruby": 2}
package org.springframework.security.config.web.servlet.headers import org.junit.Rule import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.config.web.servlet.invoke import org.springframework.security.config.test.SpringTestRule import org.springframework.security.web.server.header.XXssProtectionServerHttpHeadersWriter import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.get /** * Tests for [XssProtectionConfigDsl] * * @author <NAME> */ class XssProtectionConfigDslTests { @Rule @JvmField var spring = SpringTestRule() @Autowired lateinit var mockMvc: MockMvc @Test fun `headers when XSS protection configured then header in response`() { this.spring.register(XssProtectionConfig::class.java).autowire() this.mockMvc.get("/") { secure = true }.andExpect { header { string(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "1; mode=block") } } } @EnableWebSecurity open class XssProtectionConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { headers { defaultsDisabled = true xssProtection { } } } } } @Test fun `headers when XSS protection with block false then mode is not block in header`() { this.spring.register(XssProtectionBlockFalseConfig::class.java).autowire() this.mockMvc.get("/") { secure = true }.andExpect { header { string(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "1") } } } @EnableWebSecurity open class XssProtectionBlockFalseConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { headers { defaultsDisabled = true xssProtection { block = false } } } } } @Test fun `headers when XSS protection disabled then X-XSS-Protection header is 0`() { this.spring.register(XssProtectionDisabledConfig::class.java).autowire() this.mockMvc.get("/") { secure = true }.andExpect { header { string(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "0") } } } @EnableWebSecurity open class XssProtectionDisabledConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { headers { defaultsDisabled = true xssProtection { xssProtectionEnabled = false } } } } } @Test fun `headers when XSS protection disabled then X-XSS-Protection header not in response`() { this.spring.register(XssProtectionDisabledFunctionConfig::class.java).autowire() this.mockMvc.get("/") { secure = true }.andExpect { header { doesNotExist(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION) } } } @EnableWebSecurity open class XssProtectionDisabledFunctionConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http { headers { xssProtection { disable() } } } } } }
0
Java
0
0
9cc4bd14b66afcb0142c9a0df35738342a5eeaa4
3,920
spring-security
Apache License 2.0
Chapter10/Exercise10.02/app/src/androidTest/java/com/android/testable/myapplication/MainActivityUiTest.kt
PacktPublishing
575,781,987
false
null
package com.android.testable.myapplication import android.app.Application import androidx.lifecycle.Lifecycle import androidx.test.core.app.ActivityScenario.launch import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.* import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class MainActivityUiTest { @Test fun showSumResultInTextView() { val scenario = launch(MainActivity::class.java) scenario.moveToState(Lifecycle.State.RESUMED) onView(withId(R.id.edit_text)).perform(replaceText("5")) onView(withId(R.id.button)).perform(click()) onView(withId(R.id.text_view)).check( matches( withText( getApplicationContext<Application>().getString( R.string.the_sum_of_numbers_from_1_to_is, 5, "15" ) ) ) ) } @Test fun showErrorInTextView() { val scenario = launch(MainActivity::class.java) scenario.moveToState(Lifecycle.State.RESUMED) onView(withId(R.id.edit_text)).perform(replaceText("-5")) onView(withId(R.id.button)).perform(click()) onView(withId(R.id.text_view)).check(matches(withText(getApplicationContext<Application>().getString(R.string.error_invalid_number)))) } }
1
Kotlin
1
8
69028f4bc9fee3812072504bb1b9ec07c722db35
1,731
How-to-Build-Android-Apps-with-Kotlin-Second-Edition
MIT License
kofu/src/main/kotlin/org/springframework/fu/kofu/webflux/WebFluxClientDsl.kt
spring-projects-experimental
134,733,282
false
null
package org.springframework.fu.kofu.webflux import org.springframework.boot.autoconfigure.web.reactive.* import org.springframework.boot.autoconfigure.web.reactive.function.client.ReactiveWebClientBuilderInitializer import org.springframework.context.support.GenericApplicationContext import org.springframework.fu.kofu.AbstractDsl import org.springframework.fu.kofu.ConfigurationDsl import org.springframework.fu.kofu.web.JacksonDsl import org.springframework.web.reactive.function.client.WebClient /** * Kofu DSL for WebFlux webClient. * * Register a [WebClient.Builder] bean via a [dedicated DSL][WebFluxClientDsl]. * * When no codec is configured, `String` and `Resource` ones are configured by default. * When a `codecs { }` block is declared, the one specified are configured by default. * * Required dependencies can be retrieve using `org.springframework.boot:spring-boot-starter-webflux`. * * @sample org.springframework.fu.kofu.samples.clientDsl * @see WebFluxClientDsl.codecs * @author <NAME> */ class WebFluxClientDsl(private val init: WebFluxClientDsl.() -> Unit) : AbstractDsl() { private var codecsConfigured: Boolean = false /** * Configure a base URL for requests performed through the webClient. */ var baseUrl: String? = null override fun initialize(context: GenericApplicationContext) { super.initialize(context) init() if (!codecsConfigured) { StringCodecInitializer(true, false).initialize(context) ResourceCodecInitializer(true).initialize(context) } ReactiveWebClientBuilderInitializer(baseUrl).initialize(context) } /** * Configure codecs via a [dedicated DSL][WebFluxClientCodecDsl]. */ fun codecs(dsl: WebFluxClientCodecDsl.() -> Unit = {}) { WebFluxClientCodecDsl(dsl).initialize(context) codecsConfigured = true } class WebFluxClientCodecDsl(private val init: WebFluxClientCodecDsl.() -> Unit) : AbstractDsl() { override fun initialize(context: GenericApplicationContext) { super.initialize(context) init() } /** * Enable [org.springframework.core.codec.CharSequenceEncoder] and [org.springframework.core.codec.StringDecoder] */ fun string(textPlainOnly: Boolean = false) { StringCodecInitializer(true, textPlainOnly).initialize(context) } /** * Enable [org.springframework.http.codec.ResourceHttpMessageWriter] and [org.springframework.core.codec.ResourceDecoder] */ fun resource() { ResourceCodecInitializer(true).initialize(context) } /** * Register an `ObjectMapper` bean and configure a [Jackson](https://github.com/FasterXML/jackson) * JSON codec on WebFlux webClient via a [dedicated DSL][JacksonDsl]. * * Required dependencies can be retrieve using `org.springframework.boot:spring-boot-starter-json` * (included by default in `spring-boot-starter-webflux`). * * @sample org.springframework.fu.kofu.samples.jacksonDsl */ fun jackson(dsl: JacksonDsl.() -> Unit = {}) { JacksonDsl(dsl).initialize(context) JacksonJsonCodecInitializer(true).initialize(context) } /** * Enable [org.springframework.http.codec.protobuf.ProtobufEncoder] and [org.springframework.http.codec.protobuf.ProtobufDecoder] * * This codec requires Protobuf 3 or higher with the official `com.google.protobuf:protobuf-java` dependency, and * supports `application/x-protobuf` and `application/octet-stream`. */ fun protobuf() { ProtobufCodecInitializer(true).initialize(context) } /** * Enable [org.springframework.http.codec.FormHttpMessageWriter] and [org.springframework.http.codec.FormHttpMessageReader] */ fun form() { FormCodecInitializer(true).initialize(context) } /** * Enable [org.springframework.http.codec.multipart.MultipartHttpMessageWriter] and * [org.springframework.http.codec.multipart.MultipartHttpMessageReader] * * This codec requires Synchronoss NIO Multipart library via the `org.synchronoss.cloud:nio-multipart-parser` * dependency. */ fun multipart() { MultipartCodecInitializer(true).initialize(context) } } } /** * Declare a WebFlux webClient. * @see WebFluxClientDsl */ fun ConfigurationDsl.webClient(dsl: WebFluxClientDsl.() -> Unit = {}) { WebFluxClientDsl(dsl).initialize(context) }
39
null
139
1,673
c41806b1429dc31f75e2cb0f69ddd51a0bd8e9da
4,229
spring-fu
Apache License 2.0
app/src/main/java/com/chiccuts/utils/FirestoreUtil.kt
AhmetHTTP
798,452,333
false
{"Kotlin": 116882}
package com.chiccuts.utils import com.chiccuts.models.* import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.ListenerRegistration import kotlinx.coroutines.tasks.await object FirestoreUtil { val db = FirebaseFirestore.getInstance() private val listeners = mutableMapOf<String, ListenerRegistration>() fun getUser(userId: String, onComplete: (User?) -> Unit) { val listener = db.collection("users").document(userId).addSnapshotListener { document, error -> if (error != null) { onComplete(null) } else { onComplete(document?.toObject(User::class.java)) } } listeners[userId] = listener } fun getBarber(barberId: String, onComplete: (Barber?) -> Unit) { val listener = db.collection("barbers").document(barberId).addSnapshotListener { document, error -> if (error != null) { onComplete(null) } else { onComplete(document?.toObject(Barber::class.java)) } } listeners[barberId] = listener } fun getHairdresser(hairdresserId: String, onComplete: (Hairdresser?) -> Unit) { val listener = db.collection("hairdressers").document(hairdresserId).addSnapshotListener { document, error -> if (error != null) { onComplete(null) } else { onComplete(document?.toObject(Hairdresser::class.java)) } } listeners[hairdresserId] = listener } suspend fun addAppointment(appointment: Appointment, onComplete: (Boolean, String) -> Unit) { val appointmentRef = db.collection("appointments").document() appointment.appointmentId = appointmentRef.id try { val user = db.collection("users").document(appointment.userId).get().await().toObject(User::class.java) if (user != null) { appointment.userUsername = user.username appointment.userFirstName = user.firstName appointment.userLastName = user.lastName appointment.userProfilePictureUrl = user.profilePictureUrl var location: String? = "Default Location" if (appointment.barberId != null) { val barber = db.collection("barbers").document(appointment.barberId!!).get().await().toObject(Barber::class.java) if (barber != null) { appointment.salonName = barber.salonName appointment.rating = barber.rating appointment.businessProfilePictureUrl = barber.profilePictureUrl location = barber.location } } else if (appointment.hairdresserId != null) { val hairdresser = db.collection("hairdressers").document(appointment.hairdresserId!!).get().await().toObject(Hairdresser::class.java) if (hairdresser != null) { appointment.salonName = hairdresser.salonName appointment.rating = hairdresser.rating appointment.businessProfilePictureUrl = hairdresser.profilePictureUrl location = hairdresser.location } } appointment.location = location ?: "Default Location" appointmentRef.set(appointment).await() onComplete(true, "Appointment scheduled successfully") } else { onComplete(false, "Error fetching user details") } } catch (e: Exception) { onComplete(false, e.localizedMessage ?: "Error scheduling appointment") } } fun updateAppointment(appointmentId: String, newDetails: Map<String, Any>, onComplete: (Boolean, String) -> Unit) { db.collection("appointments").document(appointmentId).update(newDetails) .addOnSuccessListener { onComplete(true, "Appointment updated successfully") } .addOnFailureListener { exception -> onComplete(false, exception.localizedMessage ?: "Error updating appointment") } } fun cancelAppointment(appointmentId: String, onComplete: (Boolean, String) -> Unit) { db.collection("appointments").document(appointmentId).delete() .addOnSuccessListener { onComplete(true, "Appointment cancelled successfully") } .addOnFailureListener { exception -> onComplete(false, exception.localizedMessage ?: "Error cancelling appointment") } } fun getAppointments(userId: String, isBusinessOwner: Boolean, onComplete: (List<Appointment>, Exception?) -> Unit) { val collectionRef = db.collection("appointments") val appointments = mutableListOf<Appointment>() if (isBusinessOwner) { // Berber veya Kuaför için randevuları çek collectionRef.whereEqualTo("barberId", userId).get() .addOnSuccessListener { documents -> documents.forEach { document -> val appointment = document.toObject(Appointment::class.java) appointments.add(appointment) } // Kuaför randevuları için devam et }.continueWithTask { collectionRef.whereEqualTo("hairdresserId", userId).get() }.addOnSuccessListener { documents -> documents.forEach { document -> val appointment = document.toObject(Appointment::class.java) appointment.isRated = document.getBoolean("isRated") ?: false appointments.add(appointment) } onComplete(appointments, null) }.addOnFailureListener { e -> onComplete(emptyList(), e) } } else { // Normal kullanıcı için randevuları çek collectionRef.whereEqualTo("userId", userId).get() .addOnSuccessListener { documents -> documents.forEach { document -> val appointment = document.toObject(Appointment::class.java) appointment.isRated = document.getBoolean("isRated") ?: false appointments.add(appointment) } onComplete(appointments, null) }.addOnFailureListener { e -> onComplete(emptyList(), e) } } } fun getBarbersByLocation(location: String, onComplete: (List<Barber>) -> Unit) { db.collection("barbers").whereEqualTo("location", location).get() .addOnSuccessListener { documents -> val barbers = documents.toObjects(Barber::class.java) onComplete(barbers) } .addOnFailureListener { onComplete(emptyList()) } } fun getHairdressersByLocation(location: String, onComplete: (List<Hairdresser>) -> Unit) { db.collection("hairdressers").whereEqualTo("location", location).get() .addOnSuccessListener { documents -> val hairdressers = documents.toObjects(Hairdresser::class.java) onComplete(hairdressers) } .addOnFailureListener { onComplete(emptyList()) } } fun getBarbersSortedByRating(onComplete: (List<Barber>) -> Unit) { db.collection("barbers").orderBy("rating", com.google.firebase.firestore.Query.Direction.DESCENDING).get() .addOnSuccessListener { documents -> val barbers = documents.toObjects(Barber::class.java) onComplete(barbers) } .addOnFailureListener { onComplete(emptyList()) } } fun getHairdressersSortedByRating(onComplete: (List<Hairdresser>) -> Unit) { db.collection("hairdressers").orderBy("rating", com.google.firebase.firestore.Query.Direction.DESCENDING).get() .addOnSuccessListener { documents -> val hairdressers = documents.toObjects(Hairdresser::class.java) onComplete(hairdressers) } .addOnFailureListener { onComplete(emptyList()) } } fun updateProfilePictureUrl(userId: String, url: String, onComplete: (Boolean, String) -> Unit) { val userRef = db.collection("users").document(userId) userRef.update("profilePictureUrl", url) .addOnSuccessListener { onComplete(true, "Profile picture URL updated successfully for user") } .addOnFailureListener { val barberRef = db.collection("barbers").document(userId) barberRef.update("profilePictureUrl", url) .addOnSuccessListener { onComplete(true, "Profile picture URL updated successfully for barber") } .addOnFailureListener { val hairdresserRef = db.collection("hairdressers").document(userId) hairdresserRef.update("profilePictureUrl", url) .addOnSuccessListener { onComplete(true, "Profile picture URL updated successfully for hairdresser") } .addOnFailureListener { e -> onComplete(false, e.localizedMessage ?: "Error updating profile picture URL") } } } } fun removeAllListeners() { listeners.forEach { it.value.remove() } listeners.clear() } fun removeListenersForUser(userId: String) { listeners[userId]?.remove() listeners.remove(userId) } }
0
Kotlin
0
1
3568843d67f75e7f311047706f294080efc71e91
10,056
ChicCuts
MIT License
site/src/commonMain/kotlin/com/saitawngpha/blogmultiplatform/models/ApiListResponse.kt
saitawngpha
719,856,855
false
{"Kotlin": 258629, "Dockerfile": 2616, "CSS": 2102}
package com.saitawngpha.blogmultiplatform.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonContentPolymorphicSerializer import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.jsonObject /** * Created by တွင်ႉၾႃႉ on 08/11/2023. */ @Serializable(ApiListResponseSerializer::class) sealed class ApiListResponse { @Serializable @SerialName("idel") object Idel: ApiListResponse() @Serializable @SerialName("success") class Success( val data: List<PostWithoutDetails>): ApiListResponse() @Serializable @SerialName("error") class Error(val message: String): ApiListResponse() } @Serializable(ApiResponseSerializer::class) sealed class ApiResponse { @Serializable @SerialName("idel") object Idel: ApiResponse() @Serializable @SerialName("success") class Success( val data: Post): ApiResponse() @Serializable @SerialName("error") class Error(val message: String): ApiResponse() } object ApiListResponseSerializer: JsonContentPolymorphicSerializer<ApiListResponse>(ApiListResponse::class){ override fun selectDeserializer(element: JsonElement) = when { "data" in element.jsonObject -> ApiListResponse.Success.serializer() "message" in element.jsonObject -> ApiListResponse.Error.serializer() else -> ApiListResponse.Idel.serializer() } } object ApiResponseSerializer: JsonContentPolymorphicSerializer<ApiResponse>(ApiResponse::class){ override fun selectDeserializer(element: JsonElement) = when { "data" in element.jsonObject -> ApiResponse.Success.serializer() "message" in element.jsonObject -> ApiResponse.Error.serializer() else -> ApiResponse.Idel.serializer() } }
0
Kotlin
0
0
a09af5e758630cca111678817542adf8e51f3d11
1,814
blogmultiplatform
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsbookavideolinkapi/model/request/AmendVideoBookingRequest.kt
ministryofjustice
789,053,149
false
{"Kotlin": 1204892, "Shell": 11651, "Dockerfile": 1492}
package uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.model.request import com.fasterxml.jackson.annotation.JsonIgnore import io.swagger.v3.oas.annotations.media.Schema import jakarta.validation.Valid import jakarta.validation.constraints.AssertTrue import jakarta.validation.constraints.NotEmpty import jakarta.validation.constraints.NotNull import jakarta.validation.constraints.Size import java.net.URI @Schema( description = """ Amend an existing court or probation team meeting video link booking. """, ) data class AmendVideoBookingRequest( @field:NotNull(message = "The video link booking type is mandatory") @Schema(description = "The booking type", example = "COURT") val bookingType: BookingType?, @field:Valid @field:NotEmpty(message = "At least one prisoner must be supplied for a video link booking") @Schema( description = """ One or more prisoners associated with the video link booking. A probation booking should only ever have one prisoner whilst a court booking can have multiple e.g. for co-defendants. NOTE: CO-DEFENDANTS ARE NOT YET SUPPORTED BY THE SERVICE. """, ) val prisoners: List<PrisonerDetails>, @Schema(description = "The court hearing type is needed if booking type is COURT, otherwise null", example = "APPEAL") val courtHearingType: CourtHearingType? = null, @Schema( description = "The probation meeting type is needed if booking type is PROBATION, otherwise null", example = "PSR", ) val probationMeetingType: ProbationMeetingType? = null, @field:Size(max = 400, message = "Comments for the video link booking cannot not exceed {max} characters") @Schema( description = "Free text comments for the video link booking", example = "Waiting to hear on legal representation", ) val comments: String?, @field:Size(max = 120, message = "The video link should not exceed {max} characters") @Schema(description = "The video link for the appointment. Must be a valid URL", example = "https://video.here.com") val videoLinkUrl: String?, ) { @JsonIgnore @AssertTrue(message = "The court hearing type is mandatory for court bookings") private fun isInvalidCourtBooking() = (BookingType.COURT != bookingType) || (courtHearingType != null) @JsonIgnore @AssertTrue(message = "The probation probation meeting type is mandatory for probation bookings") private fun isInvalidProbationBooking() = (BookingType.PROBATION != bookingType) || (probationMeetingType != null) @JsonIgnore @AssertTrue(message = "The supplied video link for the appointment is not a valid URL") private fun isInvalidUrl() = videoLinkUrl == null || runCatching { URI(videoLinkUrl!!).toURL() }.isSuccess }
2
Kotlin
0
0
343a25d48d9ca61090c1d3248b2743c6e4b785e3
2,723
hmpps-book-a-video-link-api
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsbookavideolinkapi/model/request/AmendVideoBookingRequest.kt
ministryofjustice
789,053,149
false
{"Kotlin": 1204892, "Shell": 11651, "Dockerfile": 1492}
package uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.model.request import com.fasterxml.jackson.annotation.JsonIgnore import io.swagger.v3.oas.annotations.media.Schema import jakarta.validation.Valid import jakarta.validation.constraints.AssertTrue import jakarta.validation.constraints.NotEmpty import jakarta.validation.constraints.NotNull import jakarta.validation.constraints.Size import java.net.URI @Schema( description = """ Amend an existing court or probation team meeting video link booking. """, ) data class AmendVideoBookingRequest( @field:NotNull(message = "The video link booking type is mandatory") @Schema(description = "The booking type", example = "COURT") val bookingType: BookingType?, @field:Valid @field:NotEmpty(message = "At least one prisoner must be supplied for a video link booking") @Schema( description = """ One or more prisoners associated with the video link booking. A probation booking should only ever have one prisoner whilst a court booking can have multiple e.g. for co-defendants. NOTE: CO-DEFENDANTS ARE NOT YET SUPPORTED BY THE SERVICE. """, ) val prisoners: List<PrisonerDetails>, @Schema(description = "The court hearing type is needed if booking type is COURT, otherwise null", example = "APPEAL") val courtHearingType: CourtHearingType? = null, @Schema( description = "The probation meeting type is needed if booking type is PROBATION, otherwise null", example = "PSR", ) val probationMeetingType: ProbationMeetingType? = null, @field:Size(max = 400, message = "Comments for the video link booking cannot not exceed {max} characters") @Schema( description = "Free text comments for the video link booking", example = "Waiting to hear on legal representation", ) val comments: String?, @field:Size(max = 120, message = "The video link should not exceed {max} characters") @Schema(description = "The video link for the appointment. Must be a valid URL", example = "https://video.here.com") val videoLinkUrl: String?, ) { @JsonIgnore @AssertTrue(message = "The court hearing type is mandatory for court bookings") private fun isInvalidCourtBooking() = (BookingType.COURT != bookingType) || (courtHearingType != null) @JsonIgnore @AssertTrue(message = "The probation probation meeting type is mandatory for probation bookings") private fun isInvalidProbationBooking() = (BookingType.PROBATION != bookingType) || (probationMeetingType != null) @JsonIgnore @AssertTrue(message = "The supplied video link for the appointment is not a valid URL") private fun isInvalidUrl() = videoLinkUrl == null || runCatching { URI(videoLinkUrl!!).toURL() }.isSuccess }
2
Kotlin
0
0
343a25d48d9ca61090c1d3248b2743c6e4b785e3
2,723
hmpps-book-a-video-link-api
MIT License
app/src/test/java/ru/kabylin/andrey/vocabulator/ui/common/DefaultErrorResponder.kt
sysint64
140,518,543
false
{"Kotlin": 199316}
package ru.kabylin.andrey.vocabulator.ui.common import android.support.annotation.StringRes import junit.framework.Assert import ru.kabylin.andrey.vocabulator.* import ru.kabylin.andrey.vocabulator.client.AccessError import ru.kabylin.andrey.vocabulator.client.AccessErrorReason import ru.kabylin.andrey.vocabulator.ui.viewShouldBeVisible import ru.kabylin.andrey.vocabulator.views.ClientAppCompatActivity import ru.kabylin.andrey.vocabulator.views.ClientViewMediator class DefaultErrorsResponder : ErrorResponder { override fun onCriticalError(activity: ClientAppCompatActivity<ClientViewMediator>) { // TODO } override fun onVersionError(activity: ClientAppCompatActivity<ClientViewMediator>) { // TODO } override fun onVersionWarning(activity: ClientAppCompatActivity<ClientViewMediator>) { // TODO } private fun checkBottomBoardText(activity: ClientAppCompatActivity<ClientViewMediator>, @StringRes except: Int) { Assert.assertEquals( activity.getText(except), activity.errorsView.bottomBoardErrorTitleTextView!!.text ) } override fun onTooManyRequestError(activity: ClientAppCompatActivity<ClientViewMediator>) { activity.client.onError(AccessError(AccessErrorReason.TOO_MANY_REQUESTS)) viewShouldBeVisible(activity.errorsView.bottomBoardErrorView!!) checkBottomBoardText(activity, R.string.too_many_requests) } override fun onTimeoutError(activity: ClientAppCompatActivity<ClientViewMediator>) { activity.client.onError(AccessError(AccessErrorReason.TIMEOUT)) viewShouldBeVisible(activity.errorsView.bottomBoardErrorView!!) checkBottomBoardText(activity, R.string.time_is_out) } override fun onConnectionLostError(activity: ClientAppCompatActivity<ClientViewMediator>) { activity.client.onError(AccessError(AccessErrorReason.LOST_CONNECTION)) viewShouldBeVisible(activity.errorsView.bottomBoardErrorView!!) checkBottomBoardText(activity, R.string.lost_connection) } override fun onNotFound(activity: ClientAppCompatActivity<ClientViewMediator>) { activity.client.onError(AccessError(AccessErrorReason.NOT_FOUND)) viewShouldBeVisible(activity.errorsView.notFoundErrorView!!) } override fun onBadResponseError(activity: ClientAppCompatActivity<ClientViewMediator>) { activity.client.onError(AccessError(AccessErrorReason.BAD_RESPONSE)) viewShouldBeVisible(activity.errorsView.bottomBoardErrorView!!) checkBottomBoardText(activity, R.string.bad_response) } override fun onInternalServerError(activity: ClientAppCompatActivity<ClientViewMediator>) { activity.client.onError(AccessError(AccessErrorReason.INTERNAL_SERVER_ERROR)) viewShouldBeVisible(activity.errorsView.bottomBoardErrorView!!) checkBottomBoardText(activity, R.string.internal_server_error) } }
0
Kotlin
0
1
c6fbadf51f9ca638c1037f75306d11d7c6652444
2,952
vocabulator-android-client
MIT License
station-span/domain/src/main/java/org/mothdigital/stationdistancechecker/stationspan/domain/StationSpanRepository.kt
stanislawm97
779,379,195
false
{"Kotlin": 77179}
package org.mothdigital.stationdistancechecker.stationspan.domain import org.mothdigital.stationdistancechecker.stationspan.domain.model.Station interface StationSpanRepository { suspend fun getStation(id: Int): Station? suspend fun getStationByKeyword(keyword: String): List<Station> }
0
Kotlin
0
0
a9cdbb95335d2963b00ad4a3924eb7b4c8734f3c
296
StationDistanceChecker
MIT License
data/mediaplayer/src/main/java/com/mcgrady/xproject/data/mediaplayer/database/MusicDatabase.kt
mcgrady911
208,754,271
false
{"Gradle Kotlin DSL": 20, "Java Properties": 3, "Shell": 1, "Text": 2, "Ignore List": 17, "Batchfile": 1, "INI": 28, "Proguard": 8, "XML": 127, "Kotlin": 284, "Java": 5, "TOML": 1, "JSON": 5, "Gradle": 1, "EditorConfig": 1, "JAR Manifest": 1, "SQL": 1}
package com.mcgrady.xproject.data.mediaplayer.database import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.mcgrady.xproject.data.mediaplayer.database.dao.ChronologyDao import com.mcgrady.xproject.data.mediaplayer.database.dao.DownloadDao import com.mcgrady.xproject.data.mediaplayer.database.dao.FavoriteDao import com.mcgrady.xproject.data.mediaplayer.database.dao.QueueDao import com.mcgrady.xproject.data.mediaplayer.database.dao.RecentSearchDao import com.mcgrady.xproject.data.mediaplayer.database.dao.ServerDao import com.mcgrady.xproject.data.mediaplayer.database.entity.Chronology import com.mcgrady.xproject.data.mediaplayer.database.entity.Download import com.mcgrady.xproject.data.mediaplayer.database.entity.Favorite import com.mcgrady.xproject.data.mediaplayer.database.entity.Queue import com.mcgrady.xproject.data.mediaplayer.database.entity.RecentSearch import com.mcgrady.xproject.data.mediaplayer.database.entity.Server import com.mcgrady.xproject.data.mediaplayer.database.utils.DateConverters @Database( version = 1, entities = [Queue::class, Server::class, RecentSearch::class, Download::class, Chronology::class, Favorite::class], exportSchema = true ) @TypeConverters(value = [DateConverters::class]) abstract class MusicDatabase : RoomDatabase() { abstract fun queueDao(): QueueDao abstract fun serverDao(): ServerDao abstract fun recentSearchDao(): RecentSearchDao abstract fun downloadDao(): DownloadDao abstract fun chronologyDao(): ChronologyDao abstract fun favoriteDao(): FavoriteDao companion object { const val DB_NAME = "music_db" } }
1
null
1
1
8120d889c9cc471870cfef6fe553ca1585c6f9c7
1,688
xskeleton
Apache License 2.0
integration/common/datapool-sender/src/main/kotlin/io/holunda/polyflow/datapool/sender/DataEntryCommandSender.kt
holunda-io
135,994,693
false
null
package io.holunda.polyflow.datapool.sender import io.holunda.camunda.taskpool.api.business.* import org.axonframework.commandhandling.CommandResultMessage import org.axonframework.messaging.MetaData import java.util.function.BiFunction /** * Sends data entry commands. */ interface DataEntryCommandSender { /** * Sends command about data entry creation or update. * @param entryType type of entry. * @param entryId id of entry. * @param payload payload to send, * @param name human readable name of the data entry. * @param type human readable type of the entry. * @param state new state of the entry. * @param modification details about the change, will be added to protocol. * @param authorizationChanges changes of the authorizations. * @param correlations correlations to other data entries. * @param metaData meta data, will default to empty metadata. */ fun sendDataEntryChange( entryType: EntryType, entryId: EntryId, payload: Any = mapOf<String, Any>(), name: String = entryId, description: String? = null, type: String = entryType, state: DataEntryState = ProcessingType.UNDEFINED.of(), modification: Modification = Modification.now(), correlations: CorrelationMap = newCorrelations(), authorizationChanges: List<AuthorizationChange> = if (modification.username != null) listOf(AuthorizationChange.addUser(modification.username!!)) else listOf(), metaData: MetaData = MetaData.emptyInstance() ) /** * Sends command about data entry creation or update. * @param entryType type of entry. * @param entryId id of entry. * @param payload payload to send, * @param name human readable name of the data entry. * @param type human readable type of the entry. * @param state new state of the entry. */ fun sendDataEntryChange( entryType: EntryType, entryId: EntryId, payload: Any = mapOf<String, Any>(), name: String = entryId, description: String? = null, type: String = entryType, state: DataEntryState = ProcessingType.UNDEFINED.of() ) /** * Sends a data entry command. * @param command command to send. * @param metaData meta data, will default to empty metadata. */ fun sendDataEntryChange(command: CreateOrUpdateDataEntryCommand, metaData: MetaData = MetaData.emptyInstance()) } /** * Success handler for commands. */ interface DataEntryCommandSuccessHandler : BiFunction<Any, CommandResultMessage<out Any?>, Unit> /** * Error handler for commands. */ interface DataEntryCommandErrorHandler : BiFunction<Any, CommandResultMessage<out Any?>, Unit>
28
null
26
68
36735e6e1537fece1f75f82325bb2617321c86bd
2,627
camunda-bpm-taskpool
Apache License 2.0
adapter/unityads/src/main/java/org/bidon/unityads/impl/UnityAdsRewarded.kt
bidon-io
654,165,570
false
{"Kotlin": 1051963, "Java": 2186}
package org.bidon.unityads.impl import android.app.Activity import com.unity3d.ads.IUnityAdsLoadListener import com.unity3d.ads.IUnityAdsShowListener import com.unity3d.ads.UnityAds import com.unity3d.ads.UnityAdsShowOptions import org.bidon.sdk.adapter.AdAuctionParamSource import org.bidon.sdk.adapter.AdAuctionParams import org.bidon.sdk.adapter.AdEvent import org.bidon.sdk.adapter.AdSource import org.bidon.sdk.adapter.Mode import org.bidon.sdk.adapter.impl.AdEventFlow import org.bidon.sdk.adapter.impl.AdEventFlowImpl import org.bidon.sdk.auction.models.LineItem import org.bidon.sdk.config.BidonError import org.bidon.sdk.logs.analytic.AdValue import org.bidon.sdk.logs.analytic.Precision import org.bidon.sdk.logs.logging.impl.logError import org.bidon.sdk.logs.logging.impl.logInfo import org.bidon.sdk.stats.StatisticsCollector import org.bidon.sdk.stats.impl.StatisticsCollectorImpl import org.bidon.unityads.ext.asBidonError /** * Created by Aleksei Cherniaev on 02/03/2023. */ internal class UnityAdsInterstitial : AdSource.Interstitial<UnityAdsFullscreenAuctionParams>, Mode.Network, AdEventFlow by AdEventFlowImpl(), StatisticsCollector by StatisticsCollectorImpl() { private var lineItem: LineItem? = null override var isAdReadyToShow: Boolean = false override fun getAuctionParam(auctionParamsScope: AdAuctionParamSource): Result<AdAuctionParams> { return auctionParamsScope { UnityAdsFullscreenAuctionParams( lineItem = popLineItem(demandId) ?: error(BidonError.NoAppropriateAdUnitId) ) } } override fun load(adParams: UnityAdsFullscreenAuctionParams) { logInfo(TAG, "Starting with $adParams: $this") lineItem = adParams.lineItem val loadListener = object : IUnityAdsLoadListener { override fun onUnityAdsAdLoaded(placementId: String?) { logInfo(TAG, "onUnityAdsAdLoaded: $this") isAdReadyToShow = true getAd()?.let { emitEvent(AdEvent.Fill(it)) } } override fun onUnityAdsFailedToLoad( placementId: String?, error: UnityAds.UnityAdsLoadError?, message: String? ) { logInfo(TAG, "onUnityAdsFailedToLoad: placementId=$placementId, error=$error, message=$message") emitEvent(AdEvent.LoadFailed(BidonError.NoFill(demandId))) } } UnityAds.load(adParams.lineItem.adUnitId, loadListener) } override fun show(activity: Activity) { val showListener = object : IUnityAdsShowListener { override fun onUnityAdsShowFailure( placementId: String?, error: UnityAds.UnityAdsShowError?, message: String? ) { logError( tag = TAG, message = "onUnityAdsShowFailure: placementId=$placementId, error=$error, message=$message", error = error.asBidonError() ) emitEvent(AdEvent.ShowFailed(error.asBidonError())) } override fun onUnityAdsShowStart(placementId: String?) { logInfo(TAG, "onUnityAdsShowStart: placementId=$placementId") getAd()?.let { emitEvent(AdEvent.Shown(it)) emitEvent( AdEvent.PaidRevenue( ad = it, adValue = AdValue( adRevenue = (lineItem?.pricefloor ?: 0.0) / 1000.0, currency = AdValue.USD, precision = Precision.Estimated ) ) ) } } override fun onUnityAdsShowClick(placementId: String?) { logInfo(TAG, "onUnityAdsShowClick. placementId: $placementId") getAd()?.let { emitEvent(AdEvent.Clicked(it)) } } override fun onUnityAdsShowComplete( placementId: String?, state: UnityAds.UnityAdsShowCompletionState? ) { logInfo(TAG, "onUnityAdsShowComplete: placementId=$placementId, state=$state") getAd()?.let { emitEvent(AdEvent.Closed(it)) } } } UnityAds.show(activity, lineItem?.adUnitId, UnityAdsShowOptions(), showListener) isAdReadyToShow = false } override fun destroy() { // do nothing } } private const val TAG = "UnityAdsInterstitial"
0
Kotlin
0
0
ac4906b014f0901fd2ce2a3e593ef9d777cb0edc
4,694
bidon_sdk_android
Apache License 2.0
app/src/main/java/com/eatssu/android/data/usecase/PostReportUseCase.kt
EAT-SSU
601,871,281
false
{"Kotlin": 242143}
package com.eatssu.android.data.usecase import com.eatssu.android.base.BaseResponse import com.eatssu.android.data.dto.request.ReportRequest import com.eatssu.android.data.repository.ReportRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject class PostReportUseCase @Inject constructor( private val reportRepository: ReportRepository, ) { suspend operator fun invoke(body: ReportRequest): Flow<BaseResponse<Void>> = reportRepository.reportReview(body) }
26
Kotlin
0
9
d871fe1f48a2d21d82e68f27bd17f92d9538c832
492
Android
MIT License
src/main/kotlin/com/lynas/flywaydemo/FlywayDemoApplication.kt
lynas
279,045,013
false
null
package com.lynas.flywaydemo import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy import org.springframework.boot.runApplication import org.springframework.context.annotation.Bean @SpringBootApplication class FlywayDemoApplication { @Bean fun flywayMigrationStrategy(): FlywayMigrationStrategy? { return FlywayMigrationStrategy { } } } fun main(args: Array<String>) { runApplication<FlywayDemoApplication>(*args) }
0
Kotlin
0
0
41e9276b5166c7e0a7d325276d8ae99b534e4731
535
flyway-db-migration-demo
MIT License
app/src/main/java/com/example/pharmacologyapp/classes/Receptor.kt
JoshD898
758,310,198
false
{"Kotlin": 45619}
package com.example.pharmacologyapp.classes /** * Represents a receptor with a method to update its tension fraction. * * Tension fraction * maximal tension = tension provided from receptor * * @param name The name of the receptor. * @param agonists The list of agonists affecting the receptor. * @param antagonists The list of antagonists affecting the receptor. * @param tensionFraction The current fraction of maximal tension provided by the receptor. Default is 0.0f. */ data class Receptor( val name: String, val agonists: List<Drug>, val antagonists: List<Drug>, var tensionFraction: Float = 0.0f ) { fun updateTension() { for (agonist in agonists) { } tensionFraction = ( agonists[0].efficacy * totalConcentration(agonists) / (totalConcentration(agonists) + agonists[0].halfMax * (1 + totalConcentration(antagonists) / antagonists[0].dissociationConstant)) ) } private fun totalConcentration(drugs: List<Drug>): Float { var totalConcentration = 0.0f for (drug in drugs) { totalConcentration += drug.concentration } return totalConcentration } }
0
Kotlin
0
0
4ad411ed273f30b7f7de5393c9544e07e5362668
1,222
PCTH-Simulator
MIT License
app/src/main/java/com/example/android/politicalpreparedness/repository/CivicEngagementRepository.kt
mhmdcs
441,260,588
false
{"Kotlin": 49355}
package com.example.android.politicalpreparedness.repository import android.util.Log import androidx.lifecycle.LiveData import com.example.android.politicalpreparedness.database.ElectionDao import com.example.android.politicalpreparedness.network.CivicsApi import com.example.android.politicalpreparedness.network.models.Address import com.example.android.politicalpreparedness.network.models.Election import com.example.android.politicalpreparedness.representative.model.Representative import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.lang.Exception class CivicEngagementRepository( private val electionDao: ElectionDao, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) { val electionsFollowed: LiveData<List<Election>> = electionDao.getFollowedElections() val electionsUpcoming: LiveData<List<Election>> = electionDao.getAllElections() suspend fun getRepresentatives(address: Address) = withContext(ioDispatcher) { CivicsApi.retrofitService.getRepresentatives(address.zip) } suspend fun refreshElectionsData() = withContext(ioDispatcher) { try { val response = CivicsApi.retrofitService.getUpcomingElections() Log.i("Repository", "Is the list of products empty? $response") val elections = response.elections electionDao.insertAll(*elections.toTypedArray()) electionsFollowed } catch (error: Exception){ error.printStackTrace() Log.i("Repository", "Fetch data Error $error") } } suspend fun updateElection(election: Election) = withContext(ioDispatcher) { electionDao.updateElection(election) } suspend fun getElectionById(id: Int): Election { return electionDao.getElectionById(id) } suspend fun getVoterInfo(address: String, electionId: Int) = withContext(ioDispatcher) { CivicsApi.retrofitService.getVoterInfo(address, electionId) } suspend fun deleteElection(election: Election) = withContext(ioDispatcher) { electionDao.deleteElection(election) } suspend fun clear() = withContext(ioDispatcher) { electionDao.clear() } }
0
Kotlin
1
0
dcf328417cc092669b9df83e7bb98041aaceb63d
2,277
civic-engagement
Apache License 2.0
src/main/kotlin/org/wfanet/measurement/reporting/deploy/postgres/readers/MeasurementReader.kt
world-federation-of-advertisers
349,561,061
false
null
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.reporting.deploy.postgres.readers import kotlinx.coroutines.flow.firstOrNull import org.wfanet.measurement.common.db.r2dbc.ReadContext import org.wfanet.measurement.common.db.r2dbc.ResultRow import org.wfanet.measurement.common.db.r2dbc.boundStatement import org.wfanet.measurement.internal.reporting.Measurement import org.wfanet.measurement.internal.reporting.measurement class MeasurementReader { data class Result(val measurement: Measurement) private val baseSql: String = """ SELECT MeasurementConsumerReferenceId, MeasurementReferenceId, State, Failure, Result FROM Measurements """ fun translate(row: ResultRow): Result = Result(buildMeasurement(row)) /** * Reads a Measurement using reference IDs. * * @return null when the Measurement is not found. */ suspend fun readMeasurementByReferenceIds( readContext: ReadContext, measurementConsumerReferenceId: String, measurementReferenceId: String, ): Result? { val builder = boundStatement( baseSql + """ WHERE MeasurementConsumerReferenceId = $1 AND MeasurementReferenceId = $2 """ ) { bind("$1", measurementConsumerReferenceId) bind("$2", measurementReferenceId) } return readContext.executeQuery(builder).consume(::translate).firstOrNull() } private fun buildMeasurement(row: ResultRow): Measurement { return measurement { measurementConsumerReferenceId = row["MeasurementConsumerReferenceId"] measurementReferenceId = row["MeasurementReferenceId"] state = Measurement.State.forNumber(row["State"]) val failure: Measurement.Failure? = row.getProtoMessage("Failure", Measurement.Failure.parser()) if (failure != null) { this.failure = failure } val result: Measurement.Result? = row.getProtoMessage("Result", Measurement.Result.parser()) if (result != null) { this.result = result } } } }
88
null
11
36
b5c84f8051cd189e55f8c43ee2b9cc3f3a75e353
2,664
cross-media-measurement
Apache License 2.0
src/main/kotlin/online/bingzi/bilibili/video/internal/command/MainCommand.kt
BingZi-233
706,595,133
false
{"Kotlin": 61679}
package online.bingiz.bilibili.video.internal.command import online.bingiz.bilibili.video.internal.cache.baffleCache import online.bingiz.bilibili.video.internal.cache.cookieCache import online.bingiz.bilibili.video.internal.cache.midCache import online.bingiz.bilibili.video.internal.config.VideoConfig import online.bingiz.bilibili.video.internal.database.Database.Companion.setDataContainer import online.bingiz.bilibili.video.internal.engine.NetworkEngine import online.bingiz.bilibili.video.internal.helper.infoAsLang import taboolib.common.platform.ProxyCommandSender import taboolib.common.platform.ProxyPlayer import taboolib.common.platform.command.* import taboolib.common.platform.function.getProxyPlayer import taboolib.common.platform.function.submit import taboolib.module.chat.colored import taboolib.module.lang.sendInfoMessage import taboolib.platform.util.bukkitPlugin @CommandHeader( name = "bilibili-video", aliases = ["bv", "bilibilivideo"], permission = "BilibiliVideo.command.use", permissionDefault = PermissionDefault.TRUE ) object MainCommand { @CommandBody(permission = "BilibiliVideo.command.reload", permissionDefault = PermissionDefault.OP) val reload = subCommand { execute<ProxyCommandSender> { sender, _, _ -> sender.infoAsLang("CommandReloadSuccess") } } @CommandBody(permission = "BilibiliVideo.command.unbind", permissionDefault = PermissionDefault.OP) val unbind = subCommand { dynamic { suggestPlayers() execute<ProxyCommandSender> { sender, _, argument -> getProxyPlayer(argument)?.let { it.setDataContainer("mid", "") midCache.invalidate(it.uniqueId) cookieCache.invalidate(it.uniqueId) } ?: let { sender.infoAsLang("PlayerNotBindMid", argument) return@execute } sender.infoAsLang("PlayerUnbindSuccess", argument) } } } @CommandBody(aliases = ["open"], permission = "BilibiliVideo.command.login", permissionDefault = PermissionDefault.TRUE) val login = subCommand { // 可指定玩家启动登陆流程 // 可选参数 dynamic(optional = true, permission = "BilibiliVideo.command.login.sender") { suggestPlayers() execute<ProxyCommandSender> { _, _, argument -> getProxyPlayer(argument)?.let { player -> if (baffleCache.hasNext(player.name).not()) { player.infoAsLang("CommandBaffle") return@execute } NetworkEngine.generateBilibiliQRCodeUrl(player) } } } execute<ProxyPlayer> { sender, _, _ -> if (baffleCache.hasNext(sender.name).not()) { sender.infoAsLang("CommandBaffle") return@execute } NetworkEngine.generateBilibiliQRCodeUrl(sender) } } @CommandBody(permission = "BilibiliVideo.command.show", permissionDefault = PermissionDefault.TRUE) val show = subCommand { execute<ProxyPlayer> { sender, _, _ -> if (baffleCache.hasNext(sender.name).not()) { sender.infoAsLang("CommandBaffle") return@execute } // 因为是网络操作并且下层未进行异步操作 // 以防卡死主线程,故这里进行异步操作 submit(async = true) { NetworkEngine.getPlayerBindUserInfo(sender)?.let { sender.infoAsLang("CommandShowBindUserInfo", it.uname, it.mid) } ?: sender.infoAsLang("CommandShowBindUserInfoNotFound") } } } @CommandBody(permission = "BilibiliVideo.command.logout", permissionDefault = PermissionDefault.TRUE) val logout = subCommand { execute<ProxyPlayer> { sender, _, _ -> cookieCache.invalidate(sender.uniqueId) sender.infoAsLang("CommandLogoutSuccess") } } @CommandBody(aliases = ["use"], permission = "BilibiliVideo.command.receive", permissionDefault = PermissionDefault.TRUE) val receive = subCommand { dynamic(comment = "bv") { suggestion<ProxyPlayer> { _, _ -> VideoConfig.receiveMap.keys.toList() } execute<ProxyPlayer> { sender, _, argument -> if (baffleCache.hasNext(sender.name).not()) { sender.infoAsLang("CommandBaffle") return@execute } NetworkEngine.getTripleStatusShow(sender, argument) } literal("show", optional = true) { execute<ProxyPlayer> { sender, context, _ -> if (baffleCache.hasNext(sender.name).not()) { sender.infoAsLang("CommandBaffle") return@execute } submit(async = true) { NetworkEngine.getTripleStatusShow(sender, context["bv"]) } } } } } @CommandBody(permission = "BilibiliVideo.command.version", permissionDefault = PermissionDefault.OP) val version = subCommand { execute<ProxyCommandSender> { sender, _, _ -> sender.sendInfoMessage("&a&l插件名称 > ${bukkitPlugin.description.name}".colored()) sender.sendInfoMessage("&a&l插件版本 > ${bukkitPlugin.description.version}".colored()) sender.sendInfoMessage("&a&l插件作者 > ${bukkitPlugin.description.authors.joinToString(", ")}".colored()) } } }
1
Kotlin
5
6
f07a33937183492bff8072dac454e9fb49b8e6bc
5,656
BilibiliVideo
Creative Commons Zero v1.0 Universal
kotlin-mui-icons/src/main/generated/mui/icons/material/CircleTwoTone.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/CircleTwoTone") @file:JsNonModule package mui.icons.material @JsName("default") external val CircleTwoTone: SvgIconComponent
12
null
5
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
208
kotlin-wrappers
Apache License 2.0
ui/log/src/main/kotlin/me/gegenbauer/catspy/log/recent/RecentLogFiles.kt
Gegenbauer
609,809,576
false
null
package me.gegenbauer.catspy.log.recent import me.gegenbauer.catspy.concurrency.assertInMainThread import me.gegenbauer.catspy.file.gson import me.gegenbauer.catspy.utils.persistence.Preferences import me.gegenbauer.catspy.utils.persistence.UserPreferences import java.io.File import java.lang.ref.WeakReference /** * Manages the list of recently opened log files. * The list is stored in the [UserPreferences]. * Methods are not thread-safe and should be called from the main thread. */ object RecentLogFiles: UserPreferences.PreferencesChangeListener { private const val RECENT_FILE_STORE_KEY = "recent/recent_files" private const val MAX_RECENT_FILES = 30 private const val LAST_OPEN_DIR_STORE_KEY = "last_open_dir/log_files" private val recentFilesChangeListeners = mutableListOf<WeakReference<(List<RecentFile>) -> Unit>>() override val key: String get() = RECENT_FILE_STORE_KEY init { Preferences.addChangeListener(this) } fun getLastOpenDir(): String { return Preferences.getString(LAST_OPEN_DIR_STORE_KEY, "") } fun onNewFileOpen(file: String): List<RecentFile> { assertInMainThread() Preferences.putString(LAST_OPEN_DIR_STORE_KEY, file.substringBeforeLast(File.separator)) val recentFiles = getRecentFiles().toMutableList() val existingFile = recentFiles.find { it.path == file } recentFiles.remove(existingFile) val updatedFile = existingFile?.copy(lastOpenTime = System.currentTimeMillis()) ?: RecentFile(file) recentFiles.add(0, updatedFile) if (recentFiles.size > MAX_RECENT_FILES) { recentFiles.removeAt(recentFiles.size - 1) } saveRecentFiles(recentFiles) return recentFiles } fun getRecentFiles(): List<RecentFile> { assertInMainThread() return Preferences.getStringList(RECENT_FILE_STORE_KEY) .map { gson.fromJson(it, RecentFile::class.java) } } fun saveRecentFiles(files: List<RecentFile>) { assertInMainThread() Preferences.putStringList(RECENT_FILE_STORE_KEY, files.map { gson.toJson(it) }) } override fun onPreferencesChanged() { recentFilesChangeListeners.forEach { listenerRef -> listenerRef.get()?.invoke(getRecentFiles()) } } /** * Do not pass in an instance of an anonymous inner class created in a method, * it will be recycled after the method is completed. */ fun registerRecentFileChangeListener(listener: (List<RecentFile>) -> Unit) { assertInMainThread() recentFilesChangeListeners.add(WeakReference(listener)) } }
3
null
4
23
a868d118c42a9ab0984bfd51ea845d3dcfd16449
2,669
CatSpy
Apache License 2.0
app/src/androidTest/java/memoizrlabs/com/composable_styles/ViewStubbed.kt
memoizr
64,826,130
false
null
package memoizrlabs.com.composable_styles class ViewStubbed { }
0
Kotlin
0
0
2805901b43024f1a5822a1fe8a4686edd7bc4e7f
64
composable-styles-test
Apache License 2.0
app/src/main/kotlin/com/example/mingkangpan/learnrx2/network/BackendMock.kt
minkiapps
278,189,966
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 4, "XML": 23, "Kotlin": 24}
package com.example.mingkangpan.learnrx2.network import android.os.Looper import android.os.NetworkOnMainThreadException import com.example.mingkangpan.learnrx2.SimpleFuture import com.example.mingkangpan.learnrx2.logWithCurrentThread import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.schedulers.Schedulers import java.util.* import java.util.concurrent.Executors /** * Created by panmingk on 10/04/2017. */ class BackendMock : Backend { private val backendScheduler = Schedulers.from(Executors.newSingleThreadExecutor()) override fun nextRandomIntObs(): Observable<Int> = Observable.defer { Observable.just(work({ Thread.sleep(1000) Random().nextInt() }, "Generating random number")) } override fun nextRandomIntFuture() = SimpleFuture { work({ Thread.sleep(1000) Random().nextInt() }, "Generating random number") } override fun hashObject(any: Any): Observable<Int> = Observable.defer { Observable.just(work({ Thread.sleep(300) any.hashCode() }, "Hashing object: $any")) } override fun getScheduler(): Scheduler = backendScheduler private fun <T> work(work: () -> T, logMessage: String): T { checkIfNotMainThread() logWithCurrentThread(logMessage) return work.invoke() } private fun checkIfNotMainThread() { if (Thread.currentThread() === Looper.getMainLooper().thread) { throw NetworkOnMainThreadException() } } }
0
Kotlin
0
0
a7d4eafa8a49b4289fc678b0dc9a6d136af834cd
1,413
RxJava-Playground
Apache License 2.0
flank-scripts/src/main/kotlin/flank/scripts/cli/github/DownloadFlankCommand.kt
Flank
84,221,974
false
{"Kotlin": 1748173, "Java": 101254, "Swift": 41229, "Shell": 10674, "Objective-C": 10006, "Dart": 9705, "HTML": 7235, "Gherkin": 4210, "TypeScript": 2717, "Ruby": 2272, "JavaScript": 1764, "SCSS": 1365, "Batchfile": 1183, "EJS": 1061, "Go": 159}
package flank.scripts.cli.github import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.default import com.github.ajalt.clikt.parameters.options.option import flank.scripts.ops.github.downloadFlank import kotlinx.coroutines.runBlocking object DownloadFlankCommand : CliktCommand( name = "download_flank", help = "Downloads flank.jar with selected version." ) { private val version by option( "--version", "-v", help = "If the version not set, the latest version will be used." ) private val token by option(help = "Git Token").default("") override fun run() = runBlocking { downloadFlank(version, token) } }
64
Kotlin
115
676
b40904b4e74a670cf72ee53dc666fc3a801e7a95
708
flank
Apache License 2.0
features/fixtures/mazerunner/cxx-scenarios/src/main/java/com/bugsnag/android/mazerunner/scenarios/CXXThrowFromNoexcept.kt
bugsnag
2,406,783
false
{"Kotlin": 1012357, "Java": 502120, "C": 461672, "Gherkin": 181499, "C++": 50967, "Ruby": 28576, "CMake": 5170, "Shell": 3373, "Makefile": 3254}
package com.bugsnag.android.mazerunner.scenarios import android.content.Context import com.bugsnag.android.Configuration class CXXInvalidRethrow( config: Configuration, context: Context, eventMetadata: String? ) : Scenario(config, context, eventMetadata) { companion object { init { System.loadLibrary("cxx-scenarios") } } external fun crash() override fun startScenario() { super.startScenario() crash() } }
22
Kotlin
205
1,188
f5fd26b3cdeda9c4d4e221f55feb982a3fd97197
490
bugsnag-android
MIT License
main/src/main/java/org/mechdancer/ftclib/core/structure/composite/chassis/Mecanum.kt
MechDancer
146,752,676
false
null
package org.mechdancer.ftclib.core.structure.composite.chassis import org.mechdancer.ftclib.core.structure.monomeric.effector.Motor /** * Mecanum chassis */ open class Mecanum(override val name: String = "chassis", enable: Boolean = false, lfMotorDirection: Motor.Direction = Motor.Direction.REVERSE, lbMotorDirection: Motor.Direction = Motor.Direction.REVERSE, rfMotorDirection: Motor.Direction = Motor.Direction.FORWARD, rbMotorDirection: Motor.Direction = Motor.Direction.FORWARD, lfMotorName: String = "LF", lbMotorName: String = "LB", rfMotorName: String = "RF", rbMotorName: String = "RB" ) : Omnidirectinal(arrayOf( lfMotorName to lfMotorDirection, lbMotorName to lbMotorDirection, rfMotorName to rfMotorDirection, rbMotorName to rbMotorDirection), enable) { override fun Descartes.transform() = doubleArrayOf( +x - y - w, +x + y - w, +x + y + w, +x - y + w) }
0
Kotlin
0
3
6b9bbc0f90f83b45b9a2873c7617cd372bbbd57e
1,112
mechdancerlib
Do What The F*ck You Want To Public License
app/src/main/java/com/vadimulasevich/myweather/db/repositories/local/LocationRepository.kt
UlasevichVadim
505,810,972
false
null
package com.vadimulasevich.myweather.db.repositories.local import com.google.gson.GsonBuilder import com.vadimulasevich.myweather.db.local.models.LocationUser import java.io.File class LocationRepository { private var _locationUser = mutableListOf<LocationUser>() var locationUser: List<LocationUser> = _locationUser private set private val gson = GsonBuilder().apply { setPrettyPrinting() }.create() fun saveLocation() { val file = File("", "usersLocation.json") file.bufferedWriter().use { gson.toJson(_locationUser, it) locationUser = _locationUser } } fun loadLocation() { val file = File("", "usersLocation.json") if (file.exists()) { file.bufferedReader().use { val userArray = gson.fromJson(it, Array<LocationUser>::class.java) _locationUser = userArray.toMutableList() locationUser = _locationUser } } } fun setLocation(latitude: Double, longitude: Double) { val loc = LocationUser(latitude = latitude, longitude = longitude) _locationUser.add(loc) saveLocation() } fun getLocation(): LocationUser { loadLocation() return locationUser[0] } }
0
Kotlin
0
0
ff8cd90ebe488a0cf63f2899c7cff12bbeec63e8
1,306
MyWeather
The Unlicense
app/src/main/java/xyz/teamgravity/onlinevideoplayer/data/remote/dto/VideoDto.kt
raheemadamboev
491,407,304
false
{"Kotlin": 25232}
package xyz.teamgravity.onlinevideoplayer.data.remote.dto import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class VideoDto( @SerialName("id") val id: String, @SerialName("width") val width: Int, @SerialName("height") val height: Int, @SerialName("author") val author: String, @SerialName("url") val url: String, @SerialName("download_url") val downloadUrl: String )
0
Kotlin
0
6
dce404fe205f4d6b1e2f980ae619c38a630ced2c
442
online-video-player
Apache License 2.0
common/src/commonMain/kotlin/com/davidmatillacode/common/composeui/utils/Constants.kt
davidmatilla17
664,513,463
false
null
package com.davidmatillacode.common.composeui.utils import androidx.compose.material.Typography import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp //COLORS val primaryColor = Color(38, 60, 122) val accentColor = Color(102, 182, 255) val secondaryColor = Color(102, 182, 255) val grayLight = Color(232, 231, 230) val textColor = Color(22, 33, 47) val textHintColor = Color(150, 150, 150) val backgroundLight = Color(232, 232, 232) //TEXT SIZE val textSizeLarge = 24f val textSizeMediumLarge = 18f val textSizeMedium = 14f val textSizeSmall = 12f //PADDINGS val paddingLarge = 24.dp val paddingMedium = 16.dp val paddingSmall = 12.dp val paddingMinimun = 4.dp //DEFAULT FONT expect val defaultFont :FontFamily expect val defaultFontItalic :FontFamily expect val defaultFontBold :FontFamily expect val defaultFontBoldItalic :FontFamily expect val defaultTypography :Typography
0
Kotlin
0
0
c4026e240e4929d1e28babede9fc7f49939bd93f
954
appGestorHoras
MIT License
app/src/main/java/org/yrovas/linklater/ui/screens/saveBookmark/SaveBookmarkActivityDestination.kt
danielyrovas
756,319,329
false
{"Kotlin": 142745}
package org.yrovas.linklater.ui.screens.saveBookmark import kotlinx.serialization.Serializable import org.yrovas.linklater.ui.screens.EntryDestination @Serializable object SaveBookmarkActivityDestination : EntryDestination
2
Kotlin
0
20
3a8fd9e6e0d64bc3fa08482e9df20087cbb21290
225
linklater
MIT License
beagle/src/main/kotlin/br/com/zup/beagle/android/engine/mapper/FlexMapper.kt
ZupIT
391,144,851
false
null
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 br.com.zup.beagle.android.engine.mapper import android.view.View import br.com.zup.beagle.android.utils.dp import br.com.zup.beagle.android.utils.internalObserveBindChanges import br.com.zup.beagle.android.widget.RootView import br.com.zup.beagle.core.Style import br.com.zup.beagle.widget.core.EdgeValue import br.com.zup.beagle.widget.core.Size import br.com.zup.beagle.widget.core.UnitType import br.com.zup.beagle.widget.core.UnitValue import com.facebook.yoga.YogaAlign import com.facebook.yoga.YogaDisplay import com.facebook.yoga.YogaEdge import com.facebook.yoga.YogaFlexDirection import com.facebook.yoga.YogaJustify import com.facebook.yoga.YogaNode import com.facebook.yoga.YogaNodeFactory import com.facebook.yoga.YogaPositionType import com.facebook.yoga.YogaWrap internal class FlexMapper { fun makeYogaNode(style: Style): YogaNode = YogaNodeFactory.create().apply { flexDirection = makeYogaFlexDirection(style.flex?.flexDirection) ?: YogaFlexDirection.COLUMN wrap = makeYogaWrap(style.flex?.flexWrap) ?: YogaWrap.NO_WRAP justifyContent = makeYogaJustify(style.flex?.justifyContent) ?: YogaJustify.FLEX_START alignItems = makeYogaAlignItems(style.flex?.alignItems) ?: YogaAlign.STRETCH alignSelf = makeYogaAlignSelf(style.flex?.alignSelf) ?: YogaAlign.AUTO alignContent = makeYogaAlignContent(style.flex?.alignContent) ?: YogaAlign.FLEX_START if (style.flex?.flex == null) { flexGrow = style.flex?.grow?.toFloat() ?: 0.0f flexShrink = style.flex?.shrink?.toFloat() ?: 1.0f } style.flex?.flex?.toFloat()?.let { flex = it } display = YogaDisplay.FLEX positionType = makeYogaPositionType(style.positionType) ?: YogaPositionType.RELATIVE applyAttributes(style, this) } fun observeBindChangesFlex( style: Style, rootView: RootView, view: View, yogaNode: YogaNode, ) { if (style.display != null) { internalObserveBindChanges(rootView, view, style.display) { yogaNode.display = makeYogaDisplay(it) ?: YogaDisplay.FLEX view.requestLayout() } } } private fun applyAttributes(style: Style, yogaNode: YogaNode) { setWidth(style.size, yogaNode) setHeight(style.size, yogaNode) setMaxWidth(style.size, yogaNode) setMaxHeight(style.size, yogaNode) setMinWidth(style.size, yogaNode) setMinHeight(style.size, yogaNode) setBasis(style.flex?.basis, yogaNode) setAspectRatio(style.size?.aspectRatio, yogaNode) setMargin(style.margin, yogaNode) setPadding(style.padding, yogaNode) setPosition(style.position, yogaNode) } private fun setWidth(size: Size?, yogaNode: YogaNode) { size?.width?.let { width -> if (width.type == UnitType.REAL) { yogaNode.setWidth(width.value.dp().toFloat()) } else if (width.type == UnitType.PERCENT) { yogaNode.setWidthPercent(width.value.toFloat()) } } } private fun setHeight(size: Size?, yogaNode: YogaNode) { size?.height?.let { height -> if (height.type == UnitType.REAL) { yogaNode.setHeight(height.value.dp().toFloat()) } else if (height.type == UnitType.PERCENT) { yogaNode.setHeightPercent(height.value.toFloat()) } } } private fun setMaxWidth(size: Size?, yogaNode: YogaNode) { size?.maxWidth?.let { maxWidth -> if (maxWidth.type == UnitType.REAL) { yogaNode.setMaxWidth(maxWidth.value.dp().toFloat()) } else if (maxWidth.type == UnitType.PERCENT) { yogaNode.setMaxWidthPercent(maxWidth.value.toFloat()) } } } private fun setMaxHeight(size: Size?, yogaNode: YogaNode) { size?.maxHeight?.let { maxHeight -> if (maxHeight.type == UnitType.REAL) { yogaNode.setMaxHeight(maxHeight.value.dp().toFloat()) } else if (maxHeight.type == UnitType.PERCENT) { yogaNode.setMaxHeightPercent(maxHeight.value.toFloat()) } } } private fun setMinWidth(size: Size?, yogaNode: YogaNode) { size?.minWidth?.let { minWidth -> if (minWidth.type == UnitType.REAL) { yogaNode.setMinWidth(minWidth.value.dp().toFloat()) } else if (minWidth.type == UnitType.PERCENT) { yogaNode.setMinWidthPercent(minWidth.value.toFloat()) } } } private fun setMinHeight(size: Size?, yogaNode: YogaNode) { size?.minHeight?.let { minHeight -> if (minHeight.type == UnitType.REAL) { yogaNode.setMinHeight(minHeight.value.dp().toFloat()) } else if (minHeight.type == UnitType.PERCENT) { yogaNode.setMinHeightPercent(minHeight.value.toFloat()) } } } private fun setAspectRatio(aspectRatio: Double?, yogaNode: YogaNode) { aspectRatio?.let { yogaNode.aspectRatio = aspectRatio.toFloat() } } private fun setBasis(basis: UnitValue?, yogaNode: YogaNode) { when (basis?.type) { UnitType.REAL -> yogaNode.setFlexBasis(basis.value.toFloat()) UnitType.PERCENT -> yogaNode.setFlexBasisPercent(basis.value.toFloat()) else -> yogaNode.setFlexBasisAuto() } } private fun setMargin(margin: EdgeValue?, yogaNode: YogaNode) { applyEdgeValue(margin) { yogaEdge, unitValue -> if (unitValue.type == UnitType.REAL) { yogaNode.setMargin(yogaEdge, unitValue.value.dp().toFloat()) } else if (unitValue.type == UnitType.PERCENT) { yogaNode.setMarginPercent(yogaEdge, unitValue.value.toFloat()) } } } private fun setPadding(padding: EdgeValue?, yogaNode: YogaNode) { applyEdgeValue(padding) { yogaEdge, unitValue -> if (unitValue.type == UnitType.REAL) { yogaNode.setPadding(yogaEdge, unitValue.value.dp().toFloat()) } else if (unitValue.type == UnitType.PERCENT) { yogaNode.setPaddingPercent(yogaEdge, unitValue.value.toFloat()) } } } private fun setPosition(position: EdgeValue?, yogaNode: YogaNode) { applyEdgeValue(position) { yogaEdge, unitValue -> if (unitValue.type == UnitType.REAL) { yogaNode.setPosition(yogaEdge, unitValue.value.dp().toFloat()) } else if (unitValue.type == UnitType.PERCENT) { yogaNode.setPositionPercent(yogaEdge, unitValue.value.toFloat()) } } } private fun applyEdgeValue( edgeValue: EdgeValue?, finish: (yogaEdge: YogaEdge, unitValue: UnitValue) -> Unit, ) { edgeValue?.top?.let { finish(YogaEdge.TOP, it) } edgeValue?.left?.let { finish(YogaEdge.LEFT, it) } edgeValue?.right?.let { finish(YogaEdge.RIGHT, it) } edgeValue?.bottom?.let { finish(YogaEdge.BOTTOM, it) } edgeValue?.vertical?.let { finish(YogaEdge.VERTICAL, it) } edgeValue?.horizontal?.let { finish(YogaEdge.HORIZONTAL, it) } edgeValue?.all?.let { finish(YogaEdge.ALL, it) } } }
1
null
2
9
812a330777edd79a123495e9f678dc8f25a019f7
8,176
beagle-android
Apache License 2.0
tim/src/main/java/com/angcyo/tim/model/PushModel.kt
angcyo
229,037,684
false
{"Kotlin": 3502808, "JavaScript": 5542, "HTML": 1598}
package com.angcyo.tim.model import com.angcyo.core.lifecycle.LifecycleViewModel import com.angcyo.library.L import com.angcyo.tim.util.BrandUtil import com.angcyo.tim.util.PrivateConstants import com.angcyo.viewmodel.vmDataNull import com.tencent.imsdk.v2.V2TIMCallback import com.tencent.imsdk.v2.V2TIMManager import com.tencent.imsdk.v2.V2TIMOfflinePushConfig /** * * Email:<EMAIL> * @author angcyo * @date 2021/12/30 * Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved. */ class PushModel : LifecycleViewModel() { /**推送的token, 某些推送需要*/ val pushTokenData = vmDataNull<String>() /**将推送Token设置给TIM*/ fun setPushTokenToTIM(token: String?) { pushTokenData.value = token if (token.isNullOrEmpty()) { L.i("setPushTokenToTIM third token is empty") return } var v2TIMOfflinePushConfig: V2TIMOfflinePushConfig? = null v2TIMOfflinePushConfig = if (BrandUtil.isBrandXiaoMi()) { V2TIMOfflinePushConfig(PrivateConstants.XM_PUSH_BUZID, token) } else if (BrandUtil.isBrandHuawei()) { V2TIMOfflinePushConfig(PrivateConstants.HW_PUSH_BUZID, token) } else if (BrandUtil.isBrandMeizu()) { V2TIMOfflinePushConfig(PrivateConstants.MZ_PUSH_BUZID, token) } else if (BrandUtil.isBrandOppo()) { V2TIMOfflinePushConfig(PrivateConstants.OPPO_PUSH_BUZID, token) } else if (BrandUtil.isBrandVivo()) { V2TIMOfflinePushConfig(PrivateConstants.VIVO_PUSH_BUZID, token) } else if (BrandUtil.isGoogleServiceSupport()) { V2TIMOfflinePushConfig(PrivateConstants.GOOGLE_FCM_PUSH_BUZID, token) } else { return } V2TIMManager.getOfflinePushManager() .setOfflinePushConfig(v2TIMOfflinePushConfig, object : V2TIMCallback { override fun onError(code: Int, desc: String) { L.d("setOfflinePushToken err code = $code") } override fun onSuccess() { L.d("setOfflinePushToken success") } }) } }
0
Kotlin
4
4
438d0a123f5eea7cad0aeadd9ae9f2dca60d8142
2,129
UICoreEx
MIT License
idea/idea-core/src/org/jetbrains/kotlin/idea/core/script/configuration/cache/ScriptConfigurationFileAttributeCache.kt
android
263,405,600
false
null
/* * Copyright 2010-2019 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.idea.core.script.configuration.cache import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptConfigurationLoader import org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptConfigurationLoadingContext import org.jetbrains.kotlin.idea.core.script.scriptingDebugLog import org.jetbrains.kotlin.idea.core.util.cachedFileAttribute import org.jetbrains.kotlin.idea.core.util.readObject import org.jetbrains.kotlin.idea.core.util.writeObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition import org.jetbrains.kotlin.scripting.resolve.KtFileScriptSource import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper.FromCompilationConfiguration import java.io.Serializable import kotlin.script.experimental.api.ScriptCompilationConfiguration import kotlin.script.experimental.api.ScriptDiagnostic import kotlin.script.experimental.api.dependencies import kotlin.script.experimental.jvm.impl.toClassPathOrEmpty internal class ScriptConfigurationFileAttributeCache( val project: Project ) : ScriptConfigurationLoader { /** * todo(KT-34444): this should be changed to storing all roots in the persistent file cache */ override fun loadDependencies( isFirstLoad: Boolean, ktFile: KtFile, scriptDefinition: ScriptDefinition, context: ScriptConfigurationLoadingContext ): Boolean { if (!isFirstLoad) return false val virtualFile = ktFile.originalFile.virtualFile val fromFs = load(virtualFile) ?: return false context.saveNewConfiguration( virtualFile, ScriptConfigurationSnapshot( fromFs.inputs, fromFs.reports, FromCompilationConfiguration(KtFileScriptSource(ktFile), fromFs.configuration) ) ) return fromFs.inputs.isUpToDate(ktFile.project, virtualFile, ktFile) } private fun load( virtualFile: VirtualFile ): ScriptConfigurationSnapshotForFS? { val configurationSnapshot = virtualFile.scriptConfigurationSnapshot ?: return null scriptingDebugLog(virtualFile) { "configuration from fileAttributes = $configurationSnapshot" } val configuration = configurationSnapshot.configuration ?: return null if (!areDependenciesValid(virtualFile, configuration)) { save(virtualFile, null) return null } return configurationSnapshot } private fun areDependenciesValid(file: VirtualFile, configuration: ScriptCompilationConfiguration): Boolean { val classpath = configuration.get(ScriptCompilationConfiguration.dependencies).toClassPathOrEmpty() return classpath.all { if (it.exists()) { true } else { scriptingDebugLog(file) { "classpath root saved to file attribute doesn't exist: ${it.path}" } false } } } fun save(file: VirtualFile, value: ScriptConfigurationSnapshot?) { if (value == null) { file.scriptConfigurationSnapshot = null } else { file.scriptConfigurationSnapshot = ScriptConfigurationSnapshotForFS( value.inputs, value.reports, value.configuration?.configuration ) } } } private class ScriptConfigurationSnapshotForFS( val inputs: CachedConfigurationInputs, val reports: List<ScriptDiagnostic>, val configuration: ScriptCompilationConfiguration? ) : Serializable private var VirtualFile.scriptConfigurationSnapshot: ScriptConfigurationSnapshotForFS? by cachedFileAttribute( name = "kotlin-script-dependencies", version = 5, read = { readObject<ScriptConfigurationSnapshotForFS>() }, write = { writeObject<ScriptConfigurationSnapshotForFS>(it) } )
1
null
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
4,270
kotlin
Apache License 2.0
app/src/androidTest/java/com/anytypeio/anytype/features/relations/ObjectRelationListTest.kt
anyproto
647,371,233
false
null
package com.anytypeio.anytype.features.relations import android.os.Bundle import androidx.core.os.bundleOf import androidx.fragment.app.testing.FragmentScenario import androidx.fragment.app.testing.launchFragmentInContainer import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.hasDescendant import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.anytypeio.anytype.R import com.anytypeio.anytype.analytics.base.Analytics import com.anytypeio.anytype.core_models.Block import com.anytypeio.anytype.core_models.Id import com.anytypeio.anytype.core_models.Payload import com.anytypeio.anytype.core_models.Relation import com.anytypeio.anytype.core_models.ThemeColor import com.anytypeio.anytype.core_ui.extensions.dark import com.anytypeio.anytype.core_utils.const.DateConst import com.anytypeio.anytype.core_utils.ext.toTimeSeconds import com.anytypeio.anytype.domain.block.repo.BlockRepository import com.anytypeio.anytype.domain.config.Gateway import com.anytypeio.anytype.domain.misc.UrlBuilder import com.anytypeio.anytype.domain.`object`.UpdateDetail import com.anytypeio.anytype.domain.objects.StoreOfRelations import com.anytypeio.anytype.domain.relations.AddRelationToObject import com.anytypeio.anytype.domain.relations.AddToFeaturedRelations import com.anytypeio.anytype.domain.relations.DeleteRelationFromObject import com.anytypeio.anytype.domain.relations.RemoveFromFeaturedRelations import com.anytypeio.anytype.presentation.editor.Editor import com.anytypeio.anytype.presentation.objects.LockedStateProvider import com.anytypeio.anytype.presentation.relations.ObjectRelationListViewModelFactory import com.anytypeio.anytype.presentation.relations.providers.RelationListProvider import com.anytypeio.anytype.presentation.util.Dispatcher import com.anytypeio.anytype.test_utils.MockDataFactory import com.anytypeio.anytype.test_utils.utils.checkHasText import com.anytypeio.anytype.test_utils.utils.checkHasTextColor import com.anytypeio.anytype.test_utils.utils.checkIsRecyclerSize import com.anytypeio.anytype.test_utils.utils.onItemView import com.anytypeio.anytype.test_utils.utils.rVMatcher import com.anytypeio.anytype.test_utils.utils.resources import com.anytypeio.anytype.ui.relations.ObjectRelationListFragment import com.anytypeio.anytype.utils.CoroutinesTestRule import com.bartoszlipinski.disableanimationsrule.DisableAnimationsRule import java.text.SimpleDateFormat import java.util.* import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.MockitoAnnotations @RunWith(AndroidJUnit4::class) @LargeTest class ObjectRelationListTest { @get:Rule val animationsRule = DisableAnimationsRule() @get:Rule val coroutineTestRule = CoroutinesTestRule() @Mock lateinit var gateway: Gateway @Mock lateinit var repo: BlockRepository @Mock lateinit var dispatcher: Dispatcher<Payload> @Mock lateinit var analytics: Analytics @Mock lateinit var storeOfRelations: StoreOfRelations @Mock lateinit var relationListProvider: RelationListProvider @Mock lateinit var addRelationToObject: AddRelationToObject @Mock lateinit var lockedStateProvider: LockedStateProvider private lateinit var updateDetail: UpdateDetail private lateinit var addToFeaturedRelations: AddToFeaturedRelations private lateinit var removeFromFeaturedRelations: RemoveFromFeaturedRelations private lateinit var deleteRelationFromObject: DeleteRelationFromObject private val ctx = MockDataFactory.randomUuid() private val storage = Editor.Storage() lateinit var urlBuilder: UrlBuilder @Before fun setup() { MockitoAnnotations.openMocks(this) urlBuilder = UrlBuilder(gateway) updateDetail = UpdateDetail(repo) addToFeaturedRelations = AddToFeaturedRelations(repo) removeFromFeaturedRelations = RemoveFromFeaturedRelations(repo) deleteRelationFromObject = DeleteRelationFromObject(repo) TestObjectRelationListFragment.testVmFactory = ObjectRelationListViewModelFactory( lockedStateProvider = lockedStateProvider, relationListProvider = relationListProvider, urlBuilder = urlBuilder, dispatcher = dispatcher, updateDetail = updateDetail, addToFeaturedRelations = addToFeaturedRelations, removeFromFeaturedRelations = removeFromFeaturedRelations, deleteRelationFromObject = deleteRelationFromObject, analytics = analytics, storeOfRelations = storeOfRelations, addRelationToObject = addRelationToObject ) } @Test(expected = RuntimeException::class) fun shouldThrowAnExceptionIfArgsNotProvided() { launchFragment(bundleOf()) } @Test fun shouldDisplayOneRelationWithoutValueInsideOtherRelationsSection() { // SETUP val name = "Description" val relation = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.LONG_TEXT, source = Relation.Source.values().random(), name = name ) runBlocking { storage.relations.update( listOf(relation) ) } launchFragment(bundleOf( ObjectRelationListFragment.ARG_CTX to ctx, ObjectRelationListFragment.ARG_MODE to ObjectRelationListFragment.MODE_LIST )) // TESTING with(R.id.recycler.rVMatcher()) { onItemView(0, R.id.tvSectionName).checkHasText(R.string.other_relations) onItemView(1, R.id.tvRelationTitle).checkHasText(name) onItemView(1, R.id.tvRelationValue).checkHasText("") checkIsRecyclerSize(2) } } @Test fun shouldDisplayOnlyFirstRelationBecauseSecondIsHiddenInsideOtherRelationsSection() { // SETUP val name1 = "Description" val name2 = "Identifier" val relation1 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.LONG_TEXT, source = Relation.Source.values().random(), isHidden = true, name = name1 ) val relation2 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.LONG_TEXT, source = Relation.Source.values().random(), name = name2 ) runBlocking { storage.relations.update( listOf(relation1, relation2) ) } launchFragment(bundleOf( ObjectRelationListFragment.ARG_CTX to ctx, ObjectRelationListFragment.ARG_MODE to ObjectRelationListFragment.MODE_LIST )) // TESTING with(R.id.recycler.rVMatcher()) { onItemView(0, R.id.tvSectionName).checkHasText(R.string.other_relations) onItemView(1, R.id.tvRelationTitle).checkHasText(name2) onItemView(1, R.id.tvRelationValue).checkHasText("") checkIsRecyclerSize(2) } } @Test fun shouldDisplayTwoRelationsWithoutValueInsideOtherRelationsSection() { // SETUP val name1 = "Description" val name2 = "Comment" val relation1 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.LONG_TEXT, source = Relation.Source.values().random(), name = name1 ) val relation2 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.LONG_TEXT, source = Relation.Source.values().random(), name = name2 ) runBlocking { storage.relations.update( listOf(relation1, relation2) ) } launchFragment(bundleOf( ObjectRelationListFragment.ARG_CTX to ctx, ObjectRelationListFragment.ARG_MODE to ObjectRelationListFragment.MODE_LIST )) // TESTING with(R.id.recycler.rVMatcher()) { onItemView(0, R.id.tvSectionName).checkHasText(R.string.other_relations) onItemView(1, R.id.tvRelationTitle).checkHasText(name1) onItemView(1, R.id.tvRelationValue).checkHasText("") onItemView(2, R.id.tvRelationTitle).checkHasText(name2) onItemView(2, R.id.tvRelationValue).checkHasText("") checkIsRecyclerSize(3) } } @Test fun shouldDisplayTwoRelationsWithValuesInsideOtherRelationsSection() { // SETUP val name1 = "Description" val name2 = "Comment" val value1 = "A mountain is an elevated portion of the Earth's crust, generally with steep sides that show significant exposed bedrock." val value2 = "We've never seen that mountain before." val relation1 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.LONG_TEXT, source = Relation.Source.values().random(), name = name1 ) val relation2 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.LONG_TEXT, source = Relation.Source.values().random(), name = name2 ) val relations = listOf(relation1, relation2) val details = Block.Details( mapOf( ctx to Block.Fields( mapOf( relation1.key to value1, relation2.key to value2, ) ) ) ) runBlocking { storage.relations.update(relations) storage.details.update(details) } launchFragment( bundleOf( ObjectRelationListFragment.ARG_CTX to ctx, ObjectRelationListFragment.ARG_MODE to ObjectRelationListFragment.MODE_LIST ) ) // TESTING with(R.id.recycler.rVMatcher()) { onItemView(0, R.id.tvSectionName).checkHasText(R.string.other_relations) onItemView(1, R.id.tvRelationTitle).checkHasText(name1) onItemView(1, R.id.tvRelationValue).checkHasText(value1) onItemView(2, R.id.tvRelationTitle).checkHasText(name2) onItemView(2, R.id.tvRelationValue).checkHasText(value2) checkIsRecyclerSize(3) } } @Test fun shouldDisplayTwoObjectRelationsWithNameAndAvatarInitialsInsideOtherRelationsSection() { // SETUP val name1 = "Assignee" val target1: Id = MockDataFactory.randomUuid() val username1 = "Konstantin" val name2 = "Created by" val target2: Id = MockDataFactory.randomUuid() val username2 = "Roman" val relation1 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.OBJECT, source = Relation.Source.values().random(), name = name1 ) val relation2 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.OBJECT, source = Relation.Source.values().random(), name = name2 ) val relations = listOf(relation1, relation2) val details = Block.Details( mapOf( ctx to Block.Fields( mapOf( relation1.key to target1, relation2.key to target2, ) ), target1 to Block.Fields( mapOf( Block.Fields.NAME_KEY to username1 ) ), target2 to Block.Fields( mapOf( Block.Fields.NAME_KEY to username2 ) ) ) ) runBlocking { storage.relations.update(relations) storage.details.update(details) } launchFragment(bundleOf( ObjectRelationListFragment.ARG_CTX to ctx, ObjectRelationListFragment.ARG_MODE to ObjectRelationListFragment.MODE_LIST )) // TESTING with(R.id.recycler.rVMatcher()) { onItemView(0, R.id.tvSectionName).checkHasText(R.string.other_relations) onItemView(1, R.id.tvRelationTitle).checkHasText(name1) onItemView(1, R.id.obj0).check(matches(hasDescendant(withText(username1)))) onItemView(2, R.id.tvRelationTitle).checkHasText(name2) onItemView(2, R.id.obj0).check(matches(hasDescendant(withText(username2)))) checkIsRecyclerSize(3) } } @Test fun shouldDisplayTwoDateRelationsInsideOtherRelationsSection() { // SETUP val format = SimpleDateFormat(DateConst.DEFAULT_DATE_FORMAT, Locale.getDefault()) val name1 = "Date of birth" val date1 = System.currentTimeMillis() val date1Screen = format.format(Date(date1)) val name2 = "Last modified at" val date2 = System.currentTimeMillis() val date2Screen = format.format(Date(date2)) val relation1 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.DATE, source = Relation.Source.values().random(), name = name1, ) val relation2 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.DATE, source = Relation.Source.values().random(), name = name2 ) val relations = listOf(relation1, relation2) val details = Block.Details( mapOf( ctx to Block.Fields( mapOf( relation1.key to date1.toTimeSeconds(), relation2.key to date2.toTimeSeconds(), ) ) ) ) runBlocking { storage.relations.update(relations) storage.details.update(details) } launchFragment(bundleOf( ObjectRelationListFragment.ARG_CTX to ctx, ObjectRelationListFragment.ARG_MODE to ObjectRelationListFragment.MODE_LIST )) // TESTING with(R.id.recycler.rVMatcher()) { onItemView(0, R.id.tvSectionName).checkHasText(R.string.other_relations) onItemView(1, R.id.tvRelationTitle).checkHasText(name1) onItemView(1, R.id.tvRelationValue).checkHasText(date1Screen) onItemView(2, R.id.tvRelationTitle).checkHasText(name2) onItemView(2, R.id.tvRelationValue).checkHasText(date2Screen) checkIsRecyclerSize(3) } } @Test fun shouldDisplayTwoStatusRelationsInsideOtherRelationsSection() { // SETUP val color1 = ThemeColor.RED val color2 = ThemeColor.TEAL val option1 = Relation.Option( id = MockDataFactory.randomUuid(), text = "In progress", color = color1.code ) val option2 = Relation.Option( id = MockDataFactory.randomUuid(), text = "Done", color = color2.code ) val name1 = "Status 1" val name2 = "Status 2" val relation1 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.STATUS, source = Relation.Source.values().random(), name = name1, selections = listOf(option1) ) val relation2 = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.STATUS, source = Relation.Source.values().random(), name = name2, selections = listOf(option2) ) val relations = listOf(relation1, relation2) val details = Block.Details( mapOf( ctx to Block.Fields( mapOf( relation1.key to option1.id, relation2.key to option2.id, ) ) ) ) runBlocking { storage.relations.update(relations) storage.details.update(details) } launchFragment(bundleOf( ObjectRelationListFragment.ARG_CTX to ctx, ObjectRelationListFragment.ARG_MODE to ObjectRelationListFragment.MODE_LIST )) // TESTING with(R.id.recycler.rVMatcher()) { onItemView(0, R.id.tvSectionName).checkHasText(R.string.other_relations) onItemView(1, R.id.tvRelationTitle).checkHasText(name1) onItemView(1, R.id.tvRelationValue).checkHasText(option1.text) onItemView(1, R.id.tvRelationValue).checkHasTextColor(resources.dark(color1)) onItemView(2, R.id.tvRelationTitle).checkHasText(name2) onItemView(2, R.id.tvRelationValue).checkHasText(option2.text) onItemView(2, R.id.tvRelationValue).checkHasTextColor(resources.dark(color2)) checkIsRecyclerSize(3) } } @Test fun shouldDisplayFourTagRelationsInsideOtherRelationsSection() { // SETUP val color1 = ThemeColor.RED val color2 = ThemeColor.TEAL val color3 = ThemeColor.ICE val color4 = ThemeColor.PURPLE val name = "Role" val option1 = Relation.Option( id = MockDataFactory.randomUuid(), text = "Essayist", color = color1.code ) val option2 = Relation.Option( id = MockDataFactory.randomUuid(), text = "Journalist", color = color2.code ) val option3 = Relation.Option( id = MockDataFactory.randomUuid(), text = "Politik", color = color3.code ) val option4 = Relation.Option( id = MockDataFactory.randomUuid(), text = "Critic", color = color4.code ) val relation = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.TAG, source = Relation.Source.values().random(), name = name, selections = listOf(option1, option2, option3, option4) ) val relations = listOf(relation) val details = Block.Details( mapOf( ctx to Block.Fields( mapOf( relation.key to listOf(option1.id, option2.id, option3.id, option4.id) ) ) ) ) runBlocking { storage.relations.update(relations) storage.details.update(details) } launchFragment(bundleOf( ObjectRelationListFragment.ARG_CTX to ctx, ObjectRelationListFragment.ARG_MODE to ObjectRelationListFragment.MODE_LIST )) // TESTING with(R.id.recycler.rVMatcher()) { onItemView(0, R.id.tvSectionName).checkHasText(R.string.other_relations) onItemView(1, R.id.tvRelationTitle).checkHasText(name) onItemView(1, R.id.tag0).check(matches((withText(option1.text)))) onItemView(1, R.id.tag1).check(matches((withText(option2.text)))) onItemView(1, R.id.tag2).check(matches((withText(option3.text)))) onItemView(1, R.id.tag3).check(matches((withText(option4.text)))) checkIsRecyclerSize(2) } } @Test fun shouldDisplayTwoFileRelationsInsideOtherRelationsSection() { // SETUP val name = "Attachement" val relation = Relation( key = MockDataFactory.randomUuid(), format = Relation.Format.FILE, source = Relation.Source.values().random(), name = name, selections = emptyList() ) val relations = listOf(relation) val file1 = MockDataFactory.randomUuid() val file2 = MockDataFactory.randomUuid() val details = Block.Details( mapOf( ctx to Block.Fields( mapOf( relation.key to listOf(file1, file2) ) ), file1 to Block.Fields( mapOf( "name" to "Document", "ext" to "pdf", "mime" to "application/pdf" ) ), file2 to Block.Fields( mapOf( "name" to "Image", "ext" to "jpg", "mime" to "image/jpeg" ) ) ) ) runBlocking { storage.relations.update(relations) storage.details.update(details) } launchFragment(bundleOf( ObjectRelationListFragment.ARG_CTX to ctx, ObjectRelationListFragment.ARG_MODE to ObjectRelationListFragment.MODE_LIST )) // TESTING with(R.id.recycler.rVMatcher()) { onItemView(0, R.id.tvSectionName).checkHasText(R.string.other_relations) onItemView(1, R.id.tvRelationTitle).checkHasText(name) onItemView(1, R.id.file0).check(matches(hasDescendant(withText("Document")))) onItemView(1, R.id.file1).check(matches(hasDescendant(withText("Image")))) checkIsRecyclerSize(2) } } private fun launchFragment(args: Bundle): FragmentScenario<TestObjectRelationListFragment> { return launchFragmentInContainer( fragmentArgs = args, themeResId = R.style.AppTheme ) } }
45
null
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
22,146
anytype-kotlin
RSA Message-Digest License
app/src/main/java/com/soft507/travelsuggest/model/PersonalCenterViewModel.kt
rickey0827
274,230,136
false
null
package com.soft507.travelsuggest.model import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.soft507.travelsuggest.bean.UserBean /** * @author LRQ-Pro * @description: * @date : 2020/6/6 2:46 */ class PersonalCenterViewModel : ViewModel() { val userBean = MutableLiveData<UserBean>() fun getUserInfo() { } }
1
Kotlin
1
3
9615d375a67bd23156b5a390f799336aa14a1219
363
TravelSuggest
Apache License 2.0
app/src/main/java/com/opsc/timesync/ui/home/HomeViewModel.kt
johanngeustyn
648,824,203
false
null
package com.opsc.timesync.ui.home import Category import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.TaskCompletionSource import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase class HomeViewModel : ViewModel() { private val firestore: FirebaseFirestore = Firebase.firestore private val auth: FirebaseAuth = FirebaseAuth.getInstance() private val userId: String = auth.currentUser?.uid ?: "" private val _timesheets = MutableLiveData<List<Timesheet>>() val timesheets: LiveData<List<Timesheet>> get() = _timesheets private val _categoryMap = MutableLiveData<Map<String, Category>>() val categoryMap: LiveData<Map<String, Category>> get() = _categoryMap init { fetchTimesheets() } fun fetchTimesheets() { firestore.collection("timesheetEntries") .whereEqualTo("user", userId) .get() .addOnSuccessListener { querySnapshot -> try { val timesheetList = mutableListOf<Timesheet>() val categoryMap = mutableMapOf<String, Category>() val fetchCategoryTasks = mutableListOf<Task<DocumentSnapshot>>() for (document in querySnapshot) { val entry = document.toObject(Timesheet::class.java) val categoryRef = entry.category if (categoryRef != null) { val fetchTask = fetchCategory(categoryRef) fetchCategoryTasks.add(fetchTask) fetchTask.continueWith { categoryTask -> val categorySnapshot = categoryTask.result // Extract category data manually val categoryId = categorySnapshot?.id ?: "" val categoryName = categorySnapshot?.get("name") as? String ?: "" val category = Category(categoryId, categoryName) categoryMap[categoryId] = category entry.category = categoryRef // Pass the category reference entry.categoryName = categoryName // Set the category name directly in Timesheet Log.d("fetchTimesheet:","${categoryName}") timesheetList.add(entry) entry.photoUrl = document.getString("photoUrl") if (timesheetList.size == querySnapshot.size()) { if (fetchCategoryTasks.all { it.isComplete }) { _timesheets.value = timesheetList _categoryMap.value = categoryMap } } } } else { timesheetList.add(entry) entry.photoUrl = document.getString("photoUrl") if (timesheetList.size == querySnapshot.size()) { _timesheets.value = timesheetList _categoryMap.value = categoryMap } } } } catch (e: Exception) { Log.e("fetchTimesheets:", "Exception: ${e.message}", e) } } .addOnFailureListener { exception -> Log.e("fetchTimesheets:", "Failure: ${exception.message}", exception) } } private fun fetchCategory(categoryRef: DocumentReference): Task<DocumentSnapshot> { val completionSource = TaskCompletionSource<DocumentSnapshot>() categoryRef.get() .addOnSuccessListener { categorySnapshot -> completionSource.setResult(categorySnapshot) Log.d("fetchCategory categoryName:","${categorySnapshot.get("name")}") } .addOnFailureListener { exception -> completionSource.setException(exception) } return completionSource.task } }
0
Kotlin
0
0
3d93f597b803c66247b16d1ea7a06efb6d50c9da
4,649
TimeSync
MIT License
app/src/main/java/com/raktimyoddha/clapapp/MainActivity.kt
RaktimYoddha
507,264,097
false
null
package com.raktimyoddha.clapapp import android.media.MediaPlayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class MainActivity : AppCompatActivity() { private lateinit var mediaPlayer: MediaPlayer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val button1 = findViewById<Button>(R.id.b1) button1.setOnClickListener{ mediaPlayer = MediaPlayer.create(this,R.raw.applauding) mediaPlayer.start() } val button2 = findViewById<Button>(R.id.b2) button2.setOnClickListener{ mediaPlayer = MediaPlayer.create(this,R.raw.trumpate) mediaPlayer.start() } val button3 = findViewById<Button>(R.id.b3) button3.setOnClickListener{ mediaPlayer = MediaPlayer.create(this,R.raw.carhorn) mediaPlayer.start() } val button4 = findViewById<Button>(R.id.b4) button4.setOnClickListener{ mediaPlayer = MediaPlayer.create(this,R.raw.mario) mediaPlayer.start() } } }
0
Kotlin
0
0
a663af8f7b3d5fb110743a246241ec602a0d4a37
1,204
MultiButtonAudio
Apache License 2.0
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package92/Foo09213.kt
yamamotoj
163,851,411
false
null
package com.github.yamamotoj.singlemoduleapp.package92 class Foo09213 { fun method0() { Foo09212().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
355
android_multi_module_experiment
Apache License 2.0
app/src/test/java/com/aouerfelli/subwatcher/database/SubredditEntityQueriesTest.kt
aouerfelli
209,374,944
false
null
package com.aouerfelli.subwatcher.database import com.aouerfelli.subwatcher.DaggerTestComponent import com.aouerfelli.subwatcher.repository.SubredditIconUrl import com.aouerfelli.subwatcher.repository.SubredditLastPosted import com.aouerfelli.subwatcher.repository.SubredditName import com.aouerfelli.subwatcher.util.CoroutineTestRule import kotlinx.coroutines.ExperimentalCoroutinesApi import okhttp3.mockwebserver.MockWebServer import org.junit.Assert.assertEquals import org.junit.Assert.assertThrows import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.jupiter.api.AfterEach import javax.inject.Inject @OptIn(ExperimentalCoroutinesApi::class) class SubredditEntityQueriesTest { @get:Rule val coroutineTestRule = CoroutineTestRule() @Inject lateinit var subredditEntityQueries: SubredditQueries @Before fun startUp() { DaggerTestComponent.factory().create( coroutineTestRule.dispatcher, MockWebServer() // Unused ).inject(this) } @AfterEach fun deleteAllSubreddits() { subredditEntityQueries.deleteAll() } @Test fun `select and delete all subreddits`() { assertEquals(emptyList<Subreddit>(), subredditEntityQueries.selectAll().executeAsList()) subredditEntityQueries.insert(subreddit) assertEquals(listOf(subreddit), subredditEntityQueries.selectAll().executeAsList()) subredditEntityQueries.deleteAll() assertEquals(emptyList<Subreddit>(), subredditEntityQueries.selectAll().executeAsList()) } @Test fun `select and delete subreddit`() { assertEquals(null, subredditEntityQueries.select(subreddit.name).executeAsOneOrNull()) subredditEntityQueries.insert(subreddit) assertEquals(subreddit, subredditEntityQueries.select(subreddit.name).executeAsOneOrNull()) subredditEntityQueries.delete(subreddit.name) assertEquals(null, subredditEntityQueries.select(subreddit.name).executeAsOneOrNull()) } @Test fun `insert duplicate key constraint failure`() { val subredditCopy = subreddit.copy( name = SubredditName(subreddit.name.name.uppercase()), iconUrl = null, lastPosted = null ) subredditEntityQueries.insert(subreddit) assertThrows(java.sql.SQLException::class.java) { subredditEntityQueries.insert(subredditCopy) } } @Test fun `select all ordering`() { val subreddits = listOf( subreddit.copy(name = SubredditName("A")), subreddit.copy(name = SubredditName("b")), subreddit.copy(name = SubredditName("C")) ) subreddits.asReversed().forEach(subredditEntityQueries::insert) assertEquals(subreddits, subredditEntityQueries.selectAll().executeAsList()) } @Test fun `update existing`() { subredditEntityQueries.insert(subreddit) val updatedSubreddit = subreddit.copy(iconUrl = null, lastPosted = null) subredditEntityQueries.update( name = subreddit.name, iconUrl = updatedSubreddit.iconUrl, lastPosted = updatedSubreddit.lastPosted ) assertEquals(updatedSubreddit, subredditEntityQueries.select(subreddit.name).executeAsOne()) } @Test fun `update not inserted`() { subredditEntityQueries.update(name = subreddit.name, iconUrl = null, lastPosted = null) assertEquals(null, subredditEntityQueries.select(subreddit.name).executeAsOneOrNull()) } companion object { private val subreddit = Subreddit( name = SubredditName("subreddit"), iconUrl = SubredditIconUrl("https://icon_img.png"), lastPosted = SubredditLastPosted(123456789) ) } }
2
Kotlin
1
2
408c0498982e5fd63f1f6c38b0a15909982f046f
3,541
subwatcher
Apache License 2.0
app/src/main/java/com/samedtemiz/fitlife/ui/screens/auth/RegisterScreen.kt
SamedTemiz
675,047,674
false
{"Kotlin": 199370}
package com.samedtemiz.fitlife.ui.screens.auth import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.CutCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.blur import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import com.example.compose.BurntSienna_500 import com.example.compose.Comet_300 import com.example.compose.Licorice_900 import com.samedtemiz.fitlife.R import com.samedtemiz.fitlife.components.ButtonComponent import com.samedtemiz.fitlife.components.ClickableTextComponent import com.samedtemiz.fitlife.components.NormalTextBoxComponent import com.samedtemiz.fitlife.components.PasswordTextBoxComponent import com.samedtemiz.fitlife.data.auth.register.RegisterFormEvent import com.samedtemiz.fitlife.data.auth.register.RegisterUIState import com.samedtemiz.fitlife.data.auth.register.RegisterViewModel import com.samedtemiz.fitlife.navigation.Screen @Preview(showSystemUi = true, showBackground = true) @Composable fun RegisterScreenPreview() { // RegisterScreen() } @Composable fun RegisterScreen( navController: NavController, registerViewModel: RegisterViewModel = viewModel() ) { val state = registerViewModel.state if (state.isSuccessLogin) { /** * Navigate to Authenticated navigation route * once login is successful */ LaunchedEffect(key1 = true) { navController.navigate(Screen.Main.route) { popUpTo(navController.graph.id) { inclusive = true } } } } Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Box( Modifier .fillMaxSize() ) { Image( painter = painterResource( id = R.drawable.pear_bg ), contentDescription = "Register", modifier = Modifier .fillMaxSize() .blur(6.dp), contentScale = ContentScale.Crop ) Box( modifier = Modifier .fillMaxSize() .padding(28.dp) .alpha(0.6f) .clip( CutCornerShape( topStart = 16.dp, topEnd = 16.dp, bottomStart = 16.dp, bottomEnd = 16.dp ) ) .background(Licorice_900) ) Column( Modifier .fillMaxSize() .padding(48.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.SpaceAround ) { RegisterHeader() RegisterFields(registerViewModel, state) RegisterFooter( onRegisterClick = { registerViewModel.onEvent(RegisterFormEvent.Submit) }, onLoginClick = { // navController.navigate(Screen.Auth.Login.route) }, enabledStatus = true ) } } if (state.isLoading) { CircularProgressIndicator(color = BurntSienna_500) } } } @Composable fun RegisterHeader() { Column(horizontalAlignment = Alignment.CenterHorizontally) { Text( text = "Welcome", fontSize = 36.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily( Font(R.font.esprit_bold) ), color = Comet_300 ) Text( text = "Create an account", fontSize = 18.sp, fontWeight = FontWeight.SemiBold, fontFamily = FontFamily( Font(R.font.esprit_bold) ), color = Comet_300 ) } } @Composable fun RegisterFields(registerViewModel: RegisterViewModel, state: RegisterUIState) { Column { //FIRST NAME NormalTextBoxComponent( label = "First Name", placeholder = "Enter your first name", supportingText = state.firstNameRegisterError ?: "unknown error", onTextSelected = { registerViewModel.onEvent(RegisterFormEvent.FirstNameChanged(it)) }, leadingIcon = { Icon(Icons.Default.Person, contentDescription = "First Name") }, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Next ), errorStatus = state.firstNameRegisterError != null ) Spacer(modifier = Modifier.height(8.dp)) //LAST NAME NormalTextBoxComponent( label = "Last Name", placeholder = "Enter your last name", supportingText = state.lastNameRegisterError ?: "unknown error", onTextSelected = { registerViewModel.onEvent(RegisterFormEvent.LastNameChanged(it)) }, leadingIcon = { Icon(Icons.Default.Person, contentDescription = "Last Name") }, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Next ), errorStatus = state.lastNameRegisterError != null ) Spacer(modifier = Modifier.height(8.dp)) //EMAIL NormalTextBoxComponent( label = "Email", placeholder = "Enter your email address", supportingText = state.emailRegisterError ?: "unknown error", onTextSelected = { registerViewModel.onEvent(RegisterFormEvent.EmailChanged(it)) }, leadingIcon = { Icon(Icons.Default.Email, contentDescription = "Email") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Email, imeAction = ImeAction.Next ), errorStatus = state.emailRegisterError != null ) Spacer(modifier = Modifier.height(8.dp)) val showPassword = remember { mutableStateOf(false) } //PASSWORD PasswordTextBoxComponent( label = "Password", placeholder = "Enter your password", supportingText = state.passwordRegisterError ?: "unknown error", onTextSelected = { registerViewModel.onEvent(RegisterFormEvent.PasswordChanged(it)) }, visualTransformation = if (showPassword.value) VisualTransformation.None else PasswordVisualTransformation(), trailingIcon = { val (icon, iconColor) = if (showPassword.value) { Pair( Icons.Filled.Visibility, Color.White ) } else { Pair(Icons.Filled.VisibilityOff, Comet_300) } IconButton(onClick = { showPassword.value = !showPassword.value }) { Icon( icon, contentDescription = "Visibility", tint = iconColor ) } }, leadingIcon = { Icon(Icons.Default.Lock, contentDescription = "Password") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, imeAction = ImeAction.Done ), errorStatus = state.passwordRegisterError != null ) val showConfirmPassword = remember { mutableStateOf(false) } //CONFIRM PASSWORD PasswordTextBoxComponent( label = "Confirm Password", placeholder = "Password again", supportingText = state.confirmPasswordRegisterError ?: "unknown error", onTextSelected = { registerViewModel.onEvent(RegisterFormEvent.ConfirmPasswordChanged(it)) }, visualTransformation = if (showConfirmPassword.value) VisualTransformation.None else PasswordVisualTransformation(), trailingIcon = { val (icon, iconColor) = if (showConfirmPassword.value) { Pair( Icons.Filled.Visibility, Color.White ) } else { Pair(Icons.Filled.VisibilityOff, Comet_300) } IconButton(onClick = { showConfirmPassword.value = !showConfirmPassword.value }) { Icon( icon, contentDescription = "Visibility", tint = iconColor ) } }, leadingIcon = { Icon(Icons.Default.Lock, contentDescription = "Confirm Password") }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, imeAction = ImeAction.Done ), errorStatus = state.confirmPasswordRegisterError != null ) state.registerError?.let { Text(text = state.registerError, Modifier.fillMaxWidth(), textAlign = TextAlign.Center, color = BurntSienna_500) } } } @Composable fun RegisterFooter( onRegisterClick: () -> Unit, onLoginClick: (String) -> Unit, enabledStatus: Boolean ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { ButtonComponent( value = "Register", onButtonClicked = onRegisterClick, isEnabled = enabledStatus ) Spacer(modifier = Modifier.height(5.dp)) ClickableTextComponent( tryingToLogin = false, onTextSelected = onLoginClick ) } }
0
Kotlin
0
0
9bcd04032d12cdb57e4dbe402fc85936b603a653
12,117
FitLife
MIT License
kandroid/src/main/kotlin/com/pawegio/kandroid/KSearchView.kt
pawegio
32,946,447
false
null
/* * Copyright 2015-2016 <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.pawegio.kandroid import android.widget.SearchView import android.support.v7.widget.SearchView as SupportSearchView fun SearchView.onQueryChange(query: (String) -> Unit) { setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(q: String): Boolean { query(q) return false } override fun onQueryTextSubmit(q: String): Boolean { return false } }) } fun SearchView.onQuerySubmit(query: (String) -> Unit) { setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(q: String): Boolean { return false } override fun onQueryTextSubmit(q: String): Boolean { query(q) return false } }) } fun SupportSearchView.onQueryChange(query: (String) -> Unit) { setOnQueryTextListener(object : SupportSearchView.OnQueryTextListener { override fun onQueryTextChange(q: String): Boolean { query(q) return false } override fun onQueryTextSubmit(q: String): Boolean { return false } }) } fun SupportSearchView.onQuerySubmit(query: (String) -> Unit) { setOnQueryTextListener(object : SupportSearchView.OnQueryTextListener { override fun onQueryTextChange(q: String): Boolean { return false } override fun onQueryTextSubmit(q: String): Boolean { query(q) return false } }) }
5
Kotlin
81
893
16ad9ff774024a80a74349b33ca5b85030366357
2,143
KAndroid
Apache License 2.0
data/src/mock/kotlin/jp/co/yumemi/android/code_check/data/repositories/RepositoriesMockRepository.kt
wasabi-muffin
462,369,263
false
{"Kotlin": 2712155, "Mustache": 4796, "Ruby": 1144, "Shell": 812}
package io.github.gmvalentino8.github.sample.data.repositories import io.github.gmvalentino8.github.sample.domain.entities.PullRequest import io.github.gmvalentino8.github.sample.domain.entities.Release import io.github.gmvalentino8.github.sample.domain.entities.User import io.github.gmvalentino8.github.sample.domain.repositories.RepositoriesRepository class RepositoriesMockRepository : RepositoriesRepository { override suspend fun getContributors(name: String): List<User> = listOf() override suspend fun getReleases(name: String): List<Release> = listOf() override suspend fun getPulls(name: String): List<PullRequest> = listOf() }
0
Kotlin
0
1
2194a2504bde08427ad461d92586497c7187fb40
652
github-sample-project
Apache License 2.0
src/test/kotlin/org/lexem/angmar/parser/commons/PatternWhitespaceNodeTest.kt
lexemlang
184,409,059
false
{"Kotlin": 3049940}
package org.lexem.angmar.parser.commons import org.junit.jupiter.api.* import org.junit.jupiter.params.* import org.junit.jupiter.params.provider.* import org.lexem.angmar.* import org.lexem.angmar.io.readers.* import org.lexem.angmar.parser.descriptive.lexemes.* import java.util.stream.* internal class PatternWhitespaceNodeTest { // PARAMETERS ------------------------------------------------------------- companion object { @JvmStatic private fun provideWhitespaces(): Stream<Arguments> { return Stream.concat(WhitespaceNoEOLNodeTest.provideWsNoComments(), WhitespaceNoEOLNodeTest.provideWsWithComments()) } } // TESTS ------------------------------------------------------------------ @ParameterizedTest @MethodSource("provideWhitespaces") fun `parse correct whitespaces`(text: String) { val parser = LexemParser(IOStringReader.from(text)) val res = PatternWhitespaceNode.parse(parser) Assertions.assertTrue(res, "The parser must capture something") Assertions.assertEquals(text.length, parser.reader.currentPosition(), "The parser did not advance the cursor") } @Test fun `parse correct continuation`() { val text = ContinuationLexemeNodeTest.testExpression val parser = LexemParser(IOStringReader.from(text)) val res = PatternWhitespaceNode.parse(parser) Assertions.assertTrue(res, "The parser must capture something") Assertions.assertEquals(text.length, parser.reader.currentPosition(), "The parser did not advance the cursor") } @ParameterizedTest @ValueSource(strings = ["", "3"]) fun `not parse the node`(text: String) { val parser = LexemParser(IOStringReader.from(text)) val res = PatternWhitespaceNode.parse(parser) Assertions.assertFalse(res, "The input has incorrectly parsed anything") Assertions.assertEquals(0, parser.reader.currentPosition(), "The parser must not advance the cursor") } }
0
Kotlin
0
2
45fb563507a00c3eada89be9ab6e17cfe1701958
2,041
angmar
MIT License
fcl/src/main/java/com/portto/fcl/provider/Constants.kt
portto
505,659,431
false
null
package com.portto.fcl.provider // Blocto internal const val PROVIDER_BLOCTO_ID = 0 internal const val PROVIDER_BLOCTO_TITLE = "Blocto" internal const val PROVIDER_BLOCTO_DESC = "Best wallet to interact with Web3" internal const val PROVIDER_BLOCTO_ICON = "https://ipfs.blocto.app/ipfs/QmTmQQBz5KfVUcHW83S3kxqh29vSQ3cH7pcsc6cngYsG5U" // Dapper internal const val PROVIDER_DAPPER_ID = 1 internal const val PROVIDER_DAPPER_TITLE = "Dapper" internal const val PROVIDER_DAPPER_DESC = "Wallet created by Dapper Lab" internal const val PROVIDER_DAPPER_ICON = "https://ipfs.blocto.app/ipfs/Qmb81oGbB9qxUct7udtHsAqiJkRf4ey2bxuDhdg1ojFDfr"
0
Kotlin
3
21
5c94377766854b746e52a6fc73d3f83f84aa6c6a
633
fcl-android
MIT License
klogging/src/commonMain/kotlin/io/klogging/Klogger.kt
klogging
378,410,833
false
null
/* Copyright 2021-2022 Michael Strasser. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.klogging import io.klogging.Level.DEBUG import io.klogging.Level.ERROR import io.klogging.Level.FATAL import io.klogging.Level.INFO import io.klogging.Level.TRACE import io.klogging.Level.WARN import io.klogging.events.LogEvent /** * Logger interface for sending log events from `suspend` functions running in * [Kotlin coroutines](https://kotlinlang.org/docs/coroutines-overview.html). * * Every function is a `suspend` function and should only be called in another * `suspend` function. * * @see NoCoLogger for the corresponding non-coroutine interface. */ public interface Klogger : BaseLogger { /** Emit an event after minimum level checking. */ public suspend fun emitEvent(level: Level, throwable: Throwable?, event: Any?) public suspend fun log(level: Level, throwable: Throwable, event: Any?) { if (!isLevelEnabled(level)) return emitEvent(level, throwable, event) } public suspend fun log(level: Level, event: Any?) { if (!isLevelEnabled(level)) return emitEvent(level, null, event) } public suspend fun log( level: Level, throwable: Throwable, template: String, vararg values: Any? ) { if (!isLevelEnabled(level)) return if (values.isEmpty()) emitEvent(level, throwable, template) else emitEvent(level, throwable, e(template, *values)) } public suspend fun log(level: Level, template: String, vararg values: Any?) { if (!isLevelEnabled(level)) return if (values.isEmpty()) emitEvent(level, null, template) else emitEvent(level, null, e(template, *values)) } public suspend fun log(level: Level, throwable: Throwable, event: suspend Klogger.() -> Any?) { if (!isLevelEnabled(level)) return emitEvent(level, throwable, event()) } public suspend fun log(level: Level, event: suspend Klogger.() -> Any?) { if (!isLevelEnabled(level)) return emitEvent(level, null, event()) } public suspend fun trace(event: Any?): Unit = log(TRACE, event) public suspend fun trace(template: String, vararg values: Any?): Unit = log(TRACE, template, *values) public suspend fun trace(throwable: Throwable, event: Any?): Unit = log(WARN, throwable, event) public suspend fun trace(throwable: Throwable, template: String, vararg values: Any?): Unit = log(TRACE, throwable, template, *values) public suspend fun trace(event: suspend Klogger.() -> Any?): Unit = log(TRACE, event) public suspend fun trace(throwable: Throwable, event: suspend Klogger.() -> Any?): Unit = log(TRACE, throwable, event) public suspend fun debug(event: Any?): Unit = log(DEBUG, event) public suspend fun debug(template: String, vararg values: Any?): Unit = log(DEBUG, template, *values) public suspend fun debug(throwable: Throwable, event: Any?): Unit = log(DEBUG, throwable, event) public suspend fun debug(throwable: Throwable, template: String, vararg values: Any?): Unit = log(DEBUG, throwable, template, *values) public suspend fun debug(event: suspend Klogger.() -> Any?): Unit = log(DEBUG, event) public suspend fun debug(throwable: Throwable, event: suspend Klogger.() -> Any?): Unit = log(DEBUG, throwable, event) public suspend fun info(event: Any?): Unit = log(INFO, event) public suspend fun info(template: String, vararg values: Any?): Unit = log(INFO, template, *values) public suspend fun info(throwable: Throwable, event: Any?): Unit = log(INFO, throwable, event) public suspend fun info(throwable: Throwable, template: String, vararg values: Any?): Unit = log(INFO, throwable, template, *values) public suspend fun info(event: suspend Klogger.() -> Any?): Unit = log(INFO, event) public suspend fun info(throwable: Throwable, event: suspend Klogger.() -> Any?): Unit = log(INFO, throwable, event) public suspend fun warn(event: Any?): Unit = log(WARN, event) public suspend fun warn(template: String, vararg values: Any?): Unit = log(WARN, template, *values) public suspend fun warn(throwable: Throwable, event: Any?): Unit = log(WARN, throwable, event) public suspend fun warn(throwable: Throwable, template: String, vararg values: Any?): Unit = log(WARN, throwable, template, *values) public suspend fun warn(event: suspend Klogger.() -> Any?): Unit = log(WARN, event) public suspend fun warn(throwable: Throwable, event: suspend Klogger.() -> Any?): Unit = log(WARN, throwable, event) public suspend fun error(event: Any?): Unit = log(ERROR, event) public suspend fun error(template: String, vararg values: Any?): Unit = log(ERROR, template, *values) public suspend fun error(throwable: Throwable, event: Any?): Unit = log(ERROR, throwable, event) public suspend fun error(throwable: Throwable, template: String, vararg values: Any?): Unit = log(ERROR, throwable, template, *values) public suspend fun error(event: suspend Klogger.() -> Any?): Unit = log(ERROR, event) public suspend fun error(throwable: Throwable, event: suspend Klogger.() -> Any?): Unit = log(ERROR, throwable, event) public suspend fun fatal(event: Any?): Unit = log(FATAL, event) public suspend fun fatal(template: String, vararg values: Any?): Unit = log(FATAL, template, *values) public suspend fun fatal(throwable: Throwable, event: Any?): Unit = log(FATAL, throwable, event) public suspend fun fatal(throwable: Throwable, template: String, vararg values: Any?): Unit = log(FATAL, throwable, template, *values) public suspend fun fatal(event: suspend Klogger.() -> Any?): Unit = log(FATAL, event) public suspend fun fatal(throwable: Throwable, event: suspend Klogger.() -> Any?): Unit = log(FATAL, throwable, event) /** * Evaluates a message template with the supplied values, returning [LogEvent]. */ public suspend fun e(template: String, vararg values: Any?): LogEvent }
17
null
8
91
89ae2ddc6aedc9f4f68267ebd8b0b0f0da43e81d
6,800
klogging
Apache License 2.0
whetstone/compiler/src/main/kotlin/com/freeletics/mad/whetstone/WhetstoneCodeGenerator.kt
freeletics
375,363,637
false
null
package com.freeletics.mad.whetstone import com.freeletics.mad.whetstone.codegen.FileGenerator import com.freeletics.mad.whetstone.parser.toComposeFragmentData import com.freeletics.mad.whetstone.parser.toComposeFragmentDestinationData import com.freeletics.mad.whetstone.parser.toComposeScreenData import com.freeletics.mad.whetstone.parser.toComposeScreenDestinationData import com.freeletics.mad.whetstone.parser.toRendererFragmentData import com.freeletics.mad.whetstone.parser.toRendererFragmentDestinationData import com.google.auto.service.AutoService import com.squareup.anvil.annotations.ExperimentalAnvilApi import com.squareup.anvil.compiler.api.AnvilContext import com.squareup.anvil.compiler.api.CodeGenerator import com.squareup.anvil.compiler.api.GeneratedFile import com.squareup.anvil.compiler.api.createGeneratedFile import com.squareup.anvil.compiler.internal.reference.classAndInnerClassReferences import com.squareup.anvil.compiler.internal.reference.topLevelFunctionReferences import java.io.File import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.psi.KtFile @OptIn(ExperimentalAnvilApi::class) @AutoService(CodeGenerator::class) public class WhetstoneCodeGenerator : CodeGenerator { override fun isApplicable(context: AnvilContext): Boolean = true override fun generateCode( codeGenDir: File, module: ModuleDescriptor, projectFiles: Collection<KtFile> ): Collection<GeneratedFile> { val compose = projectFiles .topLevelFunctionReferences(module) .mapNotNull { it.toComposeScreenDestinationData() ?: it.toComposeScreenData() ?: it.toComposeFragmentDestinationData() ?: it.toComposeFragmentData() } val renderer = projectFiles .classAndInnerClassReferences(module) .mapNotNull { it.toRendererFragmentDestinationData() ?: it.toRendererFragmentData() } val data = compose.toList() + renderer return data.map { val file = FileGenerator().generate(it) createGeneratedFile( codeGenDir = codeGenDir, packageName = file.packageName, fileName = file.name, content = file.toString() ) } } }
7
null
8
66
c8943e26b0ef1934ac1487320fcfd043f6047273
2,408
mad
Apache License 2.0
library/data/src/main/java/id/apwdevs/app/data/source/remote/response/tvdetail/TvDetailResponse.kt
AlexzPurewoko
354,045,461
false
null
package id.apwdevs.app.data.source.remote.response.tvdetail import com.google.gson.annotations.SerializedName import id.apwdevs.app.data.source.remote.response.parts.Genre import id.apwdevs.app.data.source.remote.response.parts.ProductionCompany import id.apwdevs.app.data.source.remote.response.parts.ProductionCountry import id.apwdevs.app.data.source.remote.response.parts.SpokenLanguage import id.apwdevs.app.data.source.remote.response.tvdetail.parts.CreatedByItem import id.apwdevs.app.data.source.remote.response.tvdetail.parts.EpisodesToAir import id.apwdevs.app.data.source.remote.response.tvdetail.parts.NetworksItem import id.apwdevs.app.data.source.remote.response.tvdetail.parts.SeasonsItem data class TvDetailResponse( @field:SerializedName("original_language") val originalLanguage: String, @field:SerializedName("number_of_episodes") val numberOfEpisodes: Int, @field:SerializedName("networks") val networks: List<NetworksItem>, @field:SerializedName("type") val type: String, @field:SerializedName("backdrop_path") val backdropPath: String?, @field:SerializedName("genres") val genres: List<Genre>, @field:SerializedName("popularity") val popularity: Double, @field:SerializedName("production_countries") val productionCountries: List<ProductionCountry>, @field:SerializedName("id") val id: Int, @field:SerializedName("number_of_seasons") val numberOfSeasons: Int, @field:SerializedName("vote_count") val voteCount: Int, @field:SerializedName("first_air_date") val firstAirDate: String, @field:SerializedName("overview") val overview: String, @field:SerializedName("seasons") val seasons: List<SeasonsItem>, @field:SerializedName("languages") val languages: List<String>, @field:SerializedName("created_by") val createdBy: List<CreatedByItem>, @field:SerializedName("last_episode_to_air") val lastEpisodeToAir: EpisodesToAir, @field:SerializedName("poster_path") val posterPath: String?, @field:SerializedName("origin_country") val originCountry: List<String>, @field:SerializedName("spoken_languages") val spokenLanguages: List<SpokenLanguage>, @field:SerializedName("production_companies") val productionCompanies: List<ProductionCompany>, @field:SerializedName("original_name") val originalName: String, @field:SerializedName("vote_average") val voteAverage: Double, @field:SerializedName("name") val name: String, @field:SerializedName("tagline") val tagline: String, @field:SerializedName("episode_run_time") val episodeRunTime: List<Int>, @field:SerializedName("next_episode_to_air") val nextEpisodeToAir: EpisodesToAir?, @field:SerializedName("in_production") val inProduction: Boolean, @field:SerializedName("last_air_date") val lastAirDate: String, @field:SerializedName("homepage") val homepage: String, @field:SerializedName("status") val status: String )
5
Kotlin
0
0
e80db0e7f11c7d24e86e410eae052ce6e10f9d1f
3,064
movie_catalogue
MIT License
dg-pay-domain/src/main/kotlin/devgraft/dgpay/domain/wallet/port/outbound/WalletPort.kt
dev-graft
632,778,527
false
null
package devgraft.dgpay.domain.wallet.port.outbound import devgraft.dgpay.domain.wallet.model.Wallet interface WalletPort { fun addWallet(wallet: Wallet) }
0
Kotlin
0
0
00dc71a37c12898ac511fc9aebce2679b6b8b031
160
dg-pay-server
Apache License 2.0
src/main/kotlin/me/adriianhdev/plutotems/core/command/impl/GiveCommand.kt
Adriianh
590,503,165
false
{"Kotlin": 100924}
package me.adriianhdev.plutotems.core.command.impl import me.adriianhdev.plutotems.core.totem.Totem import me.adriianhdev.plutotems.core.totem.TotemManager import me.adriianhdev.plutotems.util.PlayerUtil import org.bukkit.Bukkit import org.bukkit.command.CommandSender import org.bukkit.entity.Player import taboolib.common.platform.command.subCommand import taboolib.platform.util.sendLang val giveCommand = subCommand { dynamic(comment = "player") { suggestion<Player> { _, _ -> Bukkit.getOnlinePlayers().map { it.name } } dynamic(comment = "id") { suggestion<Player> { _, _ -> TotemManager.totems.map { it.id } } execute<CommandSender> { sender, context, _ -> val totem = TotemManager.getTotem(context["id"]) val player = Bukkit.getPlayer(context["player"]) giveInfo(sender, player, totem) PlayerUtil.giveTotem(player!!, totem!!) } dynamic(comment = "amount", optional = true) { suggestion<Player> { _, _ -> (1..64).map { it.toString() } } execute<CommandSender> { sender, context, _ -> val totem = TotemManager.getTotem(context["id"]) val player = Bukkit.getPlayer(context["player"]) val amount = context["amount"].toIntOrNull() ?: 1 giveInfo(sender, player, totem) PlayerUtil.giveTotem(player!!, totem!!, amount) } } } } } fun giveInfo(sender: CommandSender, player: Player?, totem: Totem?) { if (player == null) { sender.sendLang("Command-Unknown-Player") return } if (totem == null) { sender.sendLang("Command-Unknown-Totem") return } sender.sendLang("Command-Totem-Give", totem.id, player.name) player.sendLang("Command-Totem-Get", totem.id) }
0
Kotlin
0
3
29d25b6ae9c8054b6d2c20951a35fcacb55c2af5
2,002
PluTotems
Creative Commons Zero v1.0 Universal
app/src/main/java/com/example/githubusers/ui/heroes/HeroesFragment.kt
freelanzer1
373,213,635
false
null
package com.example.githubusers.ui.heroes import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.support.v4.app.Fragment import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProvider import com.example.githubusers.R class HeroesFragment : Fragment() { private lateinit var heroesViewModel: HeroesViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { heroesViewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(HeroesViewModel::class.java) val root = inflater.inflate(R.layout.fragment_heroes, container, false) val textView: TextView = root.findViewById(R.id.text_dashboard) heroesViewModel.text.observe(viewLifecycleOwner, Observer { textView.text = it }) return root } }
0
Kotlin
0
0
1cfdc76104750493cdcd53b4fdacfd580a4d9e43
1,032
GitHubUsers
Apache License 2.0
gxpbaseeverything/src/main/java/com/peng/gxpbaseeverything/view/custom/view/KeyBoardLayout.kt
mudcastles
257,197,366
false
{"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 54, "XML": 79, "Java": 25, "INI": 1}
package com.peng.gxpbaseeverything.view.custom.view import android.content.Context import android.graphics.Color import android.text.Editable import android.text.TextWatcher import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.content.res.ResourcesCompat import com.peng.gxpbaseeverything.R import com.peng.gxpbaseeverything.util.DimenUtil import com.peng.gxpbaseeverything.util.ScreenUtil import kotlinx.android.synthetic.main.layout_keyboard.view.* import kotlin.math.max /** * 键盘,包含了AnimatorButton,实现切换过程的动画 */ class KeyBoardLayout : ViewGroup, AnimatorButton.OnExpandListener, AnimatorButton.OnButtonClickedListener, View.OnClickListener { private val mInflater = LayoutInflater.from(context) private var mKeyBoard: View = mInflater.inflate(R.layout.layout_keyboard, null) private var mButton: AnimatorButton = AnimatorButton(context) private var mWidthMeasureSpec: Int = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) private var mHeightMeasureSpec: Int = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) private var mExpandProgress = 0f //展开进度 private var mButtonOriginX = 0 //button最初的x private var mButtonTranslateX = 0 //button最终要移动的距离 private val mButtonOriginLocation = intArrayOf(0, 0) private var mTotalWidth = 0 private var mTotalHeight = 0 var mOnCallListener: OnCallListener? = null var mOnHandUpListener: OnHandupListener? = null private val teleohoneSb: StringBuffer = StringBuffer() private val mScrrenWidth = ScreenUtil.getScreenWidth(context) private val mScrrenHeight = ScreenUtil.getDaoHangHeight(context) //默认paddingBottom var mDefaultPaddingBottom = DimenUtil.dip2px(context, 20f) var mDefaultPaddingEnd = DimenUtil.dip2px(context, 20f) constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) init { addView(mKeyBoard) mButton.setCircleWidthHeight(50f) mButton.setDrawablePadding(4f) mButton.setTextPaddingVertical(10f) mButton.setTextSize(14) mButton.addButtonItems( AnimatorButton.ButtonItem( ResourcesCompat.getDrawable( context.resources, R.drawable.ic_handup, context.theme )!!, "挂断", Color.RED ), AnimatorButton.ButtonItem( ResourcesCompat.getDrawable( context.resources, R.drawable.ic_call_1, context.theme )!!, "拨打", Color.GREEN ) ) addView(mButton) mButton.setOnExpandListener(this) mButton.setOnButtonClickedListener(this) initKeyBoardClicked() tvTelephone.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (s.isNullOrEmpty()) ivDelete.visibility = View.GONE else ivDelete.visibility = View.VISIBLE } }) } private fun initKeyBoardClicked() { tvGLI0.setOnClickListener(this) tvGLI1.setOnClickListener(this) tvGLI2.setOnClickListener(this) tvGLI3.setOnClickListener(this) tvGLI4.setOnClickListener(this) tvGLI5.setOnClickListener(this) tvGLI6.setOnClickListener(this) tvGLI7.setOnClickListener(this) tvGLI8.setOnClickListener(this) tvGLI9.setOnClickListener(this) tvGLIStart.setOnClickListener(this) tvGLISharp.setOnClickListener(this) ivDelete.setOnClickListener(this) ivGLIFold.setOnClickListener(this) } override fun onClick(v: View) { when (v.id) { R.id.tvGLI0, R.id.tvGLI1, R.id.tvGLI2, R.id.tvGLI3, R.id.tvGLI4, R.id.tvGLI5, R.id.tvGLI6, R.id.tvGLI7, R.id.tvGLI8, R.id.tvGLI9, R.id.tvGLIStart, R.id.tvGLISharp -> { if (teleohoneSb.length >= 12) return teleohoneSb.append((v as TextView).text) tvTelephone.text = teleohoneSb.toString() } R.id.ivDelete -> { teleohoneSb.deleteCharAt(teleohoneSb.length - 1) tvTelephone.text = teleohoneSb.toString() } R.id.ivGLIFold -> mButton.toggle() } } fun toggle() = mButton.toggle() override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { if (mButton.getStatus() == AnimatorButton.AnimatorStatus.FOLDED) { mWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) mHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) measureChild(mButton, mWidthMeasureSpec, mHeightMeasureSpec) mTotalWidth = mButton.measuredWidth mTotalHeight = mButton.measuredHeight + mDefaultPaddingBottom } else { mWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) mHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) measureChild(mButton, mWidthMeasureSpec, mHeightMeasureSpec) mWidthMeasureSpec = MeasureSpec.makeMeasureSpec( MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY ) measureChild(mKeyBoard, mWidthMeasureSpec, mHeightMeasureSpec) mTotalWidth = MeasureSpec.getSize(widthMeasureSpec) mTotalHeight = max( (mButton.measuredHeight + mDefaultPaddingBottom).toFloat(), mKeyBoard.measuredHeight * mExpandProgress ).toInt() } setMeasuredDimension(mTotalWidth, mTotalHeight) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { mKeyBoard.layout( 0, (measuredHeight - mKeyBoard.measuredHeight * mExpandProgress).toInt(), measuredWidth, measuredHeight ) if (mButton.getStatus() == AnimatorButton.AnimatorStatus.FOLDED) { mButton.layout(0, 0, mButton.measuredWidth, mButton.measuredHeight) mButton.getLocationOnScreen(mButtonOriginLocation) mButtonOriginX = mButtonOriginLocation[0] } else { mButtonTranslateX = mButtonOriginX - (mTotalWidth - mButton.getExpandedWidth()) / 2 - left mButton.layout( (mButtonOriginX - mButtonTranslateX * mExpandProgress).toInt(), measuredHeight - mButton.measuredHeight - mDefaultPaddingBottom, (mButtonOriginX - mButtonTranslateX * mExpandProgress + mButton.measuredWidth).toInt(), measuredHeight - mDefaultPaddingBottom ) } } override fun onButtonClicked(index: Int) { when (index) { 0 -> { //挂断电话 mOnHandUpListener?.onHandUp() } 1 -> { //拨打电话 mOnCallListener?.onCall(tvTelephone.text.toString()) } } } override fun onExpand(progress: Float) { mExpandProgress = progress requestLayout() } fun getKeyBoardStatus() = mButton.getStatus() } interface OnCallListener { fun onCall(num: String) } interface OnHandupListener { fun onHandUp() }
0
Kotlin
1
1
93de9d030a6c1bc9d4815790cf9e31be538176c0
8,043
GXP-BaseEverything
Apache License 2.0
features/task/src/main/java/com/escodro/task/model/TaskWithCategory.kt
Arab1997
307,581,565
false
{"Gradle": 23, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 15, "Batchfile": 1, "YAML": 3, "Markdown": 14, "XML": 103, "Proguard": 13, "Kotlin": 211, "Java": 1, "INI": 4, "Gradle Kotlin DSL": 1, "JSON": 3}
package com.escodro.task.model /** * Data class to represent a Task with Category. */ data class TaskWithCategory( val task: Task, val category: Category? = null )
1
null
1
1
cb8056afe8bc03bfb3f89938a168961aa211f860
175
alkaa
Apache License 2.0
libraries/stdlib/src/kotlin/native/String.kt
dotlin-org
434,960,829
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * Copyright 2021-2022 Wilko Manger * * 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 kotlin /** * The `String` class represents character strings. All string literals in Kotlin programs, such as `"abc"`, are * implemented as instances of this class. */ @DartLibrary("dart:core") external class String : Comparable<String> { companion object /** * Returns a string obtained by concatenating this string with the string representation of the given [other] object. */ operator fun plus(other: Any?): String val length: Int /** * Returns the character of this string at the specified [index]. * * If the [index] is out of bounds of this string, throws an [IndexOutOfBoundsException] except in Kotlin/JS * where the behavior is unspecified. */ fun get(index: Int): String fun subSequence(startIndex: Int, endIndex: Int): String override fun compareTo(other: String): Int }
5
Kotlin
3
30
633430bfa0786923bde86d9068323f18eb5c24d5
1,509
dotlin
Apache License 2.0
touch/src/main/java/de/nicidienase/chaosflix/touch/browse/streaming/LivestreamListFragment.kt
NiciDieNase
85,370,651
false
null
package de.nicidienase.chaosflix.touch.browse.streaming import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import com.google.android.material.snackbar.Snackbar import de.nicidienase.chaosflix.touch.R import de.nicidienase.chaosflix.touch.browse.BrowseFragment import de.nicidienase.chaosflix.touch.databinding.FragmentLivestreamsBinding class LivestreamListFragment : BrowseFragment() { private lateinit var listener: InteractionListener private lateinit var binding: FragmentLivestreamsBinding lateinit var adapter: LivestreamAdapter lateinit var snackbar: Snackbar private var columnCount = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null) { columnCount = arguments!!.getInt(ARG_COLUMN_COUNT) } } override fun onAttach(context: Context) { super.onAttach(context) if (context is InteractionListener) { listener = context adapter = LivestreamAdapter(listener) } else { throw RuntimeException("$context must implement LivestreamListFragment.InteractionListener") } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentLivestreamsBinding.inflate(inflater, container, false) setupToolbar(binding.incToolbar.toolbar, R.string.livestreams) if (columnCount <= 1) { binding.list.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) } else { binding.list.layoutManager = androidx.recyclerview.widget.GridLayoutManager(context, columnCount) } binding.list.adapter = adapter binding.swipeRefreshLayout.setOnRefreshListener { updateList() } viewModel.getLivestreams().observe(viewLifecycleOwner, Observer { if (it != null) { adapter.setContent(it) if (it.isEmpty() && !snackbar.isShown) { snackbar.show() } else { snackbar.dismiss() } } binding.swipeRefreshLayout.isRefreshing = false }) viewModel.updateLiveStreams() snackbar = Snackbar.make(binding.root, R.string.no_livestreams, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.reload) { this.updateList() } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) updateList() } private fun updateList() { binding.swipeRefreshLayout.isRefreshing = true Log.d(TAG, "Refresh starting") viewModel.updateLiveStreams() } interface InteractionListener { fun onStreamSelected(streamingItem: StreamingItem) } companion object { private val ARG_COLUMN_COUNT = "column-count" private val TAG = LivestreamListFragment::class.simpleName fun newInstance(columnCount: Int): LivestreamListFragment { val fragment = LivestreamListFragment() val args = Bundle() args.putInt(ARG_COLUMN_COUNT, columnCount) fragment.arguments = args return fragment } } }
42
null
7
87
83b429928fe6a4de2796e750402fcece17bb1dab
3,524
chaosflix
MIT License
shared/src/androidMain/kotlin/main.android.kt
FebrianDev
709,151,433
false
{"Kotlin": 312460, "Ruby": 1723, "Swift": 1695, "Shell": 228}
import android.content.Context import android.content.Intent import android.net.Uri import androidx.compose.runtime.Composable import com.google.firebase.firestore.FieldValue import com.google.firebase.firestore.FirebaseFirestore import data.chat.ChatEntity import data.chat.Message import dev.gitlive.firebase.Firebase import dev.gitlive.firebase.firestore.firestore import utils.getDateNow actual fun getPlatformName(): String = "Android" private var c: Context? = null actual fun openEmail() { c?.startActivity(Intent(Intent.ACTION_SENDTO).apply { data = Uri.parse("mailto:febrian26022001@gmail.com") }) } actual fun openUrl() { c?.startActivity(Intent(Intent.ACTION_VIEW).apply { data = Uri.parse("https://linktr.ee/febrian2001") }) } private val firestore = FirebaseFirestore.getInstance() actual fun getChat(idChat: String, onGetChat: (chat: ChatEntity) -> Unit) { firestore.collection("Chat").whereEqualTo("id_chat", idChat) .addSnapshotListener { value, error -> if (error != null) { println("Chat Error ${error.message}") return@addSnapshotListener } val chat = (value!!.toObjects(ChatEntity::class.java) as ArrayList<ChatEntity>).map { it } if (chat.isNotEmpty()) onGetChat.invoke(chat[0]) } } actual fun readChat( idChat: String, idSent: String ) { val temp = java.util.ArrayList<Message>() firestore.collection("Chat").document(idChat) .get().addOnCompleteListener { if (it.result.get("id_sent").toString() == idSent) { it.result.reference.update("countReadSent", 0) } else { it.result.reference.update("countReadReceiver", 0) } it.result.toObject(ChatEntity::class.java)!!.message.forEach { data -> if (!data.read && idSent != data.sender) data.read = true temp.add(data) } it.result.reference.update("message", temp) } } actual fun sendChat( message: Message, idSent: String, idReceiver: String, idChat: String, ) { firestore.collection("Chat").whereEqualTo("id_chat", idChat).get().addOnCompleteListener { firestore.collection("Chat").document(it.result.documents[0].id) .update("message", FieldValue.arrayUnion(message), "date", getDateNow()) if (message.sender == it.result.documents[0].get("id_sent").toString()) { it.result.documents[0].reference.update( "countReadReceiver", it.result.documents[0].get("countReadReceiver").toString().toInt() + 1 ) } else { it.result.documents[0].reference.update( "countReadSent", it.result.documents[0].get("countReadSent").toString().toInt() + 1 ) } } } @Composable fun MainView(context: Context) { c = context App() }
0
Kotlin
0
0
383cc85cf6ba4436322d24cb2dd31d6a32903ba7
3,010
TellUs
Apache License 2.0
app/src/main/java/com/yelinaung/luluaung/model/network/Datum.kt
yemyatthu1990
91,767,251
true
{"Java": 929950, "Kotlin": 49268, "HTML": 4048}
package com.yelinaung.luluaung.model.network import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import java.io.Serializable import java.util.* /** * Created by user on 9/3/16. */ class Datum : Serializable { /** * @return * * The images */ /** * @param images * * The images */ @SerializedName("images") @Expose var images: List<Image> = ArrayList() /** * @return * * The id */ /** * @param id * * The id */ @SerializedName("name") @Expose var name: String? = null @SerializedName("id") @Expose var id: String? = null fun withImages(images: List<Image>): Datum { this.images = images return this } fun withId(id: String): Datum { this.id = id return this } override fun toString(): String { return "Datum(id=$id, images=$images, name=$name)" } }
0
Java
0
0
334b884267bcca85f315c7ea3908c4b9c32dced8
980
Lu-lu-aung
Do What The F*ck You Want To Public License
src/main/kotlin/com/tuk/oriddle/quizGame/adapter/in/message/QuizGameWsController.kt
Team-Oriddle
731,663,342
false
{"Kotlin": 105076}
package com.tuk.oriddle.quizGame.adapter.`in`.message import com.tuk.oriddle.global.result.ResultCode.* import com.tuk.oriddle.quizGame.adapter.`in`.message.dto.ChatReceiveMessage import com.tuk.oriddle.quizGame.adapter.`in`.message.dto.CheckAnswerMessage import com.tuk.oriddle.quizGame.application.port.`in`.QuizGameUseCase import org.springframework.messaging.handler.annotation.DestinationVariable import org.springframework.messaging.handler.annotation.MessageMapping import org.springframework.messaging.handler.annotation.Payload import org.springframework.messaging.simp.SimpMessageHeaderAccessor import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.* import java.util.* @Controller class QuizGameWsController(private val quizGameUseCase: QuizGameUseCase) { @MessageMapping("/quiz-room/{quizRoomId}/check-answer") fun handleMessage( @DestinationVariable("quizRoomId") quizRoomId: UUID, @Payload message: CheckAnswerMessage, headerAccessor: SimpMessageHeaderAccessor ) { quizGameUseCase.checkAnswer(quizRoomId, message, getUserIdInHeader(headerAccessor)) } @MessageMapping("quiz-room/{quizRoomId}/chat") fun sendChatMessage( @DestinationVariable("quizRoomId") quizRoomId: UUID, @Payload message: ChatReceiveMessage, headerAccessor: SimpMessageHeaderAccessor ) { quizGameUseCase.sendChatMessage(quizRoomId, message, getUserIdInHeader(headerAccessor)) } private fun getUserIdInHeader(headerAccessor: SimpMessageHeaderAccessor): Long { return (headerAccessor.sessionAttributes?.get("id") as String).toLong() } }
3
Kotlin
1
0
61a7daccf01705520d2943a02e7901a1710f4710
1,674
oriddle-backend
MIT License
src/main/kotlin/com/github/blarc/ai/commits/intellij/plugin/settings/clients/azureOpenAi/AzureOpenAiClientSharedState.kt
Blarc
618,925,533
false
{"Kotlin": 144393}
package com.github.blarc.ai.commits.intellij.plugin.settings.clients.azureOpenAi; import com.github.blarc.ai.commits.intellij.plugin.settings.clients.LLMClientSharedState import com.intellij.openapi.components.* import com.intellij.util.xmlb.annotations.XCollection @Service(Service.Level.APP) @State(name = "AzureOpenAiClientSharedState", storages = [Storage("AICommitsAzureOpenAi.xml")]) class AzureOpenAiClientSharedState : PersistentStateComponent<AzureOpenAiClientSharedState>, LLMClientSharedState { companion object { @JvmStatic fun getInstance(): AzureOpenAiClientSharedState = service() } @XCollection(style = XCollection.Style.v2) override val hosts: MutableSet<String> = mutableSetOf() @XCollection(style = XCollection.Style.v2) override val modelIds: MutableSet<String> = mutableSetOf() override fun getState(): AzureOpenAiClientSharedState = this override fun loadState(state: AzureOpenAiClientSharedState) { // Add all model IDs from enum in case they are not stored in xml modelIds += state.modelIds hosts += state.hosts } }
18
Kotlin
29
236
f9ad5347f3eeb7da562926187f2f533813fda6ba
1,123
ai-commits-intellij-plugin
MIT License
ReviewerMobile/app/src/main/java/com/forzz/android/reviewermobile/domain/use_cases/get_movies/GetMoviesUseCase.kt
Forzz
594,475,346
false
null
package com.forzz.android.reviewermobile.domain.use_cases.get_movies import android.util.Log import com.forzz.android.reviewermobile.data.remote.dto.MovieDTO import com.forzz.android.reviewermobile.domain.repository.ContentRepository import com.forzz.android.reviewermobile.domain.use_cases.base.SingleUseCase import io.reactivex.Single import javax.inject.Inject class GetMoviesUseCase @Inject constructor( private val repository: ContentRepository ) : SingleUseCase<List<MovieDTO>>() { override fun buildUseCaseSingle(): Single<List<MovieDTO>> { return repository.getMovies() } }
0
Kotlin
0
0
60fa59b577d15f04168908cb03c03cb4e7ee5cb7
604
Reviewer
MIT License
app/src/main/java/com/arya/moviecatalogue/ui/movie/MovieViewModel.kt
arryaaas
462,995,256
false
null
package com.arya.moviecatalogue.ui.movie import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.paging.PagedList import com.arya.moviecatalogue.data.source.MovieRepository import com.arya.moviecatalogue.data.source.local.entity.MovieEntity import com.arya.moviecatalogue.vo.Resource class MovieViewModel(private val movieRepository: MovieRepository) : ViewModel() { fun getMovie(sort: String): LiveData<Resource<PagedList<MovieEntity>>> = movieRepository.getMovie(sort) }
0
Kotlin
0
0
d78876b86a5615b3968b0eb73f227e7abbc18083
519
Movie-Catalogue
MIT License
src/main/kotlin/me/bardy/bot/listeners/BardyBotListener.kt
BomBardyGamer
273,072,409
false
null
package me.bardy.bot.listeners import net.dv8tion.jda.api.hooks.ListenerAdapter /** * Marker class for Spring to be able to inject a set of these without * injecting all listener adapters. */ abstract class BardyBotListener : ListenerAdapter()
0
Kotlin
0
3
a401ae145c222547d1e0737871ecf7d1acef689f
249
bardybot
MIT License
src/main/kotlin/me/tatarka/assertk/failure.kt
evant
84,261,688
false
null
package assertk /** * Assertions are run in a failure context which captures failures to report them. */ internal object FailureContext { internal var failure: Failure = SimpleFailure() /** * Run the given block of assertions in the given context. If we are already in a context a new one will not be * created. */ fun <T> run(failure: Failure, f: () -> T): T { if (this.failure is SimpleFailure) { val tmp = this.failure this.failure = failure val result = f() this.failure = tmp failure() return result } else { return f() } } } internal interface Failure { /** * Record a failure. Depending on the implementation this may throw an exception or collect the failure for later. */ fun fail(error: AssertionError) /** * Triggers any collected failures. */ operator fun invoke() { } } /** * Failure that immediately thrown an exception. */ internal class SimpleFailure : Failure { override fun fail(error: AssertionError) { failWithNotInStacktrace(error) } } /** * Failure that collects all failures and displays them at once. */ internal class SoftFailure : Failure { private val failures: MutableList<AssertionError> = ArrayList() override fun fail(error: AssertionError) { failures.add(error) } override fun invoke() { if (!failures.isEmpty()) { fail(compositeErrorMessage(failures)) } } private fun compositeErrorMessage(errors: List<AssertionError>): String { return if (errors.size == 1) { errors.first().message.orEmpty() } else { errors.joinToString( prefix = "The following ${errors.size} assertions failed:\n", transform = { "- ${it.message}" }, separator = "\n" ) } } } /** * Fail the test with the given {@link AssertionError}. */ fun fail(error: AssertionError) { FailureContext.failure.fail(error) } /** * Fail the test with the given message. */ fun fail(message: String) { FailureContext.failure.fail(AssertionError(message)) } @Suppress("NOTHING_TO_INLINE") private inline fun failWithNotInStacktrace(error: AssertionError): Nothing { val filtered = error.stackTrace .dropWhile { it.className.startsWith("assertk") } .toTypedArray() @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UnsafeCast") (error as java.lang.Throwable).stackTrace = filtered throw error }
4
Kotlin
0
6
5bc0de25314fcb56f17f74c45b7b4b255155b0a7
2,624
assertk
Apache License 2.0
packages/expo-updates/android/src/androidTest/java/expo/modules/updates/db/UpdatesDatabaseTest.kt
betomoedano
462,599,485
false
null
package expo.modules.updates.db import android.database.sqlite.SQLiteConstraintException import androidx.room.Room import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner import androidx.test.platform.app.InstrumentationRegistry import expo.modules.updates.db.dao.AssetDao import expo.modules.updates.db.dao.UpdateDao import expo.modules.updates.db.entity.AssetEntity import expo.modules.updates.db.entity.UpdateAssetEntity import expo.modules.updates.db.entity.UpdateEntity import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.util.* @RunWith(AndroidJUnit4ClassRunner::class) class UpdatesDatabaseTest { private lateinit var db: UpdatesDatabase private lateinit var updateDao: UpdateDao private lateinit var assetDao: AssetDao @Before fun createDb() { val context = InstrumentationRegistry.getInstrumentation().targetContext db = Room.inMemoryDatabaseBuilder(context, UpdatesDatabase::class.java).build() updateDao = db.updateDao() assetDao = db.assetDao() } @After fun closeDb() { db.close() } @Test fun testInsertUpdate() { val uuid = UUID.randomUUID() val date = Date() val runtimeVersion = "1.0" val projectId = "https://exp.host/@esamelson/test-project" val testUpdate = UpdateEntity(uuid, date, runtimeVersion, projectId) updateDao.insertUpdate(testUpdate) val byId = updateDao.loadUpdateWithId(uuid) Assert.assertNotNull(byId) Assert.assertEquals(uuid, byId!!.id) Assert.assertEquals(date, byId.commitTime) Assert.assertEquals(runtimeVersion, byId.runtimeVersion) Assert.assertEquals(projectId, byId.scopeKey) updateDao.deleteUpdates(listOf(testUpdate)) Assert.assertEquals(0, updateDao.loadAllUpdates().size.toLong()) } @Test(expected = SQLiteConstraintException::class) fun testForeignKeys() { val uuid = UUID.randomUUID() val date = Date() val runtimeVersion = "1.0" val projectId = "https://exp.host/@esamelson/test-project" val testUpdate = UpdateEntity(uuid, date, runtimeVersion, projectId) updateDao.insertUpdate(testUpdate) try { assetDao._insertUpdateAsset(UpdateAssetEntity(uuid, 47)) } finally { updateDao.deleteUpdates(listOf(testUpdate)) } } @Test fun testMarkUpdateReady() { val uuid = UUID.randomUUID() val date = Date() val runtimeVersion = "1.0" val projectId = "https://exp.host/@esamelson/test-project" val testUpdate = UpdateEntity(uuid, date, runtimeVersion, projectId) updateDao.insertUpdate(testUpdate) Assert.assertEquals(0, updateDao.loadLaunchableUpdatesForScope(projectId).size.toLong()) updateDao.markUpdateFinished(testUpdate) Assert.assertEquals(1, updateDao.loadLaunchableUpdatesForScope(projectId).size.toLong()) updateDao.deleteUpdates(Arrays.asList(testUpdate)) Assert.assertEquals(0, updateDao.loadAllUpdates().size.toLong()) } @Test fun testDeleteUnusedAssets() { val runtimeVersion = "1.0" val projectId = "https://exp.host/@esamelson/test-project" val update1 = UpdateEntity(UUID.randomUUID(), Date(), runtimeVersion, projectId) val asset1 = AssetEntity("asset1", "png") val commonAsset = AssetEntity("commonAsset", "png") updateDao.insertUpdate(update1) assetDao.insertAssets(listOf(asset1, commonAsset), update1) val update2 = UpdateEntity(UUID.randomUUID(), Date(), runtimeVersion, projectId) val asset2 = AssetEntity("asset2", "png") updateDao.insertUpdate(update2) assetDao.insertAssets(listOf(asset2), update2) assetDao.addExistingAssetToUpdate(update2, commonAsset, false) val update3 = UpdateEntity(UUID.randomUUID(), Date(), runtimeVersion, projectId) val asset3 = AssetEntity("asset3", "png") updateDao.insertUpdate(update3) assetDao.insertAssets(listOf(asset3), update3) assetDao.addExistingAssetToUpdate(update3, commonAsset, false) // update 1 will be deleted // update 2 will have keep = false // update 3 will have keep = true updateDao.deleteUpdates(listOf(update1)) updateDao.markUpdateFinished(update3) // check that test has been properly set up val allUpdates = updateDao.loadAllUpdates() Assert.assertEquals(2, allUpdates.size.toLong()) for (update in allUpdates) { if (update.id == update2.id) { Assert.assertFalse(update.keep) } else { Assert.assertTrue(update.keep) } } Assert.assertNotNull(assetDao.loadAssetWithKey("asset1")) Assert.assertNotNull(assetDao.loadAssetWithKey("asset2")) Assert.assertNotNull(assetDao.loadAssetWithKey("asset3")) Assert.assertNotNull(assetDao.loadAssetWithKey("commonAsset")) assetDao.deleteUnusedAssets() Assert.assertNull(assetDao.loadAssetWithKey("asset1")) Assert.assertNull(assetDao.loadAssetWithKey("asset2")) Assert.assertNotNull(assetDao.loadAssetWithKey("asset3")) Assert.assertNotNull(assetDao.loadAssetWithKey("commonAsset")) } }
668
null
5226
4
52d6405570a39a87149648d045d91098374f4423
5,050
expo
MIT License
kotlinUtils/src/main/java/com/pape/utils/ReflectExt.kt
ibaozi-cn
129,831,947
false
null
package com.pape.utils /** * 功能描述: * Created by Administrator on 2018/5/7. */
1
null
2
9
4a4e458a923da80da9ce454cb37f73c69c202957
82
AndroidUtilCodeToKotlin
Apache License 2.0
app/src/androidTest/java/com/concordium/wallet/data/room/TransferDaoUnitTest.kt
Concordium
358,250,608
false
null
package com.concordium.wallet.data.room import android.content.Context import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.room.Room import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.concordium.wallet.data.model.TransactionOutcome import com.concordium.wallet.data.model.TransactionStatus import com.concordium.wallet.data.model.TransactionType import com.concordium.wallet.getOrAwaitValue import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.io.IOException @RunWith(AndroidJUnit4::class) class TransferDaoUnitTest { @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() private lateinit var transferDao: TransferDao private lateinit var db: WalletDatabase @Before fun createDb() { val context = ApplicationProvider.getApplicationContext<Context>() db = Room.inMemoryDatabaseBuilder(context, WalletDatabase::class.java).build() transferDao = db.transferDao() } @After @Throws(IOException::class) fun closeDb() { db.close() } @Test @Throws(Exception::class) fun createTransferTest() { val transfer = Transfer( 1, 1, 100, 20, "0", "0", 1901176193, 1585643393, "0", TransactionStatus.UNKNOWN, TransactionOutcome.UNKNOWN, TransactionType.TRANSFER ) runBlocking { transferDao.insert(transfer) } val listLiveData = transferDao.getAllAsLiveData() val list = listLiveData.getOrAwaitValue() assertEquals(1, list.size) assertEquals(transfer.amount, list[0].amount) } @Test @Throws(Exception::class) fun transferOrderingNewestFirstTest() { val transfer1 = createTransferWithCreateAt(1) val transfer2 = createTransferWithCreateAt(3) val transfer3 = createTransferWithCreateAt(2) runBlocking { transferDao.insert(transfer1, transfer2, transfer3) } val listLiveData = transferDao.getAllAsLiveData() val list = listLiveData.getOrAwaitValue() assertEquals(3, list.size) assertEquals(3, list[0].createdAt) assertEquals(2, list[1].createdAt) assertEquals(1, list[2].createdAt) } private fun createTransferWithCreateAt(createdAt: Long): Transfer { return Transfer( 0, 1, 100, 20, "0", "0", 1901176193, createdAt, "0", TransactionStatus.UNKNOWN, TransactionOutcome.UNKNOWN, TransactionType.TRANSFER ) } }
9
null
3
9
5a273dbcac459e6c2a94b2b9a241eccfcb229cb9
2,919
concordium-reference-wallet-android
Apache License 2.0
baselibrary/src/main/java/com/ballastlane/android/baselibrary/utils/DateTimeConverter.kt
Ballastlane-LLC
123,138,312
false
null
package com.ballastlane.android.baselibrary.utils import com.google.gson.* import org.joda.time.DateTime import org.joda.time.format.ISODateTimeFormat import java.lang.reflect.Type /** * Created by <NAME> (<EMAIL>) on 8/27/18. * Copyright (c) 2018 Ballast Lane Applications LLC. All rights reserved. */ class DateTimeConverter : JsonSerializer<DateTime>, JsonDeserializer<DateTime> { override fun serialize(src: DateTime, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { val fmt = ISODateTimeFormat.dateTimeParser() return JsonPrimitive(fmt.print(src)) } @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): DateTime? { if (json.asString == null || json.asString.isEmpty()) { return null } val fmt = ISODateTimeFormat.dateTimeParser() return fmt.parseDateTime(json.asString) } companion object { private val TAG = DateTimeConverter::class.java.simpleName } }
1
null
1
1
7b45852160a7ef9c6ae04e7225cd14d5335b300a
1,174
AndroidBaseLibrary
Apache License 2.0
camera/integration-tests/extensionstestapp/src/main/java/androidx/camera/integration/extensions/Constants.kt
androidx
256,589,781
false
null
/* * Copyright 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 androidx.camera.integration.extensions /** Invalid extension mode */ const val INVALID_EXTENSION_MODE = -1 /** Extension is not enabled. Uses a non camera extension session (eg. camera2 or cameraX) */ const val EXTENSION_MODE_NONE = -1 /** Invalid lens facing */ const val INVALID_LENS_FACING = -1 /** Intent extra keys to pass necessary information between the caller and callee activities. */ object IntentExtraKey { /** * Launches the activity with the specified direction of camera. * * Possible values for this intent key are listed in [CameraDirection] */ const val INTENT_EXTRA_KEY_CAMERA_DIRECTION = "camera_direction" /** * Launches the activity with the specified lens facing of camera. * * Possible values for this intent key: [CameraMetadata#LENS_FACING_BACK] or * [CameraMetadata#LENS_FACING_FRONT]. */ const val INTENT_EXTRA_KEY_LENS_FACING = "LensFacing" /** Launches the activity with the specified id of camera. */ const val INTENT_EXTRA_KEY_CAMERA_ID = "camera_id" /** Launches the activity with the specified extension mode. */ const val INTENT_EXTRA_KEY_EXTENSION_MODE = "extension_mode" /** * The captured image will be deleted automatically if the intent used to launch the activity * includes the setting as true. */ const val INTENT_EXTRA_KEY_DELETE_CAPTURED_IMAGE = "delete_captured_image" /** * Launches the activity for the specified test type. * * Possible values for this intent key are listed in [ExtensionTestType] */ const val INTENT_EXTRA_KEY_TEST_TYPE = "TestType" /** Used to pass the captured image Uri to the caller activity. */ const val INTENT_EXTRA_KEY_IMAGE_URI = "ImageUri" /** * Used to pass the rotation degrees fo the captured image to the caller activity to show the * image in correct orientation. */ const val INTENT_EXTRA_KEY_IMAGE_ROTATION_DEGREES = "ImageRotationDegrees" /** Used to pass the request code to the callee activity. */ const val INTENT_EXTRA_KEY_REQUEST_CODE = "RequestCode" /** Used to pass the error code to the caller activity. */ const val INTENT_EXTRA_KEY_ERROR_CODE = "ErrorCode" } /** Camera directions */ object CameraDirection { /** Backward direction */ const val BACKWARD = "BACKWARD" /** Forward direction */ const val FORWARD = "FORWARD" } /** Error Codes for validation activity results */ object ValidationErrorCode { /** No error */ const val ERROR_CODE_NONE = 0 /** Failed to bind the use cases to the lifecycle owner */ const val ERROR_CODE_BIND_TO_LIFECYCLE_FAILED = 1 /** The specified extension mode is not supported */ const val ERROR_CODE_EXTENSION_MODE_NOT_SUPPORT = 2 /** Failed to take picture */ const val ERROR_CODE_TAKE_PICTURE_FAILED = 3 /** Failed to save the captured image */ const val ERROR_CODE_SAVE_IMAGE_FAILED = 4 } /** Extension test types. */ object ExtensionTestType { const val TEST_TYPE_CAMERAX_EXTENSION = "CameraX Extension" const val TEST_TYPE_CAMERA2_EXTENSION = "Camera2 Extension" const val TEST_TYPE_CAMERA2_EXTENSION_STREAM_CONFIG_LATENCY = "Camera2 Extension Stream Config Latency" } /** Test result types */ object TestResultType { /** Extension mode is not supported on the camera device */ const val TEST_RESULT_NOT_SUPPORTED = -1 /** Not tested yet */ const val TEST_RESULT_NOT_TESTED = 0 /** Only part of the tests are tested */ const val TEST_RESULT_PARTIALLY_TESTED = 1 /** All tests have been run and all passed */ const val TEST_RESULT_PASSED = 2 /** All tests have been run and some items are failed */ const val TEST_RESULT_FAILED = 3 }
28
null
937
5,108
89ec14e39cf771106a8719337062572717cbad31
4,407
androidx
Apache License 2.0