path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/backend/ci/ext/tencent/dispatch-kubernetes/biz-dispatch-kubernetes-devcloud-tencent/src/main/kotlin/com/tencent/devops/dispatch/devcloud/pojo/EnvVar.kt | terlinhe | 281,661,499 | true | {"Kotlin": 45598476, "Vue": 6397657, "Java": 5707849, "Go": 3274290, "JavaScript": 1968867, "Lua": 856156, "HTML": 649832, "Dart": 551043, "TypeScript": 411134, "SCSS": 405673, "Shell": 403216, "C++": 149772, "CSS": 95042, "Python": 79300, "Mustache": 65146, "Smarty": 46819, "C": 33502, "Less": 24714, "Dockerfile": 22944, "Makefile": 19753, "Objective-C": 18613, "C#": 9787, "Swift": 8479, "Batchfile": 8243, "Ruby": 6807, "Starlark": 3608, "PowerShell": 840, "VBScript": 189} | package com.tencent.devops.dispatch.devcloud.pojo
data class EnvVar(
val name: String,
val value: String?
)
| 0 | Kotlin | 0 | 0 | dccbcb9f44260f80ebfa1c2dad0c401222f7f93c | 117 | bk-ci | MIT License |
app/src/main/java/de/dertyp7214/rboardthememanager/component/RoundedBottomSheetDialogFragment.kt | GboardThemes | 214,174,139 | false | null | package de.dertyp7214.rboardthememanager.component
import android.app.Dialog
import android.os.Bundle
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import de.dertyp7214.rboardthememanager.R
open class RoundedBottomSheetDialogFragment : BottomSheetDialogFragment() {
override fun getTheme(): Int = R.style.BottomSheetDialogTheme
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
BottomSheetDialog(requireContext(), theme)
} | 0 | Kotlin | 2 | 15 | 602e81773984fd93113dcdda3ce4f7cf3edcaf0b | 551 | Rboard-Theme-Manager | MIT License |
src/main/resources/archetype-resources/src/test/kotlin/pageobjects/Pages.kt | secugrow | 423,127,303 | false | null | package ${package}.pageobjects
enum class PageUrls(val subUrl: String) {
HOME("/"),
SOFTWARETEST("/wiki/Software_testing");
fun getFullUrl(baseUrl: String): String? {
return baseUrl + subUrl
}
}
| 6 | null | 1 | 2 | 137c4383e7b8751e5a1062faa26ca630ef2d0936 | 221 | kotlin-archetype | Apache License 2.0 |
phoenix-ui/src/main/java/com/guoxiaoxing/phoenix/picker/ui/Navigator.kt | lianwt115 | 152,687,979 | false | null | package com.guoxiaoxing.phoenix.picker.ui
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.guoxiaoxing.phoenix.R
import com.guoxiaoxing.phoenix.core.PhoenixOption
import com.guoxiaoxing.phoenix.core.common.PhoenixConstant
import com.guoxiaoxing.phoenix.core.model.MediaEntity
import com.guoxiaoxing.phoenix.picker.rx.bus.ImagesObservable
import com.guoxiaoxing.phoenix.picker.ui.picker.PreviewActivity
import com.guoxiaoxing.phoenix.picker.util.DoubleUtils
import java.io.Serializable
/**
* centralized view navigator.
*
* @author RobinVangYang
* @since 2018-04-12 22:19.
*/
class Navigator {
companion object {
/**
* preview media files, for now, only support images or videos.
*/
fun showPreviewView(activity: Activity, option: PhoenixOption,
previewMediaList: MutableList<MediaEntity>, pickedMediaList: MutableList<MediaEntity>,
currentPosition: Int) {
if (DoubleUtils.isFastDoubleClick) return
ImagesObservable.instance.savePreviewMediaList(previewMediaList)
val bundle = Bundle()
bundle.putParcelable(PhoenixConstant.PHOENIX_OPTION, option)
bundle.putSerializable(PhoenixConstant.KEY_PICK_LIST, pickedMediaList as Serializable)
bundle.putInt(PhoenixConstant.KEY_POSITION, currentPosition)
bundle.putInt(PhoenixConstant.KEY_PREVIEW_TYPE, PhoenixConstant.TYPE_PREIVEW_FROM_PICK)
activity.startActivity(Intent(activity, PreviewActivity::class.java).putExtras(bundle))
activity.overridePendingTransition(R.anim.phoenix_activity_in, 0)
}
}
} | 0 | Kotlin | 2 | 4 | 2fec69b68b593b6eca530019f383d25699b6650b | 1,710 | qmqiu | Apache License 2.0 |
src/Day10.kt | ChAoSUnItY | 572,814,842 | false | null | fun main() {
data class CycleState(
val crtGeneration: Boolean,
var cycle: Int = 0,
var regX: Int = 1,
var rayPosition: Int = 0,
var signalSum: Int = 0,
var crtImage: MutableList<Char> = mutableListOf()
) {
fun processInstruction(instruction: String): CycleState {
val instructionSegments = instruction.split(" ")
when (instructionSegments[0]) {
"noop" -> {
nextCycle(1)
}
"addx" -> {
nextCycle(2)
regX += instructionSegments[1].toInt()
}
else -> {}
}
return this
}
fun nextCycle(cycleCount: Int) {
for (_i in 0 until cycleCount) {
crtImage +=
if (rayPosition >= regX - 1 && rayPosition <= regX + 1) '.'
else '#'
if (crtGeneration && ++rayPosition % 40 == 0) {
rayPosition = 0
crtImage += '\n'
} else if (++cycle == 20 || (cycle - 20) % 40 == 0) {
signalSum += cycle * regX
}
}
}
}
fun part1(data: List<String>): Int =
data.fold(CycleState(false), CycleState::processInstruction).signalSum
fun part2(data: List<String>): String =
data.fold(CycleState(true), CycleState::processInstruction).crtImage.joinToString("")
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 4 | 4fae89104aba1428820821dbf050822750a736bb | 1,607 | advent-of-code-2022-kt | Apache License 2.0 |
game/game_domain/src/main/java/com/ozan/game/domain/GameDomainModule.kt | ozantopuz | 241,085,584 | false | {"Gradle": 13, "Java Properties": 2, "Shell": 1, "Ignore List": 11, "Batchfile": 1, "Markdown": 1, "INI": 10, "Proguard": 9, "Kotlin": 100, "XML": 46, "Java": 12, "JSON": 3, "Text": 7, "SQL": 3, "Gradle Kotlin DSL": 1, "JAR Manifest": 1} | package com.ozan.game.domain
import com.ozan.core.domain.UseCase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
class GameDomainModule {
@Provides
fun provideGamesUseCase(gameRepository: GameRepository):
UseCase.FlowRetrieveUseCase<GamesUseCase.Params, GamesResponse> =
GamesUseCase(gameRepository)
@Provides
fun provideGameUseCase(gameRepository: GameRepository):
UseCase.FlowRetrieveUseCase<GameDetailUseCase.Params, GameDetail> =
GameDetailUseCase(gameRepository)
} | 1 | null | 1 | 1 | 9e81788c0d68b260815e1bc4063b18bca4f31b91 | 649 | ModularApp | Apache License 2.0 |
Common/src/main/java/com/tabnineCommon/lifecycle/CapabilitiesStateSingleton.kt | zxqfl | 199,185,542 | false | null | package com.tabnineCommon.lifecycle
import com.intellij.util.messages.Topic
import com.tabnineCommon.capabilities.Capabilities
import com.tabnineCommon.general.TopicBasedState
import java.util.function.Consumer
class CapabilitiesStateSingleton private constructor() :
TopicBasedState<Capabilities, CapabilitiesStateSingleton.OnChange>(
TOPIC
) {
companion object {
private val TOPIC = Topic.create("com.tabnine.capabilties", OnChange::class.java)
@JvmStatic
val instance = CapabilitiesStateSingleton()
}
public fun interface OnChange : Consumer<Capabilities>
}
| 32 | null | 57 | 509 | 1cc05157fdfd742059be88f00fb92bc58e005a1c | 617 | tabnine-intellij | MIT License |
android/src/com/android/tools/idea/welcome/install/Platform.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.welcome.install
import com.android.SdkConstants
import com.android.repository.Revision
import com.android.repository.api.RemotePackage
import com.android.sdklib.AndroidVersion
import com.android.sdklib.getFullReleaseName
import com.android.sdklib.repository.AndroidSdkHandler
import com.android.sdklib.repository.meta.DetailsTypes
import com.android.tools.idea.flags.StudioFlags
import com.android.tools.idea.progress.StudioLoggerProgressIndicator
/**
*
* Install Android SDK components for developing apps targeting Android platform.
*
* Default selection logic:
* * If the component of this kind are already installed, they cannot be
* unchecked (e.g. the wizard will not uninstall them)
* * If SDK does not have any platforms installed (or this is a new
* SDK installation), then only the latest platform will be installed.
*/
class Platform(
name: String,
description: String,
private val myVersion: AndroidVersion,
private val myIsDefaultPlatform: Boolean,
installUpdates: Boolean
) : InstallableComponent(name, description, installUpdates) {
override val requiredSdkPackages: Collection<String>
get() {
val requests = mutableListOf(DetailsTypes.getPlatformPath(myVersion))
findLatestCompatibleBuildTool()?.let {
requests.add(it)
}
return requests
}
override val optionalSdkPackages: Collection<String>
get() = listOf(DetailsTypes.getSourcesPath(myVersion))
private fun findLatestCompatibleBuildTool(): String? {
var revision: Revision? = null
var path: String? = null
for (remote in repositoryPackages.remotePackages.values) {
if (!remote.path.startsWith(SdkConstants.FD_BUILD_TOOLS)) {
continue
}
val testRevision = remote.version
if (testRevision.major == myVersion.apiLevel && (revision == null || testRevision > revision)) {
revision = testRevision
path = remote.path
}
}
return path
}
override fun configure(installContext: InstallContext, sdkHandler: AndroidSdkHandler) {}
public override fun isOptionalForSdkLocation(): Boolean {
val locals = getInstalledPlatformVersions(sdkHandler)
if (locals.isEmpty()) {
return !myIsDefaultPlatform
}
for (androidVersion in locals) {
// No unchecking if the platform is already installed. We can update but not remove existing platforms
val apiLevel = androidVersion.apiLevel
if (myVersion.featureLevel == apiLevel) {
return false
}
}
return true
}
public override fun isSelectedByDefault(): Boolean = false
companion object {
private fun getPlatformToInstall(remotePackages: Collection<RemotePackage>, installUpdates: Boolean): Platform {
val api: Int = StudioFlags.NPW_COMPILE_SDK_VERSION.get()
val version = AndroidVersion(api, null, AndroidVersion.getBaseExtensionLevel(api).takeIf { it > 0 }, true)
val versionName = version.getFullReleaseName(includeApiLevel = true, includeCodeName = true)
val description = "Android platform libraries for targeting platform: $versionName"
return Platform(versionName, description, version, !version.isPreview, installUpdates)
}
private fun getInstalledPlatformVersions(handler: AndroidSdkHandler?): List<AndroidVersion> {
val result = mutableListOf<AndroidVersion>()
if (handler != null) {
val packages = handler.getSdkManager(StudioLoggerProgressIndicator(Platform::class.java)).packages
for (p in packages.localPackages.values) {
if (p.typeDetails is DetailsTypes.PlatformDetailsType) {
result.add((p.typeDetails as DetailsTypes.PlatformDetailsType).androidVersion)
}
}
}
return result
}
fun createSubtree(remotePackages: Collection<RemotePackage>, installUpdates: Boolean): ComponentTreeNode {
val platformToInstall = getPlatformToInstall(remotePackages, installUpdates)
return ComponentCategory("Android SDK Platform", "SDK components for creating applications for different Android platforms", listOf(platformToInstall))
}
}
} | 5 | Kotlin | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 4,751 | android | Apache License 2.0 |
app/src/main/java/cn/nicolite/huthelper/view/iview/IUserInfoView.kt | djxf | 182,422,481 | false | {"Java": 1266964, "Kotlin": 86335} | package cn.nicolite.huthelper.view.iview
import android.graphics.Bitmap
import cn.nicolite.huthelper.kBase.IBaseView
import cn.nicolite.huthelper.model.bean.ClassTimeTable
import cn.nicolite.huthelper.model.bean.Code
import cn.nicolite.huthelper.model.bean.User
/**
* Created by nicolite on 17-10-28.
*/
interface IUserInfoView : IBaseView {
fun showUserInfo(user: User)
fun changeAvatarSuccess(bitmap: Bitmap)
fun changeAvatar()
fun showDialog(msg : String)
fun getAllClass(allclass : ClassTimeTable)
}
| 1 | Java | 1 | 1 | 3d3fa46850bfe088007603a8deaa0273acbf7d9c | 530 | CampusAssi | Apache License 2.0 |
identity-starter/src/main/kotlin/com/labijie/application/identity/service/impl/AbstractUserService.kt | hongque-pro | 309,874,586 | false | null | package com.labijie.application.identity.service.impl
import com.labijie.application.component.IMessageSender
import com.labijie.application.configuration.ValidationConfiguration
import com.labijie.application.configure
import com.labijie.application.exception.UserNotFoundException
import com.labijie.application.identity.DynamicTableSupport
import com.labijie.application.identity.IdentityCacheKeys
import com.labijie.application.identity.IdentityCacheKeys.getUserCacheKey
import com.labijie.application.identity.IdentityUtils
import com.labijie.application.identity.configuration.IdentityProperties
import com.labijie.application.identity.data.RoleRecord
import com.labijie.application.identity.data.UserRecord
import com.labijie.application.identity.data.UserRoleRecord
import com.labijie.application.identity.data.extensions.*
import com.labijie.application.identity.data.mapper.RoleDynamicSqlSupport.Role
import com.labijie.application.identity.data.mapper.RoleMapper
import com.labijie.application.identity.data.mapper.UserDynamicSqlSupport.User
import com.labijie.application.identity.data.mapper.UserMapper
import com.labijie.application.identity.data.mapper.UserRoleDynamicSqlSupport.UserRole
import com.labijie.application.identity.data.mapper.UserRoleMapper
import com.labijie.application.identity.exception.*
import com.labijie.application.identity.model.RegisterInfo
import com.labijie.application.identity.model.UserAndRoles
import com.labijie.application.identity.service.IUserService
import com.labijie.application.model.OrderBy
import com.labijie.application.removeAfterTransactionCommit
import com.labijie.application.verifySmsCaptcha
import com.labijie.caching.ICacheManager
import com.labijie.caching.getOrSet
import com.labijie.infra.IIdGenerator
import com.labijie.infra.utils.ShortId
import com.labijie.infra.utils.ifNullOrBlank
import org.mybatis.dynamic.sql.SqlBuilder.*
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectList
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.dao.DuplicateKeyException
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.support.TransactionTemplate
import java.time.Clock
import java.time.Duration
import java.time.Instant
/**
* Created with IntelliJ IDEA.
* @author <NAME>
* @date 2019-09-06
*/
abstract class AbstractUserService constructor(
protected val authServerProperties: IdentityProperties,
protected val idGenerator: IIdGenerator,
protected val messageSender: IMessageSender,
protected val cacheManager: ICacheManager,
protected val userMapper: UserMapper,
protected val userRoleMapper: UserRoleMapper,
protected val roleMapper: RoleMapper,
protected val transactionTemplate: TransactionTemplate
) : IUserService, ApplicationContextAware {
protected var context: ApplicationContext? = null
private set
override fun setApplicationContext(applicationContext: ApplicationContext) {
this.context = applicationContext
}
private var encoder: PasswordEncoder? = null
protected var passwordEncoder: PasswordEncoder
get() {
if (encoder == null) {
encoder = this.context?.getBeansOfType(PasswordEncoder::class.java)?.values?.firstOrNull()
?: BCryptPasswordEncoder()
}
return encoder!!
}
set(value) {
encoder = value
}
private var validationConfig: ValidationConfiguration? = null
protected var validationConfiguration: ValidationConfiguration
get() {
if (validationConfig == null) {
validationConfig =
this.context?.getBeansOfType(ValidationConfiguration::class.java)?.values?.firstOrNull()
?: ValidationConfiguration()
}
return validationConfig!!
}
set(value) {
validationConfig = value
}
protected fun getUserAndRoles(
phoneNumber: String,
loginProvider: String? = null
): UserAndRoles {
val user = userMapper.selectOne {
where(User.phoneNumber, isEqualTo(phoneNumber))
} ?: throw UserNotFoundException(
if(loginProvider.isNullOrBlank()) "User was not existed." else "User was not existed (provider: $loginProvider)."
)
val roles = this.getUserRoles(user.id ?: 0)
return UserAndRoles(user, roles)
}
protected fun getUserAndRoles(
userId: Long,
loginProvider: String? = null
): UserAndRoles {
val user = this.getUserById(userId) ?: throw UserNotFoundException(
if(loginProvider.isNullOrBlank()) "User was not existed." else "User was not existed (provider: $loginProvider)."
)
val roles = this.getUserRoles(userId)
return UserAndRoles(user, roles)
}
@Transactional
override fun changePhone(userId: Long, phoneNumber: String, confirmed: Boolean): Boolean {
val u = UserRecord()
u.id = userId
u.phoneNumber = phoneNumber
u.phoneNumberConfirmed = confirmed
u.concurrencyStamp = ShortId.newId()
cacheManager.removeAfterTransactionCommit("u:$userId", authServerProperties.cacheRegion)
val count = userMapper.updateByPrimaryKeySelective(u)
return count == 1
}
protected open fun onRegisteringUser(user: UserAndRoles, addition:String?) {}
protected open fun onRegisteredUser(user: UserAndRoles, addition:String?) {}
override fun registerUser(register: RegisterInfo): UserAndRoles {
val u = this.transactionTemplate.execute {
val p = userMapper.selectOne {
where(User.phoneNumber, isEqualTo(register.phoneNumber))
}
if (p != null) {
throw PhoneAlreadyExistedException()
}
messageSender.verifySmsCaptcha(
register.captcha,
throwIfMissMatched = true
)
val id = idGenerator.newId()
val user = IdentityUtils.createUser(
idGenerator.newId(),
register.username.ifNullOrBlank { "u${id}" },
register.phoneNumber,
passwordEncoder.encode(register.password),
getDefaultUserType()
)
val userAndRoles = this.createUser(user, *this.getDefaultUserRoles())
this.onRegisteringUser(userAndRoles, register.addition)
userAndRoles
}!!
this.onRegisteredUser(u, register.addition)
return u
}
@Transactional
override fun createUser(user: UserRecord, vararg roles: String): UserAndRoles {
val rolesExisted = if (roles.isNotEmpty()) {
val roleEntities = roles.map {
getOrCreateRole(it)
}
roleEntities.forEach {
val key = UserRoleRecord().apply {
this.userId = user.id
this.roleId = it.id
}
userRoleMapper.insert(key)
}
roleEntities
} else {
listOf()
}
try {
userMapper.insert(user)
} catch (e: DuplicateKeyException) {
throw UserAlreadyExistedException()
}
return UserAndRoles(user, rolesExisted)
}
override fun getOrCreateRole(roleName: String): RoleRecord {
val role = roleMapper.selectOne {
where(Role.name, isEqualTo(roleName))
}
return if (role == null) {
val r = RoleRecord().apply {
this.id = idGenerator.newId()
this.concurrencyStamp = ShortId.newId()
this.name = roleName
}
try {
this.transactionTemplate.execute {
roleMapper.insert(r)
r
}!!
} catch (e: DuplicateKeyException) {
roleMapper.selectOne {
where(Role.name, isEqualTo(roleName))
}?: throw RoleNotFoundException(roleName)
}
}else {
role
}
}
@Transactional
override fun setUserEnabled(userId: Long, enabled: Boolean): Boolean {
userMapper.selectByPrimaryKey(userId) ?: throw UserNotFoundException(
userId
)
val lock = if(enabled) Instant.now(Clock.systemUTC()).plusMillis(Duration.ofDays(1).toMillis()).toEpochMilli() else Long.MAX_VALUE
val cacheKey = getUserCacheKey(userId)
cacheManager.removeAfterTransactionCommit(cacheKey, authServerProperties.cacheRegion)
val count = userMapper.update {
set(User.lockoutEnabled).equalTo(enabled)
set(User.lockoutEnd).equalTo(lock)
.where(User.id, isEqualTo(userId))
}
return count > 0
}
override fun getUserById(userId: Long): UserRecord? {
if (userId <= 0) {
return null
}
val key = getUserCacheKey(userId)
return cacheManager.getOrSet(key, authServerProperties.cacheUserTimeout) {
userMapper.selectOne {
where(User.id, isEqualTo(userId))
}
}
}
@Transactional(readOnly = true)
override fun getUsers(pageSize: Int, lastUserId: Long?, order: OrderBy): List<UserRecord> {
if (pageSize < 0) {
return listOf()
}
return userMapper.select {
if(lastUserId != null){
if (order == OrderBy.Ascending) {
where(User.id, isGreaterThan(lastUserId))
} else {
where(User.id, isLessThan(lastUserId))
}
}
if (order == OrderBy.Ascending){
this.orderBy(User.id)
}else{
this.orderBy(User.id.descending())
}
this.limit(pageSize.toLong())
}
}
@Transactional
override fun changePassword(userId: Long, oldPassword: String, newPassword: String): Boolean {
val user = this.userMapper.selectByPrimaryKey(userId) ?: throw UserNotFoundException(
userId
)
if (!passwordEncoder.matches(oldPassword, user.passwordHash)) {
throw InvalidPasswordException("The old password was incorrect.")
}
val passwordHash = passwordEncoder.encode(newPassword)
val cacheKey = getUserCacheKey(userId)
cacheManager.removeAfterTransactionCommit(cacheKey, authServerProperties.cacheRegion)
val count = userMapper.update {
set(User.passwordHash).equalTo(passwordHash)
.where(User.id, isEqualTo(userId))
}
return count == 1
}
@Transactional
override fun addRoleToUser(roleId: Long, userId: Long): Boolean {
userMapper.selectByPrimaryKey(userId) ?: throw UserNotFoundException(userId)
roleMapper.selectByPrimaryKey(roleId) ?: throw RoleNotFoundException(roleId)
val record = UserRoleRecord().apply {
this.roleId = roleId
this.userId = userId
}
val count = userRoleMapper.insert(record)
return count > 0
}
@Transactional
override fun removeRoleFromUser(roleId: Long, userId: Long): Boolean {
val count = userRoleMapper.deleteByPrimaryKey(userId, roleId)
return count == 1
}
private fun fetchAllRoles(): List<RoleRecord> {
val roles = cacheManager.getOrSet(
authServerProperties.jdbcTablePrefix.plus(IdentityCacheKeys.ALL_ROLES),
authServerProperties.cacheRegion,
authServerProperties.cacheRoleTimeout
) { _ ->
transactionTemplate.execute {
val roles = roleMapper.select {
orderBy(Role.name)
}
if (roles.isNotEmpty()) {
roles
} else {
null
}
}
}
return roles ?: listOf()
}
@Transactional
override fun resetPassword(userId: Long, password: String): Boolean {
val u = userMapper.selectOne() {
where(User.id, isEqualTo(userId))
}
if (u != null) {
val passwordHash = passwordEncoder.encode(password)
val cacheKey = getUserCacheKey(userId)
cacheManager.removeAfterTransactionCommit(cacheKey, authServerProperties.cacheRegion)
val count = userMapper.update {
set(User.passwordHash).equalTo(passwordHash)
.where(User.id, isEqualTo(userId))
}
return count > 0
}
return false
}
override fun getUser(usr: String): UserRecord? {
val u = this.transactionTemplate.configure(isReadOnly = true).execute {
getUserByPrimaryField(usr)
}
if (u != null) {
this.cacheManager.set(
"u:${u.id}", u,
authServerProperties.cacheUserTimeout.toMillis()
)
}
return u
}
private fun getUserByPrimaryField(usr: String): UserRecord? {
val id = usr.toLongOrNull()
if(id != null){
return userMapper.selectOne {
where(User.id, isEqualTo(id))
.or(User.phoneNumber, isEqualTo(usr))
.or(User.userName, isEqualTo(usr))
.or(User.email, isEqualTo(usr))
}
}
return userMapper.selectOne {
where(User.phoneNumber, isEqualTo(usr))
.or(User.userName, isEqualTo(usr))
.or(User.email, isEqualTo(usr))
}
}
@Transactional(readOnly = true)
override fun getUserRoles(userId: Long): List<RoleRecord> {
val roleIds = selectList(userRoleMapper::selectMany, listOf(UserRole.roleId), DynamicTableSupport.getTable(UserRole)) {
where(UserRole.userId, isEqualTo(userId))
}.map { it.roleId ?: 0 }
val roles = this.fetchAllRoles()
return roles.filter { roleIds.contains(it.id) }
}
@Transactional
override fun updateUser(userId: Long, user: UserRecord): Boolean {
user.id = userId
val cacheKey = getUserCacheKey(userId)
cacheManager.removeAfterTransactionCommit(cacheKey, authServerProperties.cacheRegion)
return userMapper.updateByPrimaryKeySelective(user) > 0
}
} | 0 | Kotlin | 0 | 5 | e77de3c250b1afa08eda5eb1a57e2ecede59c0c3 | 14,758 | application-framework | Apache License 2.0 |
app/src/main/java/com/steleot/jetpackcompose/playground/compose/ui/PointerInputScreen.kt | Vivecstel | 338,792,534 | false | {"Kotlin": 1538487} | package com.steleot.jetpackcompose.playground.compose.ui
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
//noinspection UsingMaterialAndMaterial3Libraries
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.stringResource
import com.steleot.jetpackcompose.playground.resources.R
import com.steleot.jetpackcompose.playground.navigation.graph.UiNavRoutes
import com.steleot.jetpackcompose.playground.ui.base.material.DefaultScaffold
import kotlinx.coroutines.coroutineScope
private const val URL = "ui/PointerInputScreen.kt"
@Composable
fun PointerInputScreen() {
DefaultScaffold(
title = UiNavRoutes.PointerInput,
link = URL,
) {
var offset by remember { mutableStateOf(Offset.Zero) }
Box(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues = it)
.pointerInput(Unit) {
coroutineScope {
while (true) {
offset = awaitPointerEventScope {
awaitFirstDown().position
}
}
}
}
) {
Text(
stringResource(id = R.string.pointer_input, offset.x, offset.y),
Modifier.align(Alignment.Center)
)
}
}
} | 2 | Kotlin | 46 | 346 | 0161d9c7bf2eee53270ba2227a61d71ba8292ad0 | 1,743 | Jetpack-Compose-Playground | Apache License 2.0 |
kotlin-eclipse-ui/src/org/jetbrains/kotlin/preferences/building/WorkspaceBuildingPropertyPage.kt | bvfalcon | 263,980,575 | false | null | package org.jetbrains.kotlin.preferences.building
import org.eclipse.swt.widgets.Composite
import org.eclipse.swt.widgets.Control
import org.eclipse.ui.IWorkbench
import org.eclipse.ui.IWorkbenchPreferencePage
import org.jetbrains.kotlin.core.preferences.KotlinBuildingProperties
import org.jetbrains.kotlin.preferences.BasePropertyPage
import org.jetbrains.kotlin.preferences.views.buildingPropertiesView
import org.jetbrains.kotlin.swt.builders.asView
class WorkspaceBuildingPropertyPage : BasePropertyPage(), IWorkbenchPreferencePage {
override val properties = KotlinBuildingProperties.workspaceInstance
override fun init(workbench: IWorkbench?) {
}
override fun createUI(parent: Composite): Control =
parent.asView
.buildingPropertiesView(properties) {
onIsValidChanged = { setValid(it) }
}
.control
} | 19 | null | 7 | 43 | e6360b023e1e377325f1d10bda5755e3fc3af591 | 888 | kotlin-eclipse | Apache License 2.0 |
core/src/main/java/com/crocodic/core/extension/FileExtension.kt | yzzzd | 392,866,678 | false | null | package com.crocodic.core.extension
import android.content.Context
import android.graphics.Bitmap
import id.zelory.compressor.Compressor
import id.zelory.compressor.constraint.format
import id.zelory.compressor.constraint.quality
import id.zelory.compressor.constraint.resolution
import id.zelory.compressor.constraint.size
import java.io.File
/**
* Created by @yzzzd on 4/22/18.
*/
suspend fun File.compress(context: Context, prefWidth: Int, prefHeight: Int, prefSize: Long): File {
return Compressor.compress(context, this) {
resolution(prefWidth, prefHeight)
quality(100)
format(Bitmap.CompressFormat.JPEG)
size(prefSize)
}
} | 0 | null | 3 | 3 | d30e5df4a88f00e205a6bb8e7eaf5d5255be50ef | 673 | androidcore | Apache License 1.1 |
app/src/main/java/com/lanazirot/pokedex/domain/models/game/Score.kt | lanazirot | 621,097,461 | false | null | package com.lanazirot.pokedex.domain.models.game
import java.util.*
data class Score(
var score :Int = 0,
var date :Date? = null,
) | 0 | Kotlin | 0 | 1 | 9f473d3b008518797390e2de7afce75c54cdbf3f | 141 | pokedex-jetpack-compose | MIT License |
androidlocation/src/main/java/com/mrcompexpert/loc/permission/PermissionActivity.kt | futurehacker27 | 110,860,004 | false | null | package com.mrcompexpert.loc.permission
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import com.mrcompexpert.loc.util.EXTRA_DATA
import com.mrcompexpert.loc.util.EXTRA_RESULT
import com.mrcompexpert.loc.util.RC_PERM
import com.mrcompexpert.loc.util.hasPermission
class PermissionActivity : Activity() {
lateinit var perms: Array<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setResult(Activity.RESULT_CANCELED)
perms = intent.getStringArrayExtra(EXTRA_DATA)
if (hasPermission(perms) || Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
returnResult()
} else {
requestPermissions(perms, RC_PERM)
}
}
private fun returnResult() {
val intent = Intent()
intent.putExtra(EXTRA_RESULT, hasPermission(perms))
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
Handler().post { returnResult() }
}
} | 0 | Kotlin | 0 | 0 | 473d9a7dce4f7c95c546b1a849b027fc7d9ac645 | 1,272 | AndroidLocation | Apache License 2.0 |
publish-component/src/main/java/com/kotlin/android/publish/component/widget/article/view/entity/ImageElementData.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.publish.component.widget.article.view.entity
import android.net.Uri
import com.kotlin.android.app.data.entity.image.PhotoInfo
import com.kotlin.android.publish.component.widget.article.sytle.TextColor
import com.kotlin.android.publish.component.widget.article.view.safeGet
import com.kotlin.android.publish.component.widget.article.xml.entity.Element
/**
* 图片卡片的数据模型,关联图片相关 Element 元素
*
* Created on 2022/3/30.
*
* @author o.s
*/
class ImageElementData : IElementData {
/**
* 描述文本元素
*/
private var textElement: Element = Element()
/**
* 描述文本段落
*/
private var pElement: Element = Element(
tag = "p",
style = TextColor.GRAY.style,
editable = "false",
items = arrayListOf(textElement)
)
/**
* 图片元素
*/
private var imgElement: Element = Element(
tag = "img",
)
/**
* 描述元素
*/
private var figCaptionElement: Element = Element(
tag = "figcaption",
style = "width: 100%;",
items = arrayListOf(pElement)
)
/**
* 段落根元素
*/
override var element: Element = Element(
tag = "figure",
clazz = "image",
items = arrayListOf(imgElement, figCaptionElement),
)
set(value) {
field = value
value.apply {
items?.find { it.tag == "img" }?.apply {
imgElement = this
}
items?.find { it.tag == "figcaption" }?.apply {
figCaptionElement = this
items?.find { it.tag == "p" }?.apply {
pElement = this
items.safeGet(0)?.apply {
textElement = this
}
}
}
}
}
/**
* 设置图片信息
*/
var photoInfo: PhotoInfo? = null
set(value) {
field = value
value?.let {
url = it.url
uri = it.uri
fileId = it.fileID
imageFormat = it.imageFormat
}
}
/**
* 图片网络url(src)
*/
var url: String? = null
get() = imgElement.src
set(value) {
field = value
imgElement.src = value
}
/**
* 本地图片Uri,提升本地加载速度
*/
var uri: Uri? = null
/**
* 图片上传文件ID
*/
var fileId: String? = null
get() = imgElement.fileId
set(value) {
field = value
imgElement.fileId = value
}
/**
* 图片格式
*/
var imageFormat: String? = null
get() = imgElement.imageFormat
set(value) {
field = value
imgElement.imageFormat = value
}
/**
* 图片描述文本
*/
var text: CharSequence? = null
get() = textElement.text
set(value) {
field = value
textElement.text = value?.toString()
}
} | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 3,013 | Mtime | Apache License 2.0 |
feature/github-search/src/main/java/tech/thdev/githubusersearch/feature/github/holder/search/SearchViewModel.kt | taehwandev | 141,778,287 | false | null | package tech.thdev.githubusersearch.feature.github.holder.search
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import javax.inject.Named
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.retry
import kotlinx.coroutines.launch
import tech.thdev.githubusersearch.design.system.R
import tech.thdev.githubusersearch.domain.github.GitHubSearchRepository
import tech.thdev.githubusersearch.domain.github.model.GitHubSortType
import tech.thdev.githubusersearch.domain.github.model.GitHubUserEntity
import tech.thdev.githubusersearch.feature.github.holder.search.model.SearchUiState
import tech.thdev.githubusersearch.feature.github.holder.search.model.convert.convert
class SearchViewModel @AssistedInject constructor(
private val gitHubSearchRepository: GitHubSearchRepository,
@Assisted isTest: Boolean = false,
) : ViewModel() {
private val _showProgress = MutableStateFlow(false)
val showProgress: StateFlow<Boolean> get() = _showProgress.asStateFlow()
private val _searchUiState = MutableStateFlow(SearchUiState.Default)
val searchUiState: StateFlow<SearchUiState> get() = _searchUiState.asStateFlow()
@VisibleForTesting
val loadData = MutableStateFlow(false)
@VisibleForTesting
val flowSearchKeyword = MutableStateFlow("")
init {
if (isTest.not()) {
loadData()
.launchIn(viewModelScope)
}
}
@OptIn(ExperimentalCoroutinesApi::class)
@VisibleForTesting
fun loadData(): Flow<SearchUiState> =
loadData
.filter { it }
.onEach {
if (flowSearchKeyword.value.isNotEmpty()) {
_showProgress.value = true
}
}
.flatMapLatest { flowSearchKeyword }
.filter { searchKeyword ->
searchKeyword.isNotEmpty()
}
.flatMapLatest { searchKeyword ->
gitHubSearchRepository.flowLoadData(
searchKeyword = searchKeyword,
perPage = 30,
)
}
.map {
it.convert(searchUiState.value)
}
.onEach {
loadData.value = false
_searchUiState.value = it
_showProgress.value = false
}
.retry {
loadData.value = false
_showProgress.value = false
_searchUiState.value = searchUiState.value.copy(
uiState = SearchUiState.UiState.Empty(message = it.message),
)
true
}
fun loadMore(visibleItemCount: Int, totalItemCount: Int, firstVisibleItem: Int) {
if (loadData.value.not() && (firstVisibleItem + visibleItemCount) >= totalItemCount - 10) {
loadData.value = true
}
}
fun searchKeyword() {
flowSearchKeyword.tryEmit(searchUiState.value.searchKeyword)
loadData.value = true
}
fun changeSearchKeyword(keyword: String) {
_searchUiState.value = searchUiState.value.copy(
searchKeyword = keyword,
)
}
fun selectedLikeChange(item: SearchUiState.UiState.UserItems.Info) = viewModelScope.launch {
if (item.isLike) {
gitHubSearchRepository.unlikeUserInfo(id = item.id)
} else {
gitHubSearchRepository.likeUserInfo(
GitHubUserEntity(
id = item.id,
login = item.login,
avatarUrl = item.avatarUrl,
score = item.score,
isLike = false,
)
)
}
}
fun changeSortType(sortType: GitHubSortType) {
gitHubSearchRepository.sortList(sortType)
_searchUiState.value = searchUiState.value.copy(
sortType = sortType,
sortIcon = sortType.sortIcon,
)
}
private val GitHubSortType.sortIcon: Int
get() = when (this) {
GitHubSortType.FILTER_SORT_NAME -> R.drawable.ic_sort_alphabet
GitHubSortType.FILTER_SORT_DATE_OF_REGISTRATION -> R.drawable.ic_sort
else -> R.drawable.ic_sort_numbers
}
override fun onCleared() {
gitHubSearchRepository.clear()
}
@AssistedFactory
interface SearchAssistedFactory {
fun create(@Named("is_test") isTest: Boolean): SearchViewModel
}
companion object {
fun provideFactory(
assistedFactory: SearchAssistedFactory,
isTest: Boolean,
): ViewModelProvider.Factory =
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return assistedFactory.create(isTest) as T
}
}
}
} | 1 | null | 1 | 27 | 5a33cc8a646fe34eaa517a38485c047802bc581d | 5,506 | GithubUserSearch | Apache License 2.0 |
src/main/kotlin/edu/stanford/cfuller/imageanalysistools/filter/OneToOneLabelBySeedFilter.kt | cjfuller | 4,823,440 | false | {"Kotlin": 964294, "Ruby": 12471} | package edu.stanford.cfuller.imageanalysistools.filter
import edu.stanford.cfuller.imageanalysistools.image.WritableImage
import edu.stanford.cfuller.imageanalysistools.image.ImageCoordinate
/**
* A Filter that labels regions in a mask according to the labels in a second (seed) mask.
*
* Each distinct region in the input mask will be assigned
* the label of any seed region that has any pixel overlap with the region in the input mask. If multiple seed regions
* overlap with a single region in the input mask, all the pixels the region in the input mask will be assigned to the same one of those seed values
* (but it is unspecified which one), except for any pixels overlapping directly with a different seed region, which will always
* be assigned the same label as the seed region.
*
* Any regions in the input mask that do not overlap with a seed region will not be changed. This could potentially lead to
* duplicate labeling, so it is a good idea to either use a segmentation method that guarantees that every region has a seed,
* or to first apply a [SeedFilter].
*
* The reference Image should be set to the seed mask (this will not be modified by the Filter).
*
* The argument to the apply method should be set to the mask that is to be labeled according to the labels in the seed Image.
*
* @author <NAME>
*/
class OneToOneLabelBySeedFilter : Filter() {
/**
* Applies the Filter to the specified Image mask, relabeling it according to the seed regions in the reference Image.
* @param im The Image mask to process, whose regions will be relabeled.
*/
override fun apply(im: WritableImage) {
val referenceImage = this.referenceImage ?: throw ReferenceImageRequiredException("MaskFilter requires a reference image.")
val hasSeedSet = java.util.HashMap<Int, Int>()
val seedIsMapped = java.util.HashSet<Int>()
for (c in im) {
val currValue = im.getValue(c).toInt()
val seedValue = referenceImage.getValue(c).toInt()
if (seedValue > 0 && currValue > 0) {
hasSeedSet.put(currValue, seedValue)
}
}
seedIsMapped += hasSeedSet.values
for (c in im) {
val currValue = im.getValue(c).toInt()
if (hasSeedSet.containsKey(currValue) && currValue > 0) {
im.setValue(c, hasSeedSet[currValue]!!.toFloat())
}
if (referenceImage.getValue(c) > 0 && seedIsMapped.contains(referenceImage.getValue(c).toInt())) {
im.setValue(c, referenceImage.getValue(c))
}
}
}
}
| 14 | Kotlin | 0 | 3 | 610f6dbea06120afc23444c3b2a5826aca56700c | 2,628 | imageanalysistools | Apache License 2.0 |
cmpe/common/src/desktopMain/kotlin/com/mcxross/cohesive/cps/JarPluginRepository.kt | mcxross | 514,846,313 | false | null | package com.mcxross.cohesive.cps
import com.mcxross.cohesive.cps.utils.JarFileFilter
import okio.Path
class JarPluginRepository(pluginsRoots: List<Path>) :
BasePluginRepository(pluginsRoots, JarFileFilter()) {
constructor(vararg pluginsRoots: Path) : this(listOf<Path>(*pluginsRoots))
}
| 0 | Kotlin | 0 | 3 | 23050b3bccadcf422c4c37d6a326db08bad0d423 | 293 | cohesive | Apache License 2.0 |
src/main/kotlin/insight/ColorLineMarkerProvider.kt | electronicboy | 567,125,116 | false | null | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2023 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.insight
import com.demonwav.mcdev.MinecraftSettings
import com.intellij.codeInsight.daemon.GutterIconNavigationHandler
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo
import com.intellij.codeInsight.daemon.NavigateAction
import com.intellij.codeInsight.hint.HintManager
import com.intellij.icons.AllIcons
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.psi.JVMElementFactories
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiEditorUtil
import com.intellij.ui.ColorChooser
import com.intellij.util.FunctionUtil
import com.intellij.util.ui.ColorIcon
import com.intellij.util.ui.ColorsIcon
import java.awt.Color
import javax.swing.Icon
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.ULiteralExpression
import org.jetbrains.uast.toUElementOfType
class ColorLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? {
if (!MinecraftSettings.instance.isShowChatColorGutterIcons) {
return null
}
val identifier = element.toUElementOfType<UIdentifier>() ?: return null
val info = identifier.findColor { map, chosen -> ColorInfo(element, chosen.value, map, chosen.key, identifier) }
if (info != null) {
NavigateAction.setNavigateAction(info, "Change Color", null)
}
return info
}
open class ColorInfo : MergeableLineMarkerInfo<PsiElement> {
protected val color: Color
constructor(
element: PsiElement,
color: Color,
map: Map<String, Color>,
colorName: String,
workElement: UElement,
) : super(
element,
element.textRange,
ColorIcon(12, color),
FunctionUtil.nullConstant<Any, String>(),
GutterIconNavigationHandler handler@{ _, psiElement ->
if (psiElement == null || !psiElement.isWritable || !psiElement.isValid || !workElement.isPsiValid) {
return@handler
}
val editor = PsiEditorUtil.findEditor(psiElement) ?: return@handler
val picker = ColorPicker(map, editor.component)
val newColor = picker.showDialog()
if (newColor != null && map[newColor] != color) {
workElement.setColor(newColor)
}
},
GutterIconRenderer.Alignment.RIGHT,
{ "$colorName color indicator" },
) {
this.color = color
}
constructor(element: PsiElement, color: Color, handler: GutterIconNavigationHandler<PsiElement>) : super(
element,
element.textRange,
ColorIcon(12, color),
FunctionUtil.nullConstant<Any, String>(),
handler,
GutterIconRenderer.Alignment.RIGHT,
{ "color indicator" },
) {
this.color = color
}
override fun canMergeWith(info: MergeableLineMarkerInfo<*>) = info is ColorInfo
override fun getCommonIconAlignment(infos: List<MergeableLineMarkerInfo<*>>) =
GutterIconRenderer.Alignment.RIGHT
override fun getCommonIcon(infos: List<MergeableLineMarkerInfo<*>>): Icon {
if (infos.size == 2 && infos[0] is ColorInfo && infos[1] is ColorInfo) {
return ColorsIcon(12, (infos[0] as ColorInfo).color, (infos[1] as ColorInfo).color)
}
return AllIcons.Gutter.Colors
}
override fun getCommonTooltip(infos: List<MergeableLineMarkerInfo<*>>) =
FunctionUtil.nullConstant<PsiElement, String>()
}
class CommonColorInfo(
element: PsiElement,
color: Color,
workElement: UElement,
) : ColorInfo(
element,
color,
GutterIconNavigationHandler handler@{ _, psiElement ->
if (psiElement == null || !psiElement.isValid ||
!workElement.isPsiValid || workElement.sourcePsi?.isWritable != true
) {
return@handler
}
val editor = PsiEditorUtil.findEditor(psiElement) ?: return@handler
if (JVMElementFactories.getFactory(psiElement.language, psiElement.project) == null) {
// The setColor methods used here require a JVMElementFactory. Unfortunately the Kotlin plugin does not
// implement it yet. It is better to not display the color chooser at all than deceiving users after
// after they chose a color
HintManager.getInstance()
.showErrorHint(editor, "Can't change colors in " + psiElement.language.displayName)
return@handler
}
val c = ColorChooser.chooseColor(psiElement.project, editor.component, "Choose Color", color, false)
?: return@handler
when (workElement) {
is ULiteralExpression -> workElement.setColor(c.rgb and 0xFFFFFF)
is UCallExpression -> workElement.setColor(c.red, c.green, c.blue)
}
},
)
abstract class CommonLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? {
val pair = findColor(element) ?: return null
val info = CommonColorInfo(element, pair.first, pair.second)
NavigateAction.setNavigateAction(info, "Change color", null)
return info
}
abstract fun findColor(element: PsiElement): Pair<Color, UElement>?
}
}
| 204 | null | 152 | 2 | 72e07820f1317ddf432f4c60b03e2109e197b69f | 5,979 | crispy-waddle | MIT License |
src/main/kotlin/org/jaqpot/api/cache/CacheConfiguration.kt | ntua-unit-of-control-and-informatics | 790,773,279 | false | {"Kotlin": 176168, "FreeMarker": 2174} | package org.jaqpot.api.cache
import com.github.benmanes.caffeine.cache.Caffeine
import org.jaqpot.api.cache.keygenerator.OrganizationsByUserKeyGenerator
import org.springframework.cache.CacheManager
import org.springframework.cache.caffeine.CaffeineCacheManager
import org.springframework.cache.interceptor.KeyGenerator
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.util.concurrent.TimeUnit
@Configuration
class CacheConfiguration {
@Bean
fun caffeineConfig(): Caffeine<Any, Any> {
return Caffeine.newBuilder().maximumWeight(1_000).expireAfterWrite(5, TimeUnit.MINUTES)
}
@Bean
fun cacheManager(caffeine: Caffeine<Any, Any>): CacheManager {
val manager = CaffeineCacheManager()
manager.registerCustomCache(
CacheKeys.ALL_PUBLIC_ORGANIZATIONS,
Caffeine.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build()
)
manager.registerCustomCache(
CacheKeys.USER_ORGANIZATIONS,
Caffeine.newBuilder()
.maximumSize(2000)
.expireAfterAccess(5, TimeUnit.MINUTES)
.build()
)
manager.registerCustomCache(
CacheKeys.SEARCH_MODELS,
Caffeine.newBuilder()
.maximumSize(500)
.expireAfterAccess(1, TimeUnit.HOURS)
.build()
)
return manager
}
@Bean("organizationsByUserKeyGenerator")
fun keyGenerator(): KeyGenerator {
return OrganizationsByUserKeyGenerator()
}
}
| 0 | Kotlin | 0 | 0 | 5707aed75155d3955865b68f6b5678c451b0cd93 | 1,650 | jaqpot-api | MIT License |
src/main/kotlin/g2801_2900/s2895_minimum_processing_time/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2801_2900.s2895_minimum_processing_time
// #Medium #Array #Sorting #Greedy #2023_12_21_Time_662_ms_(80.00%)_Space_69.1_MB_(40.00%)
class Solution {
fun minProcessingTime(processorTime: List<Int>, tasks: List<Int>): Int {
val proc = IntArray(processorTime.size)
run {
var i = 0
val n = processorTime.size
while (i < n) {
proc[i] = processorTime[i]
i++
}
}
val jobs = IntArray(tasks.size)
run {
var i = 0
val n = tasks.size
while (i < n) {
jobs[i] = tasks[i]
i++
}
}
proc.sort()
jobs.sort()
var maxTime = 0
var i = 0
val n = proc.size
while (i < n) {
val procTime = proc[i] + jobs[jobs.size - 1 - i * 4]
if (procTime > maxTime) {
maxTime = procTime
}
i++
}
return maxTime
}
}
| 0 | Kotlin | 20 | 43 | 471d45c60f669ea1a2e103e6b4d8d54da55711df | 1,029 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/g2801_2900/s2895_minimum_processing_time/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2801_2900.s2895_minimum_processing_time
// #Medium #Array #Sorting #Greedy #2023_12_21_Time_662_ms_(80.00%)_Space_69.1_MB_(40.00%)
class Solution {
fun minProcessingTime(processorTime: List<Int>, tasks: List<Int>): Int {
val proc = IntArray(processorTime.size)
run {
var i = 0
val n = processorTime.size
while (i < n) {
proc[i] = processorTime[i]
i++
}
}
val jobs = IntArray(tasks.size)
run {
var i = 0
val n = tasks.size
while (i < n) {
jobs[i] = tasks[i]
i++
}
}
proc.sort()
jobs.sort()
var maxTime = 0
var i = 0
val n = proc.size
while (i < n) {
val procTime = proc[i] + jobs[jobs.size - 1 - i * 4]
if (procTime > maxTime) {
maxTime = procTime
}
i++
}
return maxTime
}
}
| 0 | Kotlin | 20 | 43 | 471d45c60f669ea1a2e103e6b4d8d54da55711df | 1,029 | LeetCode-in-Kotlin | MIT License |
kotlin.web.demo.server/examples/Kotlin in Action/Chapter 2/2.3/1_1_colors.kt | arrow-kt | 117,599,238 | true | {"Shell": 3, "Gradle": 21, "Text": 15, "YAML": 3, "INI": 4, "Java Properties": 12, "Ignore List": 2, "Batchfile": 1, "XML": 23, "Markdown": 45, "JSON": 152, "HTML": 3, "JavaScript": 20, "Kotlin": 546, "SVG": 16, "CSS": 19, "AsciiDoc": 1, "Java": 109, "JAR Manifest": 2, "SQL": 2, "Dockerfile": 3} | package ch02.colors
enum class Color {
RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET
}
| 2 | Kotlin | 2 | 7 | 7165d9568d725c9784a1e7525f35bab93241f292 | 95 | try.arrow-kt.io | Apache License 2.0 |
basic/sources/JSONException.kt | cybernetics | 196,933,210 | true | {"Kotlin": 640246} | package com.github.fluidsonic.fluid.json
abstract class JSONException(
message: String,
val offset: Int = -1,
val path: JSONPath? = null,
cause: Throwable? = null
) : RuntimeException(message, cause) {
override val message
get() = buildMessage(
message = super.message ?: "",
offset = offset,
path = path
)
companion object {
private fun buildMessage(
message: String,
offset: Int,
path: JSONPath?
) = buildString {
if (path != null) {
append("at ")
append(path.toString())
append(": ")
}
append(message)
if (offset >= 0) {
append(" - at position ")
append(offset)
}
}
}
class Parsing(
message: String,
offset: Int = -1,
path: JSONPath? = null,
cause: Throwable? = null
) : JSONException(message = message, offset = offset, path = path, cause = cause) {
companion object
}
class Schema(
message: String,
offset: Int = -1,
path: JSONPath? = null,
cause: Throwable? = null
) : JSONException(message = message, offset = offset, path = path, cause = cause) {
companion object
}
class Serialization(
message: String,
path: JSONPath? = null,
cause: Throwable? = null
) : JSONException(message = message, path = path, cause = cause) {
companion object
}
class Syntax(
message: String,
offset: Int = -1,
path: JSONPath? = null,
cause: Throwable? = null
) : JSONException(message = message, offset = offset, path = path, cause = cause) {
companion object
}
}
| 0 | Kotlin | 0 | 0 | e1991962108950fbeed46aa0e1f2dbaab2493bef | 1,490 | fluid-json | Apache License 2.0 |
attribouter/src/main/java/me/jfenn/attribouter/dialogs/UserDialog.kt | fennifith | 124,246,346 | false | null | package me.jfenn.attribouter.dialogs
import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.InsetDrawable
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatDialog
import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import me.jfenn.androidutils.bind
import me.jfenn.androidutils.dpToPx
import me.jfenn.androidutils.getThemedColor
import me.jfenn.attribouter.R
import me.jfenn.attribouter.adapters.WedgeAdapter
import me.jfenn.attribouter.utils.ResourceUtils.getString
import me.jfenn.attribouter.utils.getThemeAttr
import me.jfenn.attribouter.utils.getThemedInt
import me.jfenn.attribouter.utils.loadDrawable
import me.jfenn.attribouter.wedges.ContributorWedge
import me.jfenn.attribouter.wedges.LinkWedge
open class UserDialog(
context: Context,
private val contributor: ContributorWedge
) : AppCompatDialog(
context,
context.getThemeAttr(R.attr.attribouter_userDialogTheme, R.style.AttribouterTheme_Dialog)
) {
private val nameView: TextView? by bind(R.id.name)
private val taskView: TextView? by bind(R.id.task)
private val imageView: ImageView? by bind(R.id.image)
private val bioView: TextView? by bind(R.id.description)
private val recycler: RecyclerView? by bind(R.id.links)
override fun onStart() {
super.onStart()
window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
// create rounded dialog corners according to cardCornerRadius attr
val drawable = GradientDrawable()
drawable.setColor(context.getThemedColor(R.attr.attribouter_cardColor))
drawable.cornerRadius = context.getThemedInt(R.attr.attribouter_cardCornerRadius).toFloat()
window?.setBackgroundDrawable(InsetDrawable(drawable, dpToPx(16f)))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.attribouter_dialog_user)
nameView?.text = getString(context, contributor.getCanonicalName())
taskView?.text = getString(context, contributor.task)
bioView?.text = getString(context, contributor.bio)
context.loadDrawable(contributor.avatar, R.drawable.attribouter_image_avatar) {
imageView?.setImageDrawable(it)
}
val links = contributor.getTypedChildren<LinkWedge>()
if (links.isNotEmpty()) {
recycler?.apply {
visibility = View.VISIBLE
layoutManager = object : FlexboxLayoutManager(context) {
// Hacky workaround for wrap_content bug: https://github.com/google/flexbox-layout/issues/349
// - some items will occasionally get cut off because of this, but meh
override fun canScrollVertically(): Boolean = false
}.apply {
flexDirection = FlexDirection.ROW
justifyContent = JustifyContent.CENTER
}
adapter = WedgeAdapter(links.filter { !it.isHidden }.sorted())
}
} else recycler?.visibility = View.GONE
}
} | 5 | Kotlin | 14 | 120 | bfa65610b55a1b88673a321dd3bdd9ac409cf6a0 | 3,437 | Attribouter | Apache License 2.0 |
idea/tests/org/jetbrains/kotlin/psi/StringTemplateExpressionManipulatorTest.kt | arrow-kt | 109,678,056 | false | null | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.psi
import com.intellij.openapi.util.TextRange
import com.intellij.psi.ElementManipulators
import com.intellij.testFramework.LoggedErrorProcessor
import org.apache.log4j.Logger
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor
class StringTemplateExpressionManipulatorTest : KotlinLightCodeInsightFixtureTestCase() {
fun testSingleQuoted() {
doTestContentChange("\"a\"", "b", "\"b\"")
doTestContentChange("\"\"", "b", "\"b\"")
doTestContentChange("\"a\"", "\t", "\"\\t\"")
doTestContentChange("\"a\"", "\n", "\"\\n\"")
doTestContentChange("\"a\"", "\\t", "\"\\\\t\"")
}
fun testUnclosedQuoted() {
doTestContentChange("\"a", "b", "\"b")
doTestContentChange("\"", "b", "\"b")
doTestContentChange("\"a", "\t", "\"\\t")
doTestContentChange("\"a", "\n", "\"\\n")
doTestContentChange("\"a", "\\t", "\"\\\\t")
}
fun testTripleQuoted() {
doTestContentChange("\"\"\"a\"\"\"", "b", "\"\"\"b\"\"\"")
doTestContentChange("\"\"\"\"\"\"", "b", "\"\"\"b\"\"\"")
doTestContentChange("\"\"\"a\"\"\"", "\t", "\"\"\"\t\"\"\"")
doTestContentChange("\"\"\"a\"\"\"", "\n", "\"\"\"\n\"\"\"")
doTestContentChange("\"\"\"a\"\"\"", "\\t", "\"\"\"\\t\"\"\"")
}
fun testUnclosedTripleQuoted() {
doTestContentChange("\"\"\"a", "b", "\"\"\"b")
doTestContentChange("\"\"\"", "b", "\"\"\"b")
doTestContentChange("\"\"\"a", "\t", "\"\"\"\t")
doTestContentChange("\"\"\"a", "\n", "\"\"\"\n")
doTestContentChange("\"\"\"a", "\\t", "\"\"\"\\t")
}
fun testReplaceRange() {
doTestContentChange("\"abc\"", "x", range = TextRange(2,3), expected = "\"axc\"")
doTestContentChange("\"\"\"abc\"\"\"", "x", range = TextRange(4,5), expected = "\"\"\"axc\"\"\"")
doTestContentChange(
"\"<div style = \\\"default\\\">\${foo(\"\")}</div>\"",
"custom", range = TextRange(16, 23),
expected = "\"<div style = \\\"custom\\\">\${foo(\"\")}</div>\""
)
}
fun testHackyReplaceRange() {
suppressFallingOnLogError {
doTestContentChange("\"a\\\"bc\"", "'", range = TextRange(0, 4), expected = "'bc\"")
}
}
fun testTemplateWithInterpolation() {
doTestContentChange("\"<div>\${foo(\"\")}</div>\"", "<p>\${foo(\"\")}</p>", "\"<p>\${foo(\"\")}</p>\"")
doTestContentChange(
"\"<div style = \\\"default\\\">\${foo(\"\")}</div>\"",
"<p style = \"custom\">\${foo(\"\")}</p>",
"\"<p style = \\\"custom\\\">\${foo(\"\")}</p>\""
)
}
private fun doTestContentChange(original: String, newContent: String, expected: String, range: TextRange? = null) {
val expression = KtPsiFactory(project).createExpression(original) as KtStringTemplateExpression
val manipulator = ElementManipulators.getNotNullManipulator(expression)
val newExpression = if (range == null) manipulator.handleContentChange(expression, newContent) else manipulator.handleContentChange(expression, range, newContent)
assertEquals(expected, newExpression?.text)
}
override fun getProjectDescriptor() = KotlinLightProjectDescriptor.INSTANCE
}
private fun <T> suppressFallingOnLogError(call: () -> T) {
val loggedErrorProcessor = LoggedErrorProcessor.getInstance()
try {
LoggedErrorProcessor.setNewInstance(object : LoggedErrorProcessor() {
override fun processError(message: String?, t: Throwable?, details: Array<out String>?, logger: Logger) {}
})
call()
} finally {
LoggedErrorProcessor.setNewInstance(loggedErrorProcessor)
}
} | 12 | null | 1 | 43 | d2a24985b602e5f708e199aa58ece652a4b0ea48 | 4,432 | kotlin | Apache License 2.0 |
api/library/kotlin-simple-api-client/src/commonMain/kotlin/kim/jeonghyeon/net/HttpClientBaseEx.kt | dss99911 | 138,060,985 | false | null | package kim.jeonghyeon.net
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.features.*
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.content.*
import io.ktor.http.*
import kim.jeonghyeon.annotation.ApiParameterType
import kim.jeonghyeon.annotation.SimpleArchInternal
import kim.jeonghyeon.net.SimpleApiUtil.isKotlinXSerializer
import kim.jeonghyeon.net.SimpleApiUtil.toJsonElement
import kim.jeonghyeon.net.error.ApiError
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.encodeToJsonElement
expect fun Throwable.isConnectException(): Boolean
@SimpleArchInternal
object SimpleApiUtil {
@OptIn(ExperimentalStdlibApi::class)
suspend inline fun <reified RET> HttpClient.callApi(
callInfo: ApiCallInfo,
requestResponseAdapter: RequestResponseAdapter
): RET {
requestResponseAdapter.beforeBuildRequest(callInfo, this)
var response: HttpResponse? = null
try {
response = requestApi(callInfo, requestResponseAdapter)
val returnValue = requestResponseAdapter.transformResponse<RET>(response, callInfo, typeInfo<RET>())
setResponse(response)//`freeze` error occurs if call before readText()
return returnValue
} catch (e: Exception) {
response?.let { setResponse(it) }
if (e is ApiError || e is DeeplinkError) {
throw e
}
return requestResponseAdapter.handleException(e, callInfo, typeInfo<RET>())
}
}
inline fun <reified T : Any?> T.toParameterString(client: HttpClient): String? {
if (this == null) {
return null
}
return when (this) {
is String -> this
is Enum<*> -> this.name
else -> {
if (client.isKotlinXSerializer()) {
Json {}.encodeToString(this)//with below, generic type has error, so, use this way.
} else {
(client.feature(JsonFeature)!!.serializer.write(this) as TextContent).text
}
}
}
}
inline fun <reified T> T.toJsonElement(client: HttpClient): JsonElement? =
if (client.isKotlinXSerializer()) {
Json {}.encodeToJsonElement(this)
} else {
null
}
suspend fun HttpClient.requestApi(
callInfo: ApiCallInfo,
requestResponseAdapter: RequestResponseAdapter
) = request<HttpResponse> {
url.takeFrom(callInfo.buildPath())
method = callInfo.method
callInfo.body(this@requestApi)?.let { body = it }
if (callInfo.isJsonContentType()) {
contentType(ContentType.Application.Json)
}
callInfo.queries().forEach {
parameter(it.first, it.second)
}
callInfo.headers().forEach {
header(it.first, it.second)
}
requestResponseAdapter.buildRequest(this, callInfo)
}
fun HttpClient.isKotlinXSerializer(): Boolean {
return feature(JsonFeature)!!.serializer::class == KotlinxSerializer::class
}
}
/**
* todo make concrete logic or use some basic kotlin function
*/
fun String.isUri(): Boolean = contains("://")
data class ApiCallInfo(
val baseUrl: String,
val mainPath: String,
val subPath: String,
val className: String,//if there is no customization, className and mainPath is same
val functionName: String,//if there is no customization, subPath and functionName is same
val method: HttpMethod,
val isAuthRequired: Boolean,
val parameters: List<ApiParameterInfo>,
val parameterBinding: Map<Int, String> = emptyMap()
) {
fun buildPath(): String {
return baseUrl connectPath mainPath connectPath subPath.let {
var replacedSubPath = it
parameters.filter { it.type == ApiParameterType.PATH }.forEach {
replacedSubPath = replacedSubPath.replace("{${it.key}}", it.value.toString())
}
replacedSubPath
}
}
@OptIn(SimpleArchInternal::class)
fun body(client: HttpClient): Any? {
parameters.firstOrNull { it.type == ApiParameterType.BODY }?.getBodyOrJsonElement()?.let {
return it
}
val bodyParameters = parameters.filter { it.type == ApiParameterType.NONE }
if (bodyParameters.isEmpty()) {
return null
}
return if (client.isKotlinXSerializer()) {
buildJsonObject {
bodyParameters.forEach {
put(it.parameterName, (it.bodyJsonElement?:return@forEach))
}
}
} else {
bodyParameters.associate { Pair(it.parameterName, it.body) }
}
}
fun isJsonContentType() = when (method) {
HttpMethod.Post, HttpMethod.Put, HttpMethod.Delete, HttpMethod.Patch -> true
else -> false
}
fun queries() = parameters.filter { it.type == ApiParameterType.QUERY }
.map { it.key!! to it.value }
fun headers() = parameters.filter { it.type == ApiParameterType.HEADER }
.map { it.key!! to it.value }
private infix fun String.connectPath(end: String): String {
if (isEmpty() || end.isEmpty()) return this + end
if (end.isUri()) {
return end
}
return if (last() == '/' && end.first() == '/') {
take(lastIndex) + end
} else if (last() != '/' && end.first() != '/') {
"$this/$end"
} else this + end
}
}
/**
* @param key if it's [ApiParameterType.BODY], [ApiParameterType.NONE] type, there is no key
* @param value if it's [ApiParameterType.BODY], [ApiParameterType.NONE] type, this is null
* @param body if it's [ApiParameterType.BODY], [ApiParameterType.NONE] type, this exists.
*/
data class ApiParameterInfo(
val type: ApiParameterType,
val parameterName: String,//todo this seems not required
val key: String?,
val value: String?,
val body: Any?,
val bodyJsonElement: JsonElement?,
) {
fun getBodyOrJsonElement(): Any? {
return body?:bodyJsonElement
}
} | 1 | null | 2 | 38 | e9da57fdab9c9c1169fab422fac7432143e2c02c | 6,682 | kotlin-simple-architecture | Apache License 2.0 |
example/app-shell/shell-base/src/main/java/com/t/example_shell_webview/MockBaseApplication.kt | joyrun | 64,625,768 | false | null | package com.t.example_shell_webview
import android.app.Application
import android.content.Context
import com.alibaba.fastjson.JSON
import com.grouter.GComponentCenter
import com.grouter.GRouter
import com.grouter.demo.base.model.User
import com.grouter.demo.base.service.UserService
import com.t.example_shell_base.BuildConfig
import org.mockito.Mockito
import org.mockito.Mockito.mock
open class MockBaseApplication:Application() {
override fun onCreate() {
super.onCreate()
GRouter.setSerialization(object : GRouter.Serialization {
override fun serialize(any: Any): String {
return JSON.toJSONString(any)
}
override fun <T> deserializeObject(json: String, clazz: Class<T>): T? {
return JSON.parseObject(json, clazz)
}
override fun <T> deserializeList(json: String, clazz: Class<T>): List<T>? {
return JSON.parseArray(json, clazz)
}
})
GRouter.getInstance().init(this, BuildConfig.BUILD_TYPE, null)
System.setProperty("org.mockito.android.target",getDir("target", Context.MODE_PRIVATE).absolutePath)
}
} | 0 | Java | 67 | 378 | 6db9a3671e173eec56481c1a1adc1b4238933c9f | 1,176 | ActivityRouter | Apache License 2.0 |
common/common.consul/common.consul.model/src/main/kotlin/org/eclipse/slm/common/consul/model/acl/BindingRule.kt | NicoleSauer | 641,778,884 | true | {"JSON": 26, "Maven POM": 62, "Markdown": 30, "Git Attributes": 1, "Text": 2, "Ignore List": 6, "YAML": 184, "XML": 7, "Java": 316, "Kotlin": 208, "HTTP": 11, "JavaScript": 67, "Dotenv": 7, "JSON with Comments": 2, "Dockerfile": 25, "Browserslist": 1, "HTML": 2, "Vue": 117, "SCSS": 2, "Sass": 15, "SVG": 2, "HCL": 16, "Shell": 15, "Nginx": 3, "SQL": 1, "Python": 1, "Java Properties": 1, "CSS": 3, "INI": 5, "Fluent": 1, "PowerShell": 3, "Stylus": 2, "OASv3-yaml": 1} | package org.eclipse.slm.common.consul.model.acl
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import java.util.*
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
class BindingRule {
@JsonProperty("Description")
var description: String = ""
@JsonProperty("AuthMethod")
var authMethod: String = ""
@JsonProperty("Selector")
var selector: String = ""
@JsonProperty("BindType")
var bindType: String = ""
@JsonProperty("BindName")
var bindName: String = ""
@JsonProperty("ID", required = false)
var id: String? = null
@JsonProperty("CreateIndex", required = false)
var createIndex: Long? = null
@JsonProperty("ModifyIndex", required = false)
var modifyIndex: Long? = null
constructor(){}
constructor(description: String, authMethod: String, selector: String, bindType: String, bindName: String){
this.description = description
this.authMethod = authMethod
this.selector = selector
this.bindType = bindType
this.bindName = bindName
}
}
| 0 | Java | 0 | 0 | 53b93783823c1a4f481e977d380cb7942d6798c6 | 1,214 | slm | Apache License 2.0 |
recyclerview/src/main/java/com/tunjid/androidx/recyclerview/multiscroll/RecyclerViewMultiScroller.kt | tunjid | 89,848,117 | false | {"Kotlin": 436389, "Java": 77823} | package com.tunjid.androidx.recyclerview.multiscroll
import android.view.MotionEvent
import android.view.View
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
/**
* A class that synchronizes scrolling multiple [RecyclerView]s, useful for creating tables.
*
* It is optimized around usage with a [LinearLayoutManager]. The [CellSizer] provides information
* on how large a cell is in any row to keep all [RecyclerView] instances synchronized
*/
class RecyclerViewMultiScroller(
@RecyclerView.Orientation
private val orientation: Int = RecyclerView.HORIZONTAL,
private val cellSizer: CellSizer = DynamicCellSizer(orientation)
) {
var displacement = 0
private set
private var active: RecyclerView? = null
private val syncedScrollers = mutableSetOf<RecyclerView>()
private val displacementListeners = mutableListOf<(Int) -> Unit>()
private val onScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (orientation == RecyclerView.HORIZONTAL && dx == 0) return
if (orientation == RecyclerView.VERTICAL && dy == 0) return
if (active != null && recyclerView != active) return
active = recyclerView
syncedScrollers.forEach { if (it != recyclerView) it.scrollBy(dx, dy) }
displacement += if (orientation == RecyclerView.HORIZONTAL) dx else dy
displacementListeners.forEach { it(displacement) }
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if (active != recyclerView) return
displacementListeners.forEach { it(displacement) }
if (newState == RecyclerView.SCROLL_STATE_IDLE) active = null
}
}
private val onAttachStateChangeListener = object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View?) {
if (v is RecyclerView) include(v)
}
override fun onViewDetachedFromWindow(v: View?) {
if (v is RecyclerView) exclude(v)
}
}
private val onItemTouchListener = object : RecyclerView.SimpleOnItemTouchListener() {
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
// If the user flung the list, then touches any other synced list, stop scrolling
if (e.actionMasked == MotionEvent.ACTION_DOWN && active != null) active?.stopScroll()
return when (active) {
null -> false // return false if active is null, we aren't trying to override default scrolling
else -> rv != active // Ignore touches on other RVs while scrolling is occurring
}
}
}
fun clear() {
active = null
displacementListeners.clear()
syncedScrollers.clear(this::remove)
cellSizer.clear()
}
fun add(recyclerView: RecyclerView) {
if (syncedScrollers.contains(recyclerView)) return
include(recyclerView)
recyclerView.addOnAttachStateChangeListener(onAttachStateChangeListener)
}
fun remove(recyclerView: RecyclerView) {
exclude(recyclerView)
recyclerView.removeOnAttachStateChangeListener(onAttachStateChangeListener)
}
fun addDisplacementListener(listener: (Int) -> Unit) {
if (displacementListeners.contains(listener)) return
displacementListeners.add(listener)
listener(displacement)
}
@Suppress("unused")
fun removeDisplacementListener(listener: (Int) -> Unit) {
displacementListeners.remove(listener)
}
private fun include(recyclerView: RecyclerView) {
recyclerView.onIdle {
if (syncedScrollers.contains(recyclerView)) return@onIdle
recyclerView.sync()
syncedScrollers.add(recyclerView)
cellSizer.include(recyclerView)
recyclerView.addOnScrollListener(onScrollListener)
recyclerView.addOnItemTouchListener(onItemTouchListener)
}
if (!ViewCompat.isLaidOut(recyclerView) || recyclerView.isLayoutRequested) recyclerView.requestLayout()
}
private fun exclude(recyclerView: RecyclerView) {
recyclerView.removeOnItemTouchListener(onItemTouchListener)
recyclerView.removeOnScrollListener(onScrollListener)
cellSizer.exclude(recyclerView)
syncedScrollers.remove(recyclerView)
}
private fun RecyclerView.sync() {
var offset = displacement
var position = 0
while (offset > 0) {
offset -= cellSizer.sizeAt(position)
position++
}
when (val layoutManager = layoutManager) {
null -> Unit
is LinearLayoutManager -> layoutManager.scrollToPositionWithOffset(position, -offset)
else -> layoutManager.scrollToPosition(position)
}
}
}
| 5 | Kotlin | 60 | 595 | efdc0dcf5559984a36a8bed4cff6257f20e6e07d | 5,027 | Android-Extensions | MIT License |
appreader/src/main/java/com/ul/ims/gmdl/reader/util/SettingsUtils.kt | prashantkspatil | 284,531,234 | true | {"Gradle": 11, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 10, "Batchfile": 1, "Markdown": 5, "Proguard": 9, "XML": 45, "Java": 36, "INI": 2, "Kotlin": 233} | /*
* Copyright (C) 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ul.ims.gmdl.reader.util
import android.content.Context
import androidx.preference.PreferenceManager
import com.ul.ims.gmdl.offlinetransfer.transportLayer.EngagementChannels
object SettingsUtils {
fun getEngagementMethod(context: Context): EngagementChannels {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val qr = sharedPreferences.getBoolean("engagement_method_qr", false)
val nfc = sharedPreferences.getBoolean("engagement_method_nfc", false)
return when {
qr -> EngagementChannels.QR
nfc -> EngagementChannels.NFC
else -> throw IllegalStateException("Unable to get Engagement Method from shared preferences")
}
}
}
| 0 | Kotlin | 0 | 0 | a6c3a6077ef5e7774ff70929ae4f33968ce6f598 | 1,352 | mdl-ref-apps | Apache License 2.0 |
app/src/main/java/com/qlang/eyepetizer/bean/dynamic.kt | qlang122 | 309,645,125 | false | null | package com.qlang.eyepetizer.bean
class DynamicInfo(
val data: DynamicBody?,
val type: String?,
val tag: Any?,
val id: Int?,
val adIndex: Int?) : BaseInfo() {
}
class DynamicBody(
val dataType: String?,
val dynamicType: String?,
val text: String?,
val actionUrl: String?,
val mergeNickName: String?,
val mergeSubTitle: String?,
val merge: Boolean?,
val createDate: Long?,
val user: User?,
val simpleVideo: VideoClientInfo?,
val reply: DynamicReply?) : BaseInfo() {
}
class DynamicReply(
val id: Long?,
val videoId: Long?,
val videoTitle: String?,
val message: String?,
val likeCount: Int?,
val showConversationButton: Boolean?,
val parentReplyId: Int?,
val rootReplyId: Long?,
val ifHotReply: Boolean?,
val liked: Boolean?,
val parentReply: Any?,
val user: User?) {
}
| 1 | Kotlin | 3 | 2 | 3eefe4b5734aeb58994ff1af7a1850c7b7740e64 | 998 | EyepetizerTv | Apache License 2.0 |
challenge/flutter/all_samples/material_animatedbuilder_1/android/app/src/main/kotlin/com/example/material_animatedbuilder_1/MainActivity.kt | davidzou | 5,868,257 | false | null | package com.example.material_animatedbuilder_1
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 1 | null | 1 | 4 | 1060f6501c432510e164578d4af60a49cd5ed681 | 143 | WonderingWall | Apache License 2.0 |
idea/tests/testData/indentationOnNewline/expressionBody/AfterFunctionWithTypeParameter.kt | JetBrains | 278,369,660 | false | null | // SET_FALSE: CONTINUATION_INDENT_FOR_EXPRESSION_BODIES
fun <T> test(t: T): String<caret> | 0 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 89 | intellij-kotlin | Apache License 2.0 |
Problems/Algorithms/1491. Average Salary Excluding the Minimum and Maximum Salary/AverageSalary.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 290546, "Python": 209878, "Rust": 82753, "C++": 71636, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun average(salary: IntArray): Double {
var sum = 0
var min = minOf(salary[0], salary[1])
var max = maxOf(salary[0], salary[1])
for (i in 2..salary.size-1) {
val curr = salary[i]
if (min > curr) {
sum += min
min = curr
} else if (max < curr) {
sum += max
max = curr
} else {
sum += curr
}
}
return sum / (salary.size-2).toDouble()
}
}
| 0 | Kotlin | 0 | 1 | 64e27269784b1a31258677ab03da00f341c2fa98 | 559 | leet-code | MIT License |
sentry-android-core/src/test/java/io/sentry/android/core/performance/ActivityLifecycleTimeSpanTest.kt | getsentry | 3,368,190 | false | {"Kotlin": 3312354, "Java": 2633084, "C": 18038, "Shell": 4181, "Python": 3773, "Makefile": 2269, "CMake": 985, "C++": 703} | package io.sentry.android.core.performance
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class ActivityLifecycleTimeSpanTest {
@Test
fun `init does not auto-start the spans`() {
val span = ActivityLifecycleTimeSpan()
assertTrue(span.onCreate.hasNotStarted())
assertTrue(span.onStart.hasNotStarted())
}
@Test
fun `spans are compareable`() {
// given some spans
val spanA = ActivityLifecycleTimeSpan()
spanA.onCreate.setStartedAt(1)
val spanB = ActivityLifecycleTimeSpan()
spanB.onCreate.setStartedAt(2)
val spanC = ActivityLifecycleTimeSpan()
spanC.onCreate.setStartedAt(3)
// when put into an list out of order
// then sorted
val spans = listOf(spanB, spanC, spanA).sorted()
// puts them back in order
assertEquals(spanA, spans[0])
assertEquals(spanB, spans[1])
assertEquals(spanC, spans[2])
}
@Test
fun `if two activity spans have same onCreate, they're sorted by onstart`() {
// given span A and B with same onCreate
val spanA = ActivityLifecycleTimeSpan()
spanA.onCreate.setStartedAt(1)
val spanB = ActivityLifecycleTimeSpan()
spanB.onCreate.setStartedAt(1)
// when span A starts after span B
spanA.onStart.setStartedAt(20)
spanB.onStart.setStartedAt(10)
// then they still should be properly sorted
val sortedSpans = listOf(spanA, spanB).sorted()
assertEquals(spanB, sortedSpans[0])
}
}
| 300 | Kotlin | 435 | 1,155 | 378d12c8be1519ed7caea8bb7db8bcb0ab8275a0 | 1,602 | sentry-java | MIT License |
krichtexteditor/src/main/java/com/ebolo/krichtexteditor/fragments/EditTableFragment.kt | naseemakhtar994 | 116,084,980 | true | {"Gradle": 6, "YAML": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 21, "XML": 34, "Java": 2, "JavaScript": 5, "HTML": 1, "CSS": 3} | package com.ebolo.krichtexteditor.fragments
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ebolo.krichtexteditor.ui.layouts.EditTableFragmentLayout
import org.jetbrains.anko.AnkoContext
/**
* Edit Table Fragment
* Created by even.wu on 10/8/17.
* Ported by ebolo(daothanhduy305) on 21/12/2017
*/
@Deprecated(message = "Not officially supported yet")
class EditTableFragment: DialogFragment() {
private var callback: ((row: Int, column: Int) -> Unit)? = null
override fun onCreateView(
inflater: LayoutInflater?,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val layout = EditTableFragmentLayout()
layout.callback = this.callback
return layout.createView(AnkoContext.Companion.create(context, this))
}
fun onTableSet(callback: (row: Int, column: Int) -> Unit) {
this.callback = callback
}
}
@Deprecated(message = "Not officially supported yet")
fun editTableDialog(setup: EditTableFragment.() -> Unit): EditTableFragment {
val dialog = EditTableFragment()
setup.invoke(dialog)
return dialog
} | 0 | Kotlin | 0 | 0 | 88ecd0b8430720de6183dc214c60b2fc387d79d2 | 1,244 | KRichEditor | MIT License |
src/main/java/uk/gov/justice/digital/hmpps/whereabouts/services/AttendanceExceptions.kt | uk-gov-mirror | 356,783,561 | false | null | package uk.gov.justice.digital.hmpps.whereabouts.services
import javax.persistence.EntityNotFoundException
class AttendanceExists : RuntimeException("Attendance already exists")
class AttendanceLocked : RuntimeException("Attendance record is locked")
class AttendanceNotFound : EntityNotFoundException()
| 1 | null | 1 | 1 | fcb65de589127fb83239a288c579b6fe8db4fde6 | 306 | ministryofjustice.whereabouts-api | Apache License 2.0 |
compiler/src/main/java/io/sellmair/kompass/compiler/extension/ExtensionBuilder.kt | MaTriXy | 119,345,612 | false | null | package io.sellmair.kompass.compiler.extension
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.asTypeName
import io.sellmair.kompass.compiler.serializerClassName
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.TypeElement
/**
* Created by sebastiansellmair on 10.12.17.
*/
interface ExtensionBuilder {
fun buildSerializerFunctions(environment: ProcessingEnvironment, builder: FileSpec.Builder, element: TypeElement)
}
class ExtensionBuilderImpl : ExtensionBuilder {
override fun buildSerializerFunctions(environment: ProcessingEnvironment, builder: FileSpec.Builder, element: TypeElement) {
buildBundleExtension(environment, builder, element)
}
private fun buildBundleExtension(environment: ProcessingEnvironment, builder: FileSpec.Builder, element: TypeElement) {
val serializerClass = ClassName(environment.elementUtils.getPackageOf(element).toString(), element.serializerClassName())
builder.addFunction(FunSpec.builder("tryAs${element.simpleName}")
.receiver(ClassName("android.os", "Bundle"))
.returns(element.asType().asTypeName().asNullable())
.beginControlFlow("try")
.addStatement("return $serializerClass.createFromBundle(this)")
.endControlFlow()
.beginControlFlow("catch(e: Throwable)")
.addStatement("return null")
.endControlFlow()
.build())
builder.addFunction(FunSpec.builder("as${element.simpleName}")
.receiver(ClassName("android.os", "Bundle"))
.returns(element.asType().asTypeName())
.beginControlFlow("try")
.addStatement("return $serializerClass.createFromBundle(this)")
.endControlFlow()
.beginControlFlow("catch(e: Throwable)")
.addStatement("throw IllegalArgumentException(e)")
.endControlFlow()
.build())
}
} | 1 | null | 1 | 1 | 7db0f6eb6adbdd9a13af2f28ca3fcd3f98e969a9 | 2,127 | kompass | Apache License 2.0 |
app/src/main/kotlin/io/github/seggan/myxal/app/Main.kt | seanpm2001 | 706,446,894 | true | {"Gradle Kotlin DSL": 8, "Shell": 1, "Markdown": 3, "Git Attributes": 1, "Batchfile": 1, "Text": 3, "Ignore List": 1, "C++": 10, "YAML": 1, "Kotlin": 42, "Java": 19, "INI": 1, "ANTLR": 2, "Proguard": 1} | package io.github.seggan.myxal.app
import io.github.seggan.myxal.antlr.MyxalLexer
import io.github.seggan.myxal.antlr.MyxalParser
import io.github.seggan.myxal.compiler.MyxalCompileException
import io.github.seggan.myxal.compiler.cpp.NativeCompiler
import io.github.seggan.myxal.compiler.jvm.JvmCompiler
import io.github.seggan.myxal.runtime.text.Compression
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.CommonTokenStream
import org.apache.commons.cli.DefaultParser
import org.apache.commons.cli.Options
import org.objectweb.asm.ClassReader
import org.objectweb.asm.util.TraceClassVisitor
import proguard.ClassPath
import proguard.ClassPathEntry
import proguard.Configuration
import proguard.ConfigurationParser
import proguard.ProGuard
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.PrintWriter
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.Locale
import java.util.Scanner
import java.util.jar.Attributes
import java.util.jar.JarEntry
import java.util.jar.JarOutputStream
import java.util.jar.Manifest
import java.util.regex.Pattern
object Main {
private const val runtimeClasses = "../runtime/build/runtimeLibs"
private val p = Pattern.compile("\\..*$")
@JvmStatic
fun doMain(args: Array<String>, isTest: Boolean) {
val cmdParser = DefaultParser(false)
val options = Options()
options.addOption("h", "help", false, "Print this help message")
.addOption("c", "codepage", false, "Use the Myxal codepage")
.addOption("d", "debug", false, "Print debug stuff")
.addOption("p", "platform", true, "Platform to compile for")
.addOption("f", "file", true, "Input file")
.addOption("C", "code", true, "Input code")
.addOption("O", "nooptimize", false, "Do not optimize")
val cmd = cmdParser.parse(options, args)
println("Parsing program...")
val inputFile = if (cmd.hasOption("f")) cmd.getOptionValue("f") else "Input"
val bytes = if (cmd.hasOption("f")) {
Files.readAllBytes(Path.of(cmd.getOptionValue("f")))
} else if (cmd.hasOption("C")) {
cmd.getOptionValue("C").toByteArray()
} else {
throw MyxalCompileException("Either file or code must be given as arguments")
}
val s: String = if (cmd.hasOption("c")) {
val sb = StringBuilder()
for (b in bytes) {
sb.append(Compression.CODEPAGE[b.toInt()])
}
sb.toString()
} else {
String(bytes, StandardCharsets.UTF_8)
}
val lexer = MyxalLexer(CharStreams.fromString(s))
val parser = MyxalParser(CommonTokenStream(lexer))
val platform = SupportedPlatform.fromString(cmd.getOptionValue('p') ?: "jvm")
val transformed = Transformer.transform(parser.file(), platform)
if (cmd.hasOption("d")) {
println(transformed)
}
println("Compiling program...")
val extIndex = inputFile.lastIndexOf('.')
val fileName = if (extIndex == -1) inputFile else inputFile.substring(0, extIndex)
if (platform == SupportedPlatform.JVM) {
val main = JvmCompiler(cmd, false).compile(transformed)
val cr = ClassReader(main)
FileOutputStream("debug.log").use { os ->
val tcv = TraceClassVisitor(PrintWriter(os))
cr.accept(tcv, 0)
}
println("Extracting runtime classes...")
val resourceList: MutableSet<String> = HashSet()
val buildDir: Path = Path.of(System.getProperty("user.dir"), runtimeClasses)
Scanner(
if (isTest) Files.newInputStream(buildDir.resolve("runtime.list")) else
Main::class.java.getResourceAsStream("/runtime.list")!!
).use { scanner ->
while (scanner.hasNextLine()) {
resourceList.add(scanner.nextLine())
}
}
println("Writing to jar...")
val file = File("$fileName-temp.jar")
val final = File("$fileName.jar")
JarOutputStream(FileOutputStream(file)).use { jar ->
for (resource in resourceList) {
val entry = JarEntry(resource)
entry.time = System.currentTimeMillis()
jar.putNextEntry(entry)
if (isTest) Files.newInputStream(buildDir.resolve(resource)) else Main::class.java.getResourceAsStream(
"/$resource"
).use { inp ->
inp?.copyTo(jar) ?: println("Skipping resource: $resource")
}
}
val manifest = Manifest()
manifest.mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0"
manifest.mainAttributes[Attributes.Name.MAIN_CLASS] = "myxal.Main"
jar.putNextEntry(JarEntry("META-INF/MANIFEST.MF"))
manifest.write(jar)
val entry = JarEntry("myxal/Main.class")
entry.time = System.currentTimeMillis()
jar.putNextEntry(entry)
jar.write(main)
}
if (!cmd.hasOption('O')) {
println("Performing post-compilation optimisations...")
val config = Configuration()
ConfigurationParser(Main::class.java.getResource("/rules.pro")!!, System.getProperties())
.parse(config)
config.obfuscate = false
config.optimizationPasses = 2
config.programJars = ClassPath()
config.programJars.add(ClassPathEntry(file, false))
config.programJars.add(ClassPathEntry(final, true))
config.libraryJars = ClassPath()
config.libraryJars.add(
ClassPathEntry(
File(
"${System.getProperty("java.home")}/jmods/java.base.jmod"
), false
)
)
config.libraryJars.add(
ClassPathEntry(
File(
"${System.getProperty("java.home")}/jmods/jdk.jshell.jmod"
), false
)
)
config.warn = mutableListOf("!java.lang.invoke.MethodHandle")
config.optimizations = mutableListOf("!class/unboxing/enum")
ProGuard(config).execute()
} else {
FileInputStream(file).use { fis ->
FileOutputStream(final).use { fos ->
fis.copyTo(fos)
}
}
}
if (!cmd.hasOption('d')) {
file.delete()
}
} else if (platform == SupportedPlatform.NATIVE) {
val main = NativeCompiler(cmd).compile(transformed)
println("Compiling native code...")
val buildDir = Path.of(System.getProperty("user.dir"), "build-${System.currentTimeMillis()}")
val file = buildDir.resolve("main.cpp")
Files.createDirectories(buildDir)
Files.writeString(file, main)
val resourceList = mutableListOf<String>()
Scanner(Main::class.java.getResourceAsStream("/cpp-resources.txt")!!).use { scanner ->
while (scanner.hasNextLine()) {
resourceList.add(scanner.nextLine())
}
}
val includes = mutableListOf<String>()
for (resource in resourceList) {
val inp = Main::class.java.getResourceAsStream("/$resource")
if (inp != null) {
Files.copy(inp, buildDir.resolve(resource), StandardCopyOption.REPLACE_EXISTING)
}
includes.add(resource)
}
includes.add("main.cpp")
val isWindows = System.getProperty("os.name").lowercase(Locale.getDefault()).contains("win")
val executableName = if (isWindows) "$fileName.exe" else fileName
val a = mutableListOf(
"g++",
"-o", executableName
)
if (cmd.hasOption('d')) {
a.add("-g")
}
if (!cmd.hasOption('O')) {
a.add("-O3")
}
a.addAll(includes)
ProcessBuilder(*a.toTypedArray())
.directory(buildDir.toFile())
.redirectOutput(ProcessBuilder.Redirect.INHERIT)
.redirectError(ProcessBuilder.Redirect.INHERIT)
.start()
.waitFor()
try {
val final = buildDir.resolve(executableName)
if (!Files.exists(final)) {
throw RuntimeException("Failed to compile native code. See g++ output for details.")
}
println("Cleaning up...")
Files.move(final, buildDir.parent.resolve(executableName), StandardCopyOption.REPLACE_EXISTING)
} finally {
if (!cmd.hasOption('d')) {
Files.walk(buildDir).filter { !Files.isDirectory(it) }.forEach {
Files.delete(it)
}
Files.walk(buildDir).forEach {
if (Files.isDirectory(it)) {
Files.delete(it)
} else {
Files.deleteIfExists(it)
}
}
}
}
}
println("Done!")
}
@JvmStatic
fun main(args: Array<String>) {
doMain(args, false)
}
}
| 0 | null | 0 | 1 | b53015699278ef5fc2800447106581ca34ecbdea | 9,992 | Vyxal_Myxal | Apache License 2.0 |
j2k/new/tests/testData/inference/nullability/compareWithNull.kt | JetBrains | 278,369,660 | false | null | fun a(): /*T0@*/Int? {
return 42/*LIT*/
}
val b: /*T1@*/Int? = 2/*LIT*/
fun c(p: /*T2@*/Int?) {
if (p/*T2@Int*/ == null/*LIT*/);
}
fun check() {
if (a()/*T0@Int*/ == null/*LIT*/ || b/*T1@Int*/ == null/*LIT*//*LIT*/);
}
//LOWER <: T0 due to 'RETURN'
//LOWER <: T1 due to 'INITIALIZER'
//T2 := UPPER due to 'COMPARE_WITH_NULL'
//T0 := UPPER due to 'COMPARE_WITH_NULL'
//T1 := UPPER due to 'COMPARE_WITH_NULL'
| 0 | Kotlin | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 423 | intellij-kotlin | Apache License 2.0 |
app/src/main/java/com/jove/android/ui/ProtogenesisRecyclerViewTest.kt | jupiter-energy | 130,473,608 | false | null | package com.jove.android.ui
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class ProtogenesisRecyclerViewTest : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_protogenesis_recycler_view_test)
}
private class RVAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val data = listOf("a.123", "b.23.23", "c.1231.122.222")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
var v = LayoutInflater.from(parent.context).inflate(R.layout.item_protogenesis_recycler_view_test, parent);
return RVHolder(v)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
}
override fun getItemCount(): Int {
return data.size
}
}
private class RVHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var textView: TextView = itemView.findViewById(R.id.tv_text)
//var t = TextView
fun fillData(item: String) {
}
}
}
| 1 | null | 1 | 1 | cac548d4e761b58a110afd3441713f9b4183f034 | 1,343 | JoveAndroidUtils | Apache License 2.0 |
platform/platform-impl/src/com/intellij/openapi/application/actions.kt | onurkaracali | 66,496,779 | false | null | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.application
import com.intellij.openapi.components.impl.stores.BatchUpdateListener
import com.intellij.openapi.util.Computable
import com.intellij.util.messages.MessageBus
import javax.swing.SwingUtilities
inline fun <T> runWriteAction(crossinline runnable: () -> T): T = ApplicationManager.getApplication().runWriteAction(Computable { runnable.invoke() })
inline fun <T> runReadAction(crossinline runnable: () -> T): T = ApplicationManager.getApplication().runReadAction(Computable { runnable.invoke() })
inline fun <T> runBatchUpdate(messageBus: MessageBus, runnable: () -> T): T {
val publisher = messageBus.syncPublisher(BatchUpdateListener.TOPIC)
publisher.onBatchUpdateStarted()
try {
return runnable()
}
finally {
publisher.onBatchUpdateFinished()
}
}
/**
* @exclude Internal use only
*/
fun <T> invokeAndWaitIfNeed(runnable: () -> T): T {
val app = ApplicationManager.getApplication()
if (app == null) {
if (SwingUtilities.isEventDispatchThread()) {
return runnable()
}
else {
var result: T? = null
SwingUtilities.invokeAndWait { result = runnable() }
return result as T
}
}
else {
var result: T? = null
app.invokeAndWait { result = runnable() }
return result as T
}
} | 0 | null | 0 | 1 | c84ce39d8382d3f2039917fb37995c9c12bd0c98 | 1,895 | intellij-community | Apache License 2.0 |
compiler/testData/diagnostics/testsWithStdLib/buildLazyValueForMap.kt | JetBrains | 3,432,266 | false | null | // FIR_IDENTICAL
interface ClassId
interface JavaAnnotation {
val classId: ClassId?
}
interface JavaAnnotationOwner {
val annotations: Collection<JavaAnnotation>
}
interface MapBasedJavaAnnotationOwner : JavaAnnotationOwner {
val annotationsByFqNameHash: Map<Int?, JavaAnnotation>
}
fun JavaAnnotationOwner.buildLazyValueForMap() = lazy {
annotations.associateBy { it.classId?.hashCode() }
}
abstract class BinaryJavaMethodBase(): MapBasedJavaAnnotationOwner {
override val annotationsByFqNameHash by buildLazyValueForMap()
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 552 | kotlin | Apache License 2.0 |
src/main/java/tornadofx/ViewModelFacades.kt | edvin | 49,143,977 | false | {"Maven POM": 1, "Markdown": 2, "Text": 1, "Ignore List": 1, "XML": 6, "YAML": 1, "CSS": 7, "JSON": 1, "Kotlin": 148, "Java": 2, "INI": 12, "SVG": 2} | package tornadofx
import javafx.beans.Observable
import javafx.beans.property.*
import javafx.beans.value.ObservableValue
import javafx.collections.ObservableList
import javafx.collections.ObservableMap
import javafx.collections.ObservableSet
interface BindingAware
/**
* A property wrapper that will report it's ViewModel relation
* to a central location to make it possible for validators
* to retrieve the correct ValidationContext from the ViewModel
* this property is bound to.
*/
interface BindingAwareProperty<T> : BindingAware, Property<T> {
fun recordBinding(observableValue: ObservableValue<*>?) {
if (observableValue is Observable) {
ViewModel.propertyToFacade[observableValue] = this
ViewModel.propertyToViewModel[observableValue] = bean as ViewModel
}
}
}
class BindingAwareSimpleBooleanProperty(viewModel: ViewModel, name: String?) : SimpleBooleanProperty(viewModel, name), BindingAwareProperty<Boolean> {
override fun bind(rawObservable: ObservableValue<out Boolean>?) {
super.bind(rawObservable)
recordBinding(rawObservable)
}
override fun bindBidirectional(other: Property<Boolean>?) {
super.bindBidirectional(other)
recordBinding(other)
}
}
class BindingAwareSimpleStringProperty(viewModel: ViewModel, name: String?) : SimpleStringProperty(viewModel, name), BindingAwareProperty<String> {
override fun bind(rawObservable: ObservableValue<out String>?) {
super.bind(rawObservable)
recordBinding(rawObservable)
}
override fun bindBidirectional(other: Property<String>?) {
super.bindBidirectional(other)
recordBinding(other)
}
}
class BindingAwareSimpleObjectProperty<T>(viewModel: ViewModel, name: String?) : SimpleObjectProperty<T>(viewModel, name), BindingAwareProperty<T> {
override fun bind(rawObservable: ObservableValue<out T>?) {
super.bind(rawObservable)
recordBinding(rawObservable)
}
override fun bindBidirectional(other: Property<T>?) {
super.bindBidirectional(other)
recordBinding(other)
}
}
class BindingAwareSimpleListProperty<T>(viewModel: ViewModel, name: String?) : SimpleListProperty<T>(viewModel, name) {
override fun bind(newObservable: ObservableValue<out ObservableList<T>>?) {
super.bind(newObservable)
recordBinding(newObservable)
}
override fun bindContentBidirectional(list: ObservableList<T>?) {
super.bindContentBidirectional(list)
recordBinding(list)
}
fun recordBinding(observableValue: Observable?) {
if (observableValue != null) {
ViewModel.propertyToFacade[observableValue] = this
ViewModel.propertyToViewModel[observableValue] = bean as ViewModel
}
}
/**
* Return a unique id for this object instead of the default hashCode which is dependent on the children.
* Without this override we wouldn't be able to identify the facade in our internal maps.
*/
override fun hashCode() = System.identityHashCode(this)
override fun equals(other: Any?) = this === other
}
class BindingAwareSimpleSetProperty<T>(viewModel: ViewModel, name: String?) : SimpleSetProperty<T>(viewModel, name) {
override fun bind(newObservable: ObservableValue<out ObservableSet<T>>?) {
super.bind(newObservable)
recordBinding(newObservable)
}
override fun bindContentBidirectional(list: ObservableSet<T>?) {
super.bindContentBidirectional(list)
recordBinding(list)
}
fun recordBinding(observableValue: Observable?) {
if (observableValue != null) {
ViewModel.propertyToFacade[observableValue] = this
ViewModel.propertyToViewModel[observableValue] = bean as ViewModel
}
}
/**
* Return a unique id for this object instead of the default hashCode which is dependent on the children.
* Without this override we wouldn't be able to identify the facade in our internal maps.
*/
override fun hashCode() = System.identityHashCode(this)
override fun equals(other: Any?) = this === other
}
class BindingAwareSimpleMapProperty<S, T>(viewModel: ViewModel, name: String?) : SimpleMapProperty<S, T>(viewModel, name) {
override fun bind(newObservable: ObservableValue<out ObservableMap<S, T>>?) {
super.bind(newObservable)
recordBinding(newObservable)
}
override fun bindContentBidirectional(list: ObservableMap<S, T>?) {
super.bindContentBidirectional(list)
recordBinding(list)
}
fun recordBinding(observableValue: Observable?) {
if (observableValue != null) {
ViewModel.propertyToFacade[observableValue] = this
ViewModel.propertyToViewModel[observableValue] = bean as ViewModel
}
}
/**
* Return a unique id for this object instead of the default hashCode which is dependent on the children.
* Without this override we wouldn't be able to identify the facade in our internal maps.
*/
override fun hashCode() = System.identityHashCode(this)
override fun equals(other: Any?) = this === other
}
class BindingAwareSimpleFloatProperty(viewModel: ViewModel, name: String?) : SimpleFloatProperty(viewModel, name), BindingAwareProperty<Number> {
override fun bind(rawObservable: ObservableValue<out Number>?) {
super.bind(rawObservable)
recordBinding(rawObservable)
}
override fun bindBidirectional(other: Property<Number>?) {
super.bindBidirectional(other)
recordBinding(other)
}
}
class BindingAwareSimpleDoubleProperty(viewModel: ViewModel, name: String?) : SimpleDoubleProperty(viewModel, name), BindingAwareProperty<Number> {
override fun bind(rawObservable: ObservableValue<out Number>?) {
super.bind(rawObservable)
recordBinding(rawObservable)
}
override fun bindBidirectional(other: Property<Number>?) {
super.bindBidirectional(other)
recordBinding(other)
}
}
class BindingAwareSimpleLongProperty(viewModel: ViewModel, name: String?) : SimpleLongProperty(viewModel, name), BindingAwareProperty<Number> {
override fun bind(rawObservable: ObservableValue<out Number>?) {
super.bind(rawObservable)
recordBinding(rawObservable)
}
override fun bindBidirectional(other: Property<Number>?) {
super.bindBidirectional(other)
recordBinding(other)
}
}
class BindingAwareSimpleIntegerProperty(viewModel: ViewModel, name: String?) : SimpleIntegerProperty(viewModel, name), BindingAwareProperty<Number> {
override fun bind(rawObservable: ObservableValue<out Number>?) {
super.bind(rawObservable)
recordBinding(rawObservable)
}
override fun bindBidirectional(other: Property<Number>?) {
super.bindBidirectional(other)
recordBinding(other)
}
} | 196 | Kotlin | 266 | 3,674 | 94fd553aced7a2ffe7528b1977a9f8406028432c | 6,921 | tornadofx | Apache License 2.0 |
buildSrc/src/main/kotlin/Config.kt | oliverspryn | 446,959,362 | false | {"Kotlin": 57199} | object Config {
const val APPLICATION_ID = "com.oliverspryn.android.multimodal"
const val PROJECT_NAME = "Multimodal Spanner"
}
| 0 | Kotlin | 0 | 0 | 87629ae247ac3fe22e5334e029b3240d4e239c25 | 136 | multimodal-spanner | MIT License |
Client/core/src/main/java/com/t3ddyss/core/util/extensions/FragmentExt.kt | t3ddyss | 337,083,750 | false | null | package com.t3ddyss.core.util.extensions
import android.util.TypedValue
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import com.google.android.material.snackbar.Snackbar
import com.t3ddyss.core.R
import com.t3ddyss.core.domain.models.Error
import com.t3ddyss.core.domain.models.InfoMessage
import com.t3ddyss.core.presentation.NavMenuController
import com.t3ddyss.core.util.utils.StringUtils
import kotlin.math.roundToInt
val Fragment.dp: Int.() -> Int
get() = {
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
this.toFloat(),
[email protected]().resources.displayMetrics
).roundToInt()
}
val Fragment.errorText: Error<*>.() -> String
get() = {
when (message) {
is InfoMessage.StringMessage -> {
message.message ?: StringUtils.getErrorText(throwable, requireContext())
}
is InfoMessage.StringResMessage -> {
getString(message.messageRes)
}
else -> {
StringUtils.getErrorText(throwable, requireContext())
}
}
}
fun Fragment.showSnackbarWithText(text: String?) {
val snackbar = Snackbar.make(
requireView(),
text ?: getString(R.string.error_unknown),
Snackbar.LENGTH_SHORT
)
showSnackbar(snackbar)
}
fun Fragment.showSnackbarWithText(@StringRes textRes: Int?) {
val text = textRes?.let {
getString(it)
}
showSnackbarWithText(text)
}
fun Fragment.showSnackbarWithText(error: Error<*>) {
showSnackbarWithText(error.errorText())
}
fun Fragment.showSnackbarWithText(throwable: Throwable) {
showSnackbarWithText(StringUtils.getErrorText(throwable, requireContext()))
}
fun Fragment.showSnackbarWithAction(
@StringRes text: Int,
@StringRes actionText: Int,
action: (() -> Unit)
) {
val snackbar = Snackbar.make(
requireView(),
getString(text),
Snackbar.LENGTH_SHORT
)
snackbar.setAction(actionText) {
action.invoke()
}
showSnackbar(snackbar)
}
private fun Fragment.showSnackbar(snackbar: Snackbar) {
val navMenuController = activity as? NavMenuController
if (navMenuController?.isMenuVisible == true) {
snackbar.anchorView = navMenuController.menuView
}
snackbar.show()
} | 0 | Kotlin | 1 | 23 | a2439707002e0086de09bf37c3d10e7c8cf9f060 | 2,371 | Clother | MIT License |
compiler/testData/diagnostics/testsWithStdLib/callableReference/property/memberFromTopLevel.kt | chashnikov | 14,658,474 | false | null | import kotlin.reflect.*
class A {
val foo: Int = 42
var bar: String = ""
}
fun test() {
val p = A::foo
p : KMemberProperty<A, Int>
<!TYPE_MISMATCH!>p<!> : KMutableMemberProperty<A, Int>
p.get(A()) : Int
p.get(<!NO_VALUE_FOR_PARAMETER!>)<!>
p.<!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>set<!>(A(), 239)
val q = A::bar
q : KMemberProperty<A, String>
q : KMutableMemberProperty<A, String>
q.get(A()): String
q.set(A(), "q")
}
| 0 | null | 0 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 476 | kotlin | Apache License 2.0 |
android/src/main/java/com/preventscreenshot/PreventScreenshotModule.kt | jesusebzcp | 869,134,075 | false | {"Kotlin": 10868, "TypeScript": 8922, "Swift": 5397, "Ruby": 3245, "Objective-C": 2561, "JavaScript": 1380, "Objective-C++": 816, "C": 103} | package com.preventscreenshot
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.util.Base64
import android.util.Log
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.RelativeLayout
import com.facebook.react.bridge.LifecycleEventListener
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import java.io.IOException
import java.net.URL
class PreventScreenshotModule(reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext), LifecycleEventListener {
private var overlayLayout: RelativeLayout? = null
private var secureFlagWasSet: Boolean = false
init {
reactContext.addLifecycleEventListener(this)
}
override fun getName(): String {
return "RNScreenshotPrevent"
}
@ReactMethod
fun enabled(enable: Boolean) {
currentActivity?.let { activity ->
activity.runOnUiThread {
if (enable) {
activity.window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
} else {
activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
}
}
@ReactMethod
fun enableSecureView(imageData: String) {
currentActivity?.let { activity ->
if (overlayLayout == null) {
if (imageData.startsWith("data:image")) {
Log.d("PreventScreenshot", "Processing Base64 image")
createOverlayFromBase64(activity, imageData)
} else {
Log.d("PreventScreenshot", "Processing image from URL")
createOverlay(activity, imageData)
}
}
activity.runOnUiThread {
activity.window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
}
}
}
@ReactMethod
fun disableSecureView() {
currentActivity?.let { activity ->
activity.runOnUiThread {
overlayLayout?.let {
val rootView = activity.window.decorView.rootView as ViewGroup
rootView.removeView(overlayLayout)
overlayLayout = null
}
activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
}
private fun createOverlayFromBase64(activity: Activity, base64ImageData: String) {
val base64Data = base64ImageData.substringAfter("base64,")
val imageBytes = Base64.decode(base64Data, Base64.DEFAULT)
// Convertir los bytes en un Bitmap
val bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
if (bitmap == null) {
Log.e("PreventScreenshot", "Failed to decode base64 image")
return
} else {
Log.d("PreventScreenshot", "Successfully decoded base64 image")
}
// Crear el overlay
overlayLayout =
RelativeLayout(activity).apply { setBackgroundColor(Color.parseColor("#FFFFFF")) }
val imageView = ImageView(activity)
val imageParams =
RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
)
.apply { addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE) }
imageView.layoutParams = imageParams
// Ajustar el tamaño de la imagen si es muy grande
val scaledBitmap =
Bitmap.createScaledBitmap(
bitmap,
activity.resources.displayMetrics.widthPixels,
(bitmap.height *
(activity.resources.displayMetrics.widthPixels.toFloat() /
bitmap.width))
.toInt(),
true
)
imageView.setImageBitmap(scaledBitmap)
imageView.scaleType =
ImageView.ScaleType
.FIT_CENTER // Ajustamos la imagen para que se ajuste al tamaño disponible
overlayLayout?.addView(imageView)
// Asegurarnos de agregar la vista al root view
activity.runOnUiThread {
val rootView = activity.window.decorView.rootView as ViewGroup
rootView.addView(overlayLayout)
Log.d("PreventScreenshot", "Overlay added to root view")
}
}
private fun createOverlay(activity: Activity, imagePath: String) {
overlayLayout =
RelativeLayout(activity).apply { setBackgroundColor(Color.parseColor("#FFFFFF")) }
val imageView = ImageView(activity)
val imageParams =
RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
)
.apply { addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE) }
imageView.layoutParams = imageParams
val bitmap = decodeImageUrl(imagePath)
if (bitmap != null) {
Log.d("PreventScreenshot", "Image from URL decoded successfully")
} else {
Log.e("PreventScreenshot", "Failed to decode image from URL")
return
}
val imageHeight =
(bitmap.height *
(activity.resources.displayMetrics.widthPixels.toFloat() /
bitmap.width))
.toInt()
val scaledBitmap =
Bitmap.createScaledBitmap(
bitmap,
activity.resources.displayMetrics.widthPixels,
imageHeight,
true
)
imageView.setImageBitmap(scaledBitmap)
overlayLayout?.addView(imageView)
// Asegurarnos de agregar la vista al root view
activity.runOnUiThread {
val rootView = activity.window.decorView.rootView as ViewGroup
rootView.addView(overlayLayout)
Log.d("PreventScreenshot", "Overlay added to root view")
}
}
private fun decodeImageUrl(imagePath: String): Bitmap? {
return try {
val imageUrl = URL(imagePath)
BitmapFactory.decodeStream(imageUrl.openConnection().getInputStream())
} catch (e: IOException) {
e.printStackTrace()
null
}
}
override fun onHostResume() {
currentActivity?.let { activity ->
if (overlayLayout != null) {
activity.runOnUiThread {
val rootView = activity.window.decorView.rootView as ViewGroup
rootView.removeView(overlayLayout)
if (secureFlagWasSet) {
activity.window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
secureFlagWasSet = false
}
}
}
}
}
override fun onHostPause() {
currentActivity?.let { activity ->
if (overlayLayout != null) {
activity.runOnUiThread {
val rootView = activity.window.decorView.rootView as ViewGroup
val layoutParams =
RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
rootView.addView(overlayLayout, layoutParams)
val flags = activity.window.attributes.flags
if ((flags and WindowManager.LayoutParams.FLAG_SECURE) != 0) {
activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
secureFlagWasSet = true
} else {
secureFlagWasSet = false
}
}
}
}
}
override fun onHostDestroy() {
// Limpieza si es necesario
}
}
| 0 | Kotlin | 0 | 0 | 2b52678d8cb7335a9bda7d77228f5c044b7668d1 | 7,839 | boletia-react-native-prevent-screenshot | MIT License |
android/src/main/java/com/preventscreenshot/PreventScreenshotModule.kt | jesusebzcp | 869,134,075 | false | {"Kotlin": 10868, "TypeScript": 8922, "Swift": 5397, "Ruby": 3245, "Objective-C": 2561, "JavaScript": 1380, "Objective-C++": 816, "C": 103} | package com.preventscreenshot
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.util.Base64
import android.util.Log
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.RelativeLayout
import com.facebook.react.bridge.LifecycleEventListener
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import java.io.IOException
import java.net.URL
class PreventScreenshotModule(reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext), LifecycleEventListener {
private var overlayLayout: RelativeLayout? = null
private var secureFlagWasSet: Boolean = false
init {
reactContext.addLifecycleEventListener(this)
}
override fun getName(): String {
return "RNScreenshotPrevent"
}
@ReactMethod
fun enabled(enable: Boolean) {
currentActivity?.let { activity ->
activity.runOnUiThread {
if (enable) {
activity.window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
} else {
activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
}
}
@ReactMethod
fun enableSecureView(imageData: String) {
currentActivity?.let { activity ->
if (overlayLayout == null) {
if (imageData.startsWith("data:image")) {
Log.d("PreventScreenshot", "Processing Base64 image")
createOverlayFromBase64(activity, imageData)
} else {
Log.d("PreventScreenshot", "Processing image from URL")
createOverlay(activity, imageData)
}
}
activity.runOnUiThread {
activity.window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
}
}
}
@ReactMethod
fun disableSecureView() {
currentActivity?.let { activity ->
activity.runOnUiThread {
overlayLayout?.let {
val rootView = activity.window.decorView.rootView as ViewGroup
rootView.removeView(overlayLayout)
overlayLayout = null
}
activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
}
private fun createOverlayFromBase64(activity: Activity, base64ImageData: String) {
val base64Data = base64ImageData.substringAfter("base64,")
val imageBytes = Base64.decode(base64Data, Base64.DEFAULT)
// Convertir los bytes en un Bitmap
val bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
if (bitmap == null) {
Log.e("PreventScreenshot", "Failed to decode base64 image")
return
} else {
Log.d("PreventScreenshot", "Successfully decoded base64 image")
}
// Crear el overlay
overlayLayout =
RelativeLayout(activity).apply { setBackgroundColor(Color.parseColor("#FFFFFF")) }
val imageView = ImageView(activity)
val imageParams =
RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
)
.apply { addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE) }
imageView.layoutParams = imageParams
// Ajustar el tamaño de la imagen si es muy grande
val scaledBitmap =
Bitmap.createScaledBitmap(
bitmap,
activity.resources.displayMetrics.widthPixels,
(bitmap.height *
(activity.resources.displayMetrics.widthPixels.toFloat() /
bitmap.width))
.toInt(),
true
)
imageView.setImageBitmap(scaledBitmap)
imageView.scaleType =
ImageView.ScaleType
.FIT_CENTER // Ajustamos la imagen para que se ajuste al tamaño disponible
overlayLayout?.addView(imageView)
// Asegurarnos de agregar la vista al root view
activity.runOnUiThread {
val rootView = activity.window.decorView.rootView as ViewGroup
rootView.addView(overlayLayout)
Log.d("PreventScreenshot", "Overlay added to root view")
}
}
private fun createOverlay(activity: Activity, imagePath: String) {
overlayLayout =
RelativeLayout(activity).apply { setBackgroundColor(Color.parseColor("#FFFFFF")) }
val imageView = ImageView(activity)
val imageParams =
RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
)
.apply { addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE) }
imageView.layoutParams = imageParams
val bitmap = decodeImageUrl(imagePath)
if (bitmap != null) {
Log.d("PreventScreenshot", "Image from URL decoded successfully")
} else {
Log.e("PreventScreenshot", "Failed to decode image from URL")
return
}
val imageHeight =
(bitmap.height *
(activity.resources.displayMetrics.widthPixels.toFloat() /
bitmap.width))
.toInt()
val scaledBitmap =
Bitmap.createScaledBitmap(
bitmap,
activity.resources.displayMetrics.widthPixels,
imageHeight,
true
)
imageView.setImageBitmap(scaledBitmap)
overlayLayout?.addView(imageView)
// Asegurarnos de agregar la vista al root view
activity.runOnUiThread {
val rootView = activity.window.decorView.rootView as ViewGroup
rootView.addView(overlayLayout)
Log.d("PreventScreenshot", "Overlay added to root view")
}
}
private fun decodeImageUrl(imagePath: String): Bitmap? {
return try {
val imageUrl = URL(imagePath)
BitmapFactory.decodeStream(imageUrl.openConnection().getInputStream())
} catch (e: IOException) {
e.printStackTrace()
null
}
}
override fun onHostResume() {
currentActivity?.let { activity ->
if (overlayLayout != null) {
activity.runOnUiThread {
val rootView = activity.window.decorView.rootView as ViewGroup
rootView.removeView(overlayLayout)
if (secureFlagWasSet) {
activity.window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
secureFlagWasSet = false
}
}
}
}
}
override fun onHostPause() {
currentActivity?.let { activity ->
if (overlayLayout != null) {
activity.runOnUiThread {
val rootView = activity.window.decorView.rootView as ViewGroup
val layoutParams =
RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
rootView.addView(overlayLayout, layoutParams)
val flags = activity.window.attributes.flags
if ((flags and WindowManager.LayoutParams.FLAG_SECURE) != 0) {
activity.window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
secureFlagWasSet = true
} else {
secureFlagWasSet = false
}
}
}
}
}
override fun onHostDestroy() {
// Limpieza si es necesario
}
}
| 0 | Kotlin | 0 | 0 | 2b52678d8cb7335a9bda7d77228f5c044b7668d1 | 7,839 | boletia-react-native-prevent-screenshot | MIT License |
idea/idea-frontend-api/src/org/jetbrains/kotlin/idea/frontend/api/components/KtTypeInfoProvider.kt | BradOselo | 367,097,840 | false | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.frontend.api.components
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.idea.frontend.api.types.KtClassType
import org.jetbrains.kotlin.idea.frontend.api.types.KtType
import org.jetbrains.kotlin.idea.frontend.api.types.KtTypeNullability
import org.jetbrains.kotlin.idea.frontend.api.types.KtTypeWithNullability
import org.jetbrains.kotlin.name.ClassId
abstract class KtTypeInfoProvider : KtAnalysisSessionComponent() {
abstract fun canBeNull(type: KtType): Boolean
}
interface KtTypeInfoProviderMixIn : KtAnalysisSessionMixIn {
/**
* Returns true if a value of this type can potentially be null. This means this type is not a subtype of [Any]. However, it does not
* mean one can assign `null` to a variable of this type because it may be unknown if this type can accept `null`. For example, a value
* of type `T:Any?` can potentially be null. But one can not assign `null` to such a variable because the instantiated type may not be
* nullable.
*/
val KtType.canBeNull: Boolean get() = analysisSession.typeInfoProvider.canBeNull(this)
/** Returns true if the type is explicitly marked as nullable. This means it's safe to assign `null` to a variable with this type. */
val KtType.isMarkedNullable: Boolean get() = (this as? KtTypeWithNullability)?.nullability == KtTypeNullability.NULLABLE
val KtType.isUnit: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.UNIT)
val KtType.isInt: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.INT)
val KtType.isLong: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.LONG)
val KtType.isShort: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.SHORT)
val KtType.isByte: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.BYTE)
val KtType.isFloat: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.FLOAT)
val KtType.isDouble: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.DOUBLE)
val KtType.isChar: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.CHAR)
val KtType.isBoolean: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.BOOLEAN)
val KtType.isString: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.STRING)
val KtType.isAny: Boolean get() = isClassTypeWithClassId(DefaultTypeClassIds.ANY)
val KtType.isUInt: Boolean get() = isClassTypeWithClassId(StandardNames.FqNames.uInt)
val KtType.isULong: Boolean get() = isClassTypeWithClassId(StandardNames.FqNames.uLong)
val KtType.isUShort: Boolean get() = isClassTypeWithClassId(StandardNames.FqNames.uShort)
val KtType.isUByte: Boolean get() = isClassTypeWithClassId(StandardNames.FqNames.uByte)
fun KtType.isClassTypeWithClassId(classId: ClassId): Boolean {
if (this !is KtClassType) return false
return this.classId == classId
}
val KtType.isPrimitive: Boolean
get() {
if (this !is KtClassType) return false
return this.classId in DefaultTypeClassIds.PRIMITIVES
}
val KtType.defaultInitializer: String?
get() = when {
isMarkedNullable -> "null"
isInt || isLong || isShort || isByte -> "0"
isFloat -> "0.0f"
isDouble -> "0.0"
isChar -> "'\\u0000'"
isBoolean -> "false"
isUnit -> "Unit"
isString -> "\"\""
isUInt -> "0.toUInt()"
isULong -> "0.toULong()"
isUShort -> "0.toUShort()"
isUByte -> "0.toUByte()"
else -> null
}
}
object DefaultTypeClassIds {
val UNIT = ClassId.topLevel(StandardNames.FqNames.unit.toSafe())
val INT = ClassId.topLevel(StandardNames.FqNames._int.toSafe())
val LONG = ClassId.topLevel(StandardNames.FqNames._long.toSafe())
val SHORT = ClassId.topLevel(StandardNames.FqNames._short.toSafe())
val BYTE = ClassId.topLevel(StandardNames.FqNames._byte.toSafe())
val FLOAT = ClassId.topLevel(StandardNames.FqNames._float.toSafe())
val DOUBLE = ClassId.topLevel(StandardNames.FqNames._double.toSafe())
val CHAR = ClassId.topLevel(StandardNames.FqNames._char.toSafe())
val BOOLEAN = ClassId.topLevel(StandardNames.FqNames._boolean.toSafe())
val STRING = ClassId.topLevel(StandardNames.FqNames.string.toSafe())
val ANY = ClassId.topLevel(StandardNames.FqNames.any.toSafe())
val PRIMITIVES = setOf(INT, LONG, SHORT, BYTE, FLOAT, DOUBLE, CHAR, BOOLEAN)
}
| 5 | null | 1 | 3 | 58c7aa9937334b7f3a70acca84a9ce59c35ab9d1 | 4,735 | kotlin | Apache License 2.0 |
maestro-client/src/test/java/maestro/xctestdriver/XCTestDriverClientTest.kt | mobile-dev-inc | 476,427,476 | false | null | package maestro.xctestdriver
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.google.common.truth.Truth.assertThat
import maestro.debuglog.IOSDriverLogger
import maestro.ios.MockXCTestInstaller
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.SocketPolicy
import org.junit.jupiter.api.Test
import xcuitest.XCTestClient
import xcuitest.XCTestDriverClient
import xcuitest.api.NetworkException
import java.net.InetAddress
class XCTestDriverClientTest {
@Test
fun `it should return correct message in case of TimeoutException with 3 retries`() {
// given
val mockWebServer = MockWebServer()
// do not enqueue any response
mockWebServer.start(InetAddress.getByName( "localhost"), 22087)
val httpUrl = mockWebServer.url("/deviceInfo")
// when
val simulator = MockXCTestInstaller.Simulator(
installationRetryCount = 0,
shouldInstall = false
)
val mockXCTestInstaller = MockXCTestInstaller(simulator)
val xcTestDriverClient = XCTestDriverClient(
mockXCTestInstaller,
IOSDriverLogger(XCTestDriverClient::class.java),
XCTestClient("localhost", 22087)
)
val response = xcTestDriverClient.deviceInfo(httpUrl)
// then
assertThat(response.message).contains(
"A timeout occurred while waiting for a response from the XCUITest server."
)
mockXCTestInstaller.assertInstallationRetries(3)
mockWebServer.shutdown()
}
@Test
fun `it should return the 4xx response as is without retrying`() {
// given
val mockWebServer = MockWebServer()
val mockResponse = MockResponse().apply {
setResponseCode(401)
setBody("This is a bad request")
}
mockWebServer.enqueue(mockResponse)
mockWebServer.start(InetAddress.getByName( "localhost"), 22087)
val httpUrl = mockWebServer.url("/deviceInfo")
// when
val simulator = MockXCTestInstaller.Simulator()
val mockXCTestInstaller = MockXCTestInstaller(simulator)
val xcTestDriverClient = XCTestDriverClient(
mockXCTestInstaller,
IOSDriverLogger(XCTestDriverClient::class.java),
XCTestClient("localhost", 22087)
)
val response = xcTestDriverClient.deviceInfo(httpUrl)
// then
val body = response.body?.string()
val code = response.code
assertThat(code).isEqualTo(401)
assertThat(body).isNotNull()
assertThat(body).isEqualTo("This is a bad request")
mockXCTestInstaller.assertInstallationRetries(0)
mockWebServer.shutdown()
}
@Test
fun `it should return the 200 response as is without retrying`() {
// given
val mockWebServer = MockWebServer()
val mockResponse = MockResponse().apply {
setResponseCode(200)
setBody("This is a valid response")
}
mockWebServer.enqueue(mockResponse)
mockWebServer.start(InetAddress.getByName( "localhost"), 22087)
val httpUrl = mockWebServer.url("/deviceInfo")
// when
val simulator = MockXCTestInstaller.Simulator()
val mockXCTestInstaller = MockXCTestInstaller(simulator)
val xcTestDriverClient = XCTestDriverClient(
mockXCTestInstaller,
IOSDriverLogger(XCTestDriverClient::class.java),
XCTestClient("localhost", 22087)
)
val response = xcTestDriverClient.deviceInfo(httpUrl)
// then
val body = response.body?.string()
val code = response.code
assertThat(code).isEqualTo(200)
assertThat(body).isNotNull()
assertThat(body).isEqualTo("This is a valid response")
mockXCTestInstaller.assertInstallationRetries(0)
mockWebServer.shutdown()
}
@Test
fun `it should return correct message in case of UnknownHostException without retries`() {
// given
val mockWebServer = MockWebServer()
mockWebServer.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)
)
mockWebServer.start(InetAddress.getByName( "localhost"), 22087)
val httpUrl = mockWebServer.url("http://nonexistent-domain.local")
val mapper = jacksonObjectMapper()
// when
val simulator = MockXCTestInstaller.Simulator(
installationRetryCount = 0,
shouldInstall = false
)
val mockXCTestInstaller = MockXCTestInstaller(simulator)
val xcTestDriverClient = XCTestDriverClient(
mockXCTestInstaller,
IOSDriverLogger(XCTestDriverClient::class.java),
XCTestClient("localhost", 22087)
)
val response = xcTestDriverClient.deviceInfo(httpUrl)
// then
val networkErrorModel = response.body?.use {
mapper.readValue(it.bytes(), NetworkException.NetworkErrorModel::class.java)
} ?: throw IllegalStateException("No NetworkError model found for response body")
assertThat(response.code).isEqualTo(502)
assertThat(networkErrorModel.userFriendlyMessage).contains(
"The host for the XCUITest server is unknown."
)
mockXCTestInstaller.assertInstallationRetries(0)
mockWebServer.shutdown()
}
@Test
fun `it should return correct message in case of ConnectExceptions with 3 retries`() {
// given
val mockWebServer = MockWebServer()
mockWebServer.enqueue(
MockResponse()
.setSocketPolicy(SocketPolicy.DISCONNECT_DURING_REQUEST_BODY)
)
mockWebServer.start(InetAddress.getByName( "localhost"), 22087)
val httpUrl = mockWebServer.url("/deviceInfo")
mockWebServer.shutdown()
val mapper = jacksonObjectMapper()
// when
val simulator = MockXCTestInstaller.Simulator(
installationRetryCount = 0,
shouldInstall = false
)
val mockXCTestInstaller = MockXCTestInstaller(simulator)
val xcTestDriverClient = XCTestDriverClient(
mockXCTestInstaller,
IOSDriverLogger(XCTestDriverClient::class.java),
XCTestClient("localhost", 22087)
)
val response = xcTestDriverClient.deviceInfo(httpUrl)
// then
assertThat(response.code).isEqualTo(502)
val networkErrorModel = response.body?.use {
mapper.readValue(it.bytes(), NetworkException.NetworkErrorModel::class.java)
} ?: throw IllegalStateException("No NetworkError model found for response body")
assertThat(networkErrorModel.userFriendlyMessage).contains(
"Unable to establish a connection to the XCUITest server."
)
mockXCTestInstaller.assertInstallationRetries(3)
}
} | 236 | Kotlin | 160 | 4,242 | 6d369c39c7e9735d58311d0e3c83dc6ff862ac66 | 6,995 | maestro | Apache License 2.0 |
app/src/main/kotlin/com/mgaetan89/showsrage/adapter/EpisodePagerAdapter.kt | MGaetan89 | 38,072,270 | false | null | package com.mgaetan89.showsrage.adapter
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import com.mgaetan89.showsrage.Constants
import com.mgaetan89.showsrage.R
import com.mgaetan89.showsrage.fragment.EpisodeDetailFragment
import com.mgaetan89.showsrage.model.Episode
class EpisodePagerAdapter(fragmentManager: FragmentManager, val fragment: Fragment, val episodes: List<Int>) : FragmentStatePagerAdapter(fragmentManager) {
override fun getCount() = this.episodes.size
override fun getItem(position: Int): Fragment {
val episodeNumber = this.episodes[position]
val indexerId = this.fragment.arguments?.getInt(Constants.Bundle.INDEXER_ID) ?: 0
val seasonNumber = this.fragment.arguments?.getInt(Constants.Bundle.SEASON_NUMBER) ?: 0
val arguments = Bundle(this.fragment.arguments)
arguments.putString(Constants.Bundle.EPISODE_ID, Episode.buildId(indexerId, seasonNumber, episodeNumber))
arguments.putInt(Constants.Bundle.EPISODE_NUMBER, episodeNumber)
val fragment = EpisodeDetailFragment()
fragment.arguments = arguments
return fragment
}
override fun getPageTitle(position: Int): CharSequence? {
val episode = this.episodes[position]
return this.fragment.getString(R.string.episode_name_short, episode)
}
}
| 20 | null | 11 | 52 | b677ff242caecf0d4685d71ade56ae9a204727b1 | 1,361 | ShowsRage | Apache License 2.0 |
character_search/src/test/java/com/ezike/tobenna/starwarssearch/charactersearch/presentation/SearchScreenStateReducerTest.kt | Ezike | 294,171,829 | false | {"Kotlin": 190696, "Shell": 657} | package com.ezike.tobenna.starwarssearch.charactersearch.presentation
import com.ezike.tobenna.starwarssearch.charactersearch.data.DummyData
import com.ezike.tobenna.starwarssearch.charactersearch.mapper.CharacterModelMapper
import com.ezike.tobenna.starwarssearch.charactersearch.presentation.SearchScreenResult.SearchCharacterResult
import com.ezike.tobenna.starwarssearch.charactersearch.presentation.viewstate.SearchScreenState
import com.ezike.tobenna.starwarssearch.charactersearch.ui.views.history.SearchHistoryViewState
import com.ezike.tobenna.starwarssearch.charactersearch.ui.views.result.SearchResultViewState
import com.ezike.tobenna.starwarssearch.libcharactersearch.domain.model.Character
import com.ezike.tobenna.starwarssearch.testutils.ERROR_MSG
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Test
class SearchScreenStateReducerTest {
private val mapper = CharacterModelMapper()
private val reducer = SearchScreenStateReducer(mapper)
@Test
fun `check that emptySearchHistoryState is emitted when SearchHistoryResult is Empty`() {
runBlockingTest {
val initialState: SearchScreenState = SearchScreenState.Initial
val viewState: SearchScreenState = reducer.reduce(
initialState,
SearchScreenResult.LoadedHistory(emptyList())
)
assertThat(viewState).isEqualTo(
SearchScreenState.HistoryView(
SearchHistoryViewState.DataLoaded(emptyList())
)
)
}
}
@Test
fun `check that SearchHistoryLoadedState is emitted when SearchHistoryResult is Success`() {
runBlockingTest {
val initialState: SearchScreenState = SearchScreenState.Initial
val list: List<Character> = DummyData.characterList
val viewState: SearchScreenState = reducer.reduce(
initialState,
SearchScreenResult.LoadedHistory(list)
)
assertThat(viewState).isEqualTo(
SearchScreenState.HistoryView(
SearchHistoryViewState.DataLoaded(mapper.mapToModelList(list))
)
)
}
}
@Test
fun `check that SearchingState is emitted when SearchCharacterResult is Searching`() {
runBlockingTest {
val initialState: SearchScreenState = SearchScreenState.Initial
val viewState: SearchScreenState = reducer.reduce(
initialState,
SearchCharacterResult.Searching
)
assertThat(viewState).isEqualTo(
SearchScreenState.ResultView(
SearchResultViewState.Searching(emptyList())
)
)
}
}
@Test
fun `check that SearchResultLoadedState is emitted when SearchCharacterResult is Success`() {
runBlockingTest {
val initialState: SearchScreenState = SearchScreenState.Initial
val list: List<Character> = DummyData.characterList
val viewState: SearchScreenState = reducer.reduce(
initialState,
SearchCharacterResult.LoadedSearchResult(list)
)
assertThat(viewState).isEqualTo(
SearchScreenState.ResultView(
SearchResultViewState.DataLoaded(mapper.mapToModelList(list))
)
)
}
}
@Test
fun `check that SearchResultErrorState is emitted when SearchCharacterResult is Error`() {
runBlockingTest {
val initialState: SearchScreenState = SearchScreenState.Initial
val viewState: SearchScreenState = reducer.reduce(
initialState,
SearchCharacterResult.SearchError(Throwable(ERROR_MSG))
)
assertThat(viewState).isEqualTo(
SearchScreenState.ResultView(
SearchResultViewState.Error(ERROR_MSG)
)
)
}
}
@Test
fun `check that fall back error message is returned when SearchCharacterResult is Error`() {
runBlockingTest {
val initialState: SearchScreenState = SearchScreenState.Initial
val viewState: SearchScreenState = reducer.reduce(
initialState,
SearchCharacterResult.SearchError(Throwable())
)
assertThat(viewState).isEqualTo(
SearchScreenState.ResultView(
SearchResultViewState.Error("An error occurred")
)
)
}
}
}
| 0 | Kotlin | 30 | 198 | 0dadbc74a04bc6530cbee594716aae214fe24cc6 | 4,674 | StarWarsSearch-MVI | Apache License 2.0 |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Brackets.kt | walter-juan | 868,046,028 | false | {"Kotlin": 20416825} | package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.AlignLeft2: ImageVector
get() {
if (_alignLeft2 != null) {
return _alignLeft2!!
}
_alignLeft2 = Builder(name = "AlignLeft2", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 4.0f)
verticalLineToRelative(16.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(8.0f, 6.0f)
horizontalLineToRelative(12.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(8.0f, 12.0f)
horizontalLineToRelative(6.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(8.0f, 18.0f)
horizontalLineToRelative(10.0f)
}
}
.build()
return _alignLeft2!!
}
private var _alignLeft2: ImageVector? = null
| 0 | Kotlin | 0 | 1 | b037895588c2f62d069c724abe624b67c0889bf9 | 2,561 | compose-icon-collections | MIT License |
solar/src/main/java/com/chiksmedina/solar/outline/files/FileCorrupted.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.outline.files
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.outline.FilesGroup
val FilesGroup.FileCorrupted: ImageVector
get() {
if (_fileCorrupted != null) {
return _fileCorrupted!!
}
_fileCorrupted = Builder(
name = "FileCorrupted", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(12.25f, 2.8336f)
curveTo(11.7897f, 2.7559f, 11.1621f, 2.7501f, 10.0324f, 2.7501f)
curveTo(8.1151f, 2.7501f, 6.7523f, 2.7516f, 5.719f, 2.8899f)
curveTo(4.7067f, 3.0253f, 4.125f, 3.2794f, 3.7022f, 3.702f)
curveTo(3.2788f, 4.1253f, 3.0251f, 4.7049f, 2.8898f, 5.7109f)
curveTo(2.7516f, 6.7386f, 2.75f, 8.0932f, 2.75f, 10.0001f)
verticalLineTo(11.9397f)
curveTo(2.75f, 12.0247f, 2.75f, 12.0794f, 2.7506f, 12.1201f)
curveTo(2.7511f, 12.1474f, 2.7517f, 12.1594f, 2.7519f, 12.1622f)
curveTo(2.773f, 12.3333f, 2.9578f, 12.4327f, 3.1126f, 12.355f)
curveTo(3.115f, 12.3535f, 3.1254f, 12.3474f, 3.1484f, 12.3326f)
curveTo(3.1826f, 12.3106f, 3.2282f, 12.2802f, 3.2989f, 12.2331f)
curveTo(4.3296f, 11.5462f, 5.6723f, 11.5462f, 6.703f, 12.2331f)
curveTo(7.4896f, 12.7573f, 8.5143f, 12.7573f, 9.3008f, 12.2331f)
curveTo(10.3316f, 11.5462f, 11.6743f, 11.5462f, 12.705f, 12.2331f)
curveTo(13.4915f, 12.7573f, 14.5163f, 12.7573f, 15.3028f, 12.2331f)
curveTo(16.3335f, 11.5462f, 17.6762f, 11.5462f, 18.7069f, 12.2331f)
curveTo(19.4749f, 12.7449f, 20.4699f, 12.757f, 21.2486f, 12.2694f)
curveTo(21.233f, 11.5536f, 21.1871f, 11.1061f, 21.0821f, 10.7501f)
horizontalLineTo(17.9463f)
curveTo(16.8135f, 10.7501f, 15.8877f, 10.7501f, 15.1569f, 10.6518f)
curveTo(14.3929f, 10.5491f, 13.7306f, 10.3268f, 13.2019f, 9.7982f)
curveTo(12.6732f, 9.2695f, 12.4509f, 8.6071f, 12.3482f, 7.8432f)
curveTo(12.2499f, 7.1123f, 12.25f, 6.1866f, 12.25f, 5.0537f)
verticalLineTo(2.8336f)
close()
moveTo(13.75f, 3.6062f)
verticalLineTo(5.0001f)
curveTo(13.75f, 6.1998f, 13.7516f, 7.0241f, 13.8348f, 7.6433f)
curveTo(13.9152f, 8.2409f, 14.059f, 8.5339f, 14.2625f, 8.7375f)
curveTo(14.4661f, 8.941f, 14.7591f, 9.0849f, 15.3567f, 9.1652f)
curveTo(15.9759f, 9.2485f, 16.8003f, 9.25f, 18.0f, 9.25f)
horizontalLineTo(20.0255f)
curveTo(19.729f, 8.9625f, 19.3491f, 8.618f, 18.8557f, 8.1742f)
lineTo(14.8957f, 4.6112f)
curveTo(14.4079f, 4.1724f, 14.0454f, 3.849f, 13.75f, 3.6062f)
close()
moveTo(10.178f, 1.25f)
curveTo(11.5632f, 1.2497f, 12.4579f, 1.2494f, 13.2814f, 1.5653f)
curveTo(14.1049f, 1.8812f, 14.7671f, 2.4773f, 15.7916f, 3.3995f)
curveTo(15.8269f, 3.4313f, 15.8627f, 3.4635f, 15.8989f, 3.4962f)
lineTo(19.859f, 7.059f)
curveTo(19.9012f, 7.097f, 19.9428f, 7.1344f, 19.984f, 7.1714f)
curveTo(21.168f, 8.236f, 21.9336f, 8.9245f, 22.3455f, 9.8489f)
curveTo(22.665f, 10.566f, 22.7314f, 11.3208f, 22.7497f, 12.3135f)
curveTo(22.7585f, 12.7861f, 22.5227f, 13.224f, 22.1366f, 13.4813f)
curveTo(20.8463f, 14.3412f, 19.1654f, 14.3412f, 17.8751f, 13.4813f)
curveTo(17.3481f, 13.1301f, 16.6616f, 13.1301f, 16.1347f, 13.4813f)
curveTo(14.8444f, 14.3412f, 13.1634f, 14.3412f, 11.8731f, 13.4813f)
curveTo(11.3462f, 13.1301f, 10.6597f, 13.1301f, 10.1327f, 13.4813f)
curveTo(8.8424f, 14.3412f, 7.1615f, 14.3412f, 5.8712f, 13.4813f)
curveTo(5.3442f, 13.1301f, 4.6577f, 13.1301f, 4.1308f, 13.4813f)
curveTo(4.1206f, 13.4881f, 4.1104f, 13.4949f, 4.1003f, 13.5016f)
curveTo(3.9951f, 13.5719f, 3.8921f, 13.6406f, 3.8041f, 13.6861f)
curveTo(2.7138f, 14.2496f, 1.3965f, 13.5453f, 1.2607f, 12.3251f)
curveTo(1.2498f, 12.2266f, 1.2499f, 12.1028f, 1.25f, 11.9764f)
curveTo(1.25f, 11.9642f, 1.25f, 11.952f, 1.25f, 11.9397f)
lineTo(1.25f, 9.9436f)
curveTo(1.25f, 8.1059f, 1.25f, 6.6502f, 1.4032f, 5.511f)
curveTo(1.5609f, 4.3385f, 1.8931f, 3.3896f, 2.6417f, 2.6412f)
curveTo(3.3908f, 1.8923f, 4.3432f, 1.5606f, 5.5201f, 1.4031f)
curveTo(6.6644f, 1.25f, 8.1277f, 1.25f, 9.9761f, 1.25f)
lineTo(10.0324f, 1.25f)
curveTo(10.0815f, 1.25f, 10.1301f, 1.25f, 10.178f, 1.25f)
close()
moveTo(5.8712f, 17.4813f)
curveTo(5.3442f, 17.1301f, 4.6577f, 17.1301f, 4.1308f, 17.4813f)
lineTo(3.5046f, 17.8986f)
curveTo(3.2366f, 18.0772f, 3.0914f, 18.1755f, 2.993f, 18.2599f)
curveTo(2.9501f, 18.2967f, 2.931f, 18.3188f, 2.9228f, 18.3294f)
curveTo(2.9165f, 18.3375f, 2.9145f, 18.3416f, 2.9123f, 18.3472f)
lineTo(2.9118f, 18.3485f)
curveTo(2.905f, 18.366f, 2.899f, 18.3809f, 2.9051f, 18.4446f)
curveTo(2.9145f, 18.5426f, 2.9438f, 18.6724f, 3.0078f, 18.941f)
curveTo(3.1551f, 19.5588f, 3.3767f, 19.9727f, 3.7022f, 20.2981f)
curveTo(4.1256f, 20.7213f, 4.7055f, 20.975f, 5.712f, 21.1103f)
curveTo(6.74f, 21.2485f, 8.0952f, 21.2501f, 10.0026f, 21.2501f)
horizontalLineTo(14.0039f)
curveTo(15.9113f, 21.2501f, 17.2665f, 21.2485f, 18.2945f, 21.1103f)
curveTo(19.301f, 20.975f, 19.8809f, 20.7213f, 20.3043f, 20.2981f)
curveTo(20.7776f, 19.8249f, 21.0337f, 19.1631f, 21.1559f, 17.9503f)
curveTo(20.0656f, 18.2922f, 18.8572f, 18.1358f, 17.8751f, 17.4813f)
curveTo(17.3481f, 17.1301f, 16.6616f, 17.1301f, 16.1347f, 17.4813f)
curveTo(14.8444f, 18.3412f, 13.1634f, 18.3412f, 11.8731f, 17.4813f)
curveTo(11.3462f, 17.1301f, 10.6597f, 17.1301f, 10.1327f, 17.4813f)
curveTo(8.8424f, 18.3412f, 7.1615f, 18.3412f, 5.8712f, 17.4813f)
close()
moveTo(3.2989f, 16.2331f)
curveTo(4.3296f, 15.5462f, 5.6723f, 15.5462f, 6.703f, 16.2331f)
curveTo(7.4896f, 16.7573f, 8.5143f, 16.7573f, 9.3008f, 16.2331f)
curveTo(10.3316f, 15.5462f, 11.6743f, 15.5462f, 12.705f, 16.2331f)
curveTo(13.4915f, 16.7573f, 14.5163f, 16.7573f, 15.3028f, 16.2331f)
curveTo(16.3335f, 15.5462f, 17.6762f, 15.5462f, 18.7069f, 16.2331f)
curveTo(19.4935f, 16.7573f, 20.5182f, 16.7573f, 21.3048f, 16.2331f)
curveTo(21.9217f, 15.822f, 22.752f, 16.2805f, 22.721f, 17.0289f)
curveTo(22.6429f, 18.9115f, 22.3944f, 20.3297f, 21.3648f, 21.3589f)
curveTo(20.6162f, 22.1072f, 19.6671f, 22.4393f, 18.4943f, 22.5969f)
curveTo(17.3548f, 22.7501f, 15.8987f, 22.7501f, 14.0603f, 22.7501f)
horizontalLineTo(9.9462f)
curveTo(8.1078f, 22.7501f, 6.6517f, 22.7501f, 5.5122f, 22.5969f)
curveTo(4.3394f, 22.4393f, 3.3902f, 22.1072f, 2.6417f, 21.3589f)
curveTo(2.0747f, 20.7921f, 1.7437f, 20.1068f, 1.5487f, 19.2888f)
curveTo(1.5419f, 19.2604f, 1.535f, 19.2318f, 1.528f, 19.2029f)
curveTo(1.4272f, 18.7868f, 1.313f, 18.3156f, 1.5163f, 17.7984f)
curveTo(1.6315f, 17.5054f, 1.8138f, 17.2951f, 2.0164f, 17.1214f)
curveTo(2.1925f, 16.9703f, 2.4157f, 16.8216f, 2.6441f, 16.6694f)
lineTo(3.2989f, 16.2331f)
close()
}
}
.build()
return _fileCorrupted!!
}
private var _fileCorrupted: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 8,967 | SolarIconSetAndroid | MIT License |
ViewBinding/app/src/main/java/com/mac/jamil/SignUp.kt | Jamil226 | 791,254,798 | false | {"Kotlin": 63972, "Java": 2228} | package com.jamil.app
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.jamil.app.databinding.ActivitySignUpBinding
class SignUp : AppCompatActivity() {
private lateinit var binding:ActivitySignUpBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignUpBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnSignUp.setOnClickListener {
Toast.makeText(this, "Sign Up Success", Toast.LENGTH_LONG).show()
val i = Intent(this, Login::class.java)
startActivity(i)
}
}
} | 0 | Kotlin | 1 | 4 | 9366d713e95fdf849acfaa3a3b1ae5857b9219cb | 730 | AndroidDev | Apache License 2.0 |
buildSrc/src/main/kotlin/plugin/ProjectConfigureDetekt.kt | gojek | 483,142,816 | false | {"Kotlin": 482600, "Shell": 9122} | package plugin
import deps
import io.gitlab.arturbosch.detekt.DetektPlugin
import io.gitlab.arturbosch.detekt.detekt
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.dependencies
import versions
class DetektConfigurationPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.apply<DetektPlugin>()
project.afterEvaluate {
val configFile = "$rootDir/buildSrc/detekt/detekt.yml"
detekt {
toolVersion = versions.detekt
input = files(
"src/main/kotlin",
"src/test/kotlin",
"src/androidTest/kotlin"
)
config = files(configFile)
reports {
xml {
enabled = true
destination = file("${rootDir}/report/${project.name}/detekt/detekt.xml")
}
html {
enabled = true
destination = file("${rootDir}/report/${project.name}/detekt/detekt.html")
}
}
}
dependencies {
add("detekt", deps.detekt.cli)
add("detektPlugins", deps.detekt.lint)
}
}
}
}
| 2 | Kotlin | 9 | 67 | 7cc79cbf17be9a47103fd0585d0f158d7e75d40a | 1,380 | clickstream-android | Apache License 2.0 |
lista-testing/src/main/java/com/rubensousa/lista/testing/actions/WaitForItemViewLayoutAction.kt | rubensousa | 259,334,522 | false | null | /*
* Copyright (c) 2020. Cabriole
*
* 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.cabriole.lista.testing.actions
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom
import org.hamcrest.Matcher
/**
* An Action that waits until a RecyclerView has at least one item laid out
*/
class WaitForItemViewLayoutAction : ViewAction {
override fun getDescription(): String {
return "Waiting for RecyclerView layout"
}
override fun getConstraints(): Matcher<View> {
return isAssignableFrom(RecyclerView::class.java)
}
override fun perform(uiController: UiController?, view: View) {
if (view !is RecyclerView) {
return
}
var itemView = getView(view)
while (itemView == null || (!itemView.isLaidOut || itemView.height == 0)) {
itemView = getView(view)
}
}
private fun getView(view: RecyclerView): View? {
if (view.adapter == null) {
return null
}
return view.getChildAt(0)
}
}
| 0 | null | 4 | 14 | ad727e02dd13a5cd2e7a171d99baca4a572e6e27 | 1,721 | lista | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Selection.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.Selection: ImageVector
get() {
if (_selection != null) {
return _selection!!
}
_selection = Builder(name = "Selection", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(19.0f, 2.0f)
curveToRelative(0.0f, -1.105f, 0.895f, -2.0f, 2.0f, -2.0f)
reflectiveCurveToRelative(2.0f, 0.895f, 2.0f, 2.0f)
reflectiveCurveToRelative(-0.895f, 2.0f, -2.0f, 2.0f)
reflectiveCurveToRelative(-2.0f, -0.895f, -2.0f, -2.0f)
close()
moveTo(3.0f, 4.0f)
curveToRelative(1.105f, 0.0f, 2.0f, -0.895f, 2.0f, -2.0f)
reflectiveCurveTo(4.105f, 0.0f, 3.0f, 0.0f)
reflectiveCurveTo(1.0f, 0.895f, 1.0f, 2.0f)
reflectiveCurveToRelative(0.895f, 2.0f, 2.0f, 2.0f)
close()
moveTo(23.969f, 7.121f)
curveToRelative(-0.376f, -1.228f, -1.518f, -2.121f, -2.869f, -2.121f)
horizontalLineToRelative(-1.169f)
curveToRelative(0.041f, 0.328f, 0.069f, 0.661f, 0.069f, 1.0f)
curveToRelative(0.0f, 0.692f, -0.097f, 1.36f, -0.262f, 2.0f)
horizontalLineToRelative(3.603f)
curveToRelative(0.454f, 0.0f, 0.76f, -0.444f, 0.628f, -0.879f)
close()
moveTo(4.0f, 6.0f)
curveToRelative(0.0f, -0.339f, 0.028f, -0.672f, 0.069f, -1.0f)
horizontalLineToRelative(-1.154f)
curveTo(1.533f, 5.0f, 0.368f, 5.935f, 0.021f, 7.208f)
curveToRelative(-0.11f, 0.403f, 0.229f, 0.792f, 0.647f, 0.792f)
horizontalLineToRelative(3.594f)
curveToRelative(-0.165f, -0.64f, -0.262f, -1.308f, -0.262f, -2.0f)
close()
moveTo(12.0f, 6.0f)
curveToRelative(0.828f, 0.0f, 1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
close()
moveTo(21.999f, 22.942f)
curveToRelative(0.032f, 0.551f, -0.389f, 1.024f, -0.94f, 1.057f)
curveToRelative(-0.02f, 0.0f, -0.04f, 0.001f, -0.059f, 0.001f)
curveToRelative(-0.526f, 0.0f, -0.966f, -0.41f, -0.998f, -0.942f)
curveToRelative(-0.068f, -1.183f, -0.831f, -2.217f, -1.941f, -2.633f)
lineToRelative(-4.38f, -1.477f)
curveToRelative(-0.406f, -0.137f, -0.68f, -0.519f, -0.68f, -0.948f)
verticalLineToRelative(-4.893f)
curveToRelative(0.0f, -0.537f, -0.362f, -1.017f, -0.825f, -1.093f)
curveToRelative(-0.304f, -0.049f, -0.595f, 0.03f, -0.823f, 0.224f)
curveToRelative(-0.224f, 0.19f, -0.353f, 0.468f, -0.353f, 0.762f)
verticalLineToRelative(7.455f)
curveToRelative(0.0f, 0.608f, -0.34f, 1.15f, -0.889f, 1.415f)
reflectiveCurveToRelative(-1.184f, 0.191f, -1.66f, -0.186f)
curveToRelative(0.0f, 0.0f, -1.761f, -1.405f, -1.771f, -1.415f)
curveToRelative(-0.402f, -0.373f, -1.034f, -0.354f, -1.41f, 0.048f)
curveToRelative(-0.377f, 0.403f, -0.356f, 1.038f, 0.046f, 1.416f)
lineToRelative(0.568f, 0.548f)
curveToRelative(0.648f, 0.624f, 0.206f, 1.72f, -0.694f, 1.72f)
curveToRelative(-0.259f, 0.0f, -0.508f, -0.1f, -0.694f, -0.28f)
lineToRelative(-0.558f, -0.538f)
curveToRelative(-1.196f, -1.12f, -1.26f, -3.022f, -0.13f, -4.23f)
curveToRelative(1.103f, -1.181f, 2.94f, -1.26f, 4.151f, -0.208f)
curveToRelative(0.008f, 0.006f, 1.04f, 0.821f, 1.04f, 0.821f)
verticalLineToRelative(-6.563f)
curveToRelative(0.0f, -0.567f, 0.174f, -1.106f, 0.467f, -1.576f)
curveToRelative(-2.093f, -0.976f, -3.467f, -3.072f, -3.467f, -5.424f)
curveToRelative(0.0f, -3.309f, 2.691f, -6.0f, 6.0f, -6.0f)
reflectiveCurveToRelative(6.0f, 2.691f, 6.0f, 6.0f)
curveToRelative(0.0f, 2.373f, -1.375f, 4.464f, -3.482f, 5.435f)
curveToRelative(0.302f, 0.488f, 0.482f, 1.062f, 0.482f, 1.672f)
verticalLineToRelative(4.175f)
lineToRelative(3.731f, 1.258f)
curveToRelative(1.882f, 0.706f, 3.153f, 2.429f, 3.268f, 4.401f)
close()
moveTo(8.0f, 6.0f)
curveToRelative(0.0f, 1.11f, 0.46f, 2.135f, 1.221f, 2.872f)
curveToRelative(0.444f, -1.097f, 1.515f, -1.872f, 2.771f, -1.872f)
horizontalLineToRelative(0.016f)
curveToRelative(1.255f, 0.0f, 2.325f, 0.778f, 2.769f, 1.875f)
curveToRelative(0.762f, -0.735f, 1.223f, -1.757f, 1.223f, -2.875f)
curveToRelative(0.0f, -2.206f, -1.794f, -4.0f, -4.0f, -4.0f)
reflectiveCurveToRelative(-4.0f, 1.794f, -4.0f, 4.0f)
close()
}
}
.build()
return _selection!!
}
private var _selection: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 6,217 | icons | MIT License |
app/src/test/kotlin/fr/free/nrw/commons/feedback/FeedbackDialogTests.kt | commons-app | 42,032,884 | false | null | package fr.free.nrw.commons.feedback
import android.content.Context
import android.os.Looper.getMainLooper
import android.text.Editable
import androidx.test.core.app.ApplicationProvider
import com.nhaarman.mockitokotlin2.doReturn
import fr.free.nrw.commons.TestAppAdapter
import fr.free.nrw.commons.TestCommonsApplication
import fr.free.nrw.commons.TestUtility.setFinalStatic
import fr.free.nrw.commons.contributions.MainActivity
import fr.free.nrw.commons.databinding.DialogFeedbackBinding
import fr.free.nrw.commons.ui.PasteSensitiveTextInputEditText
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.MockitoAnnotations
import org.powermock.reflect.Whitebox
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import org.wikipedia.AppAdapter
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
@LooperMode(LooperMode.Mode.PAUSED)
class FeedbackDialogTests {
private lateinit var dialogFeedbackBinding: DialogFeedbackBinding
@Mock
private val onFeedbackSubmitCallback: OnFeedbackSubmitCallback? = null
private lateinit var dialog: FeedbackDialog
private lateinit var context: Context
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
context = ApplicationProvider.getApplicationContext()
AppAdapter.set(TestAppAdapter())
val activity = Robolectric.buildActivity(MainActivity::class.java).create().get()
dialog = FeedbackDialog(activity.applicationContext, onFeedbackSubmitCallback)
dialogFeedbackBinding = DialogFeedbackBinding.inflate(dialog.layoutInflater)
dialog.show()
Whitebox.setInternalState(dialog, "onFeedbackSubmitCallback", onFeedbackSubmitCallback)
Whitebox.setInternalState(dialog, "dialogFeedbackBinding", dialogFeedbackBinding)
}
@Test
fun testOnCreate() {
dialog.onCreate(null)
}
@Test
fun testSubmitFeedbackError() {
val editable = mock(Editable::class.java)
val ed = mock(PasteSensitiveTextInputEditText::class.java)
setFinalStatic(
DialogFeedbackBinding::class.java.getDeclaredField("feedbackItemEditText"),
ed)
`when`(ed?.text).thenReturn(editable)
doReturn(editable).`when`(ed)?.text
doReturn("").`when`(editable).toString()
dialog.submitFeedback()
}
@Test
fun testSubmitFeedback() {
shadowOf(getMainLooper()).idle()
val editable: Editable = mock(Editable::class.java)
val ed = mock(PasteSensitiveTextInputEditText::class.java)
setFinalStatic(
DialogFeedbackBinding::class.java.getDeclaredField("feedbackItemEditText"),
ed)
`when`(ed?.text).thenReturn(editable)
`when`(editable.toString()).thenReturn("1234")
Assert.assertEquals(ed.text.toString(), "1234")
dialog.submitFeedback()
}
} | 571 | null | 1179 | 997 | 93f1e1ec299a78dac8a013ea21414272c1675e7b | 3,248 | apps-android-commons | Apache License 2.0 |
basicktest/src/main/java/com/mozhimen/basicktest/elemk/android/ElemKAutoRunReceiver.kt | mozhimen | 353,952,154 | false | {"Kotlin": 2509081, "Java": 320961, "AIDL": 1012} | package com.mozhimen.basicktest.elemk.android
import com.mozhimen.basick.elemk.android.content.bases.BaseBootBroadcastReceiver
import com.mozhimen.basick.manifestk.cons.CPermission
import com.mozhimen.basick.manifestk.annors.AManifestKRequire
import com.mozhimen.basicktest.BasicKActivity
/**
* @ClassName AutoRunReceiver
* @Description TODO
* @Author <NAME> / Mozhimen
* @Date 2022/9/26 18:53
* @Version 1.0
*/
@AManifestKRequire(CPermission.RECEIVE_BOOT_COMPLETED)
class ElemKAutoRunReceiver : BaseBootBroadcastReceiver(BasicKActivity::class.java, 5000) | 0 | Kotlin | 6 | 114 | d74563aa5722b01ceb0e7d24c9001050b577db5d | 563 | SwiftKit | Apache License 2.0 |
common/src/commonMain/kotlin/com.chrynan.chat/model/contact/ContactInfo.kt | chRyNaN | 206,982,352 | false | null | package com.chrynan.chat.model.contact
data class ContactInfo(
val addresses: List<FullAddress> = emptyList(),
val webAddresses: List<WebAddress> = emptyList(),
val importantDates: List<ImportantDate> = emptyList(),
val places: List<Place> = emptyList(),
val phoneNumbers: List<PhoneNumber> = emptyList(),
val emails: List<Email> = emptyList(),
val interests: List<String> = emptyList(),
val notes: List<String> = emptyList()
) | 0 | Kotlin | 0 | 3 | 8269e4bcecad6ba4ef10e211ca4cb52e1cdff4b8 | 460 | Chat | Apache License 2.0 |
src/main/kotlin/it/bot/repository/UserRepository.kt | gturi | 480,951,059 | false | {"Kotlin": 113492, "Shell": 1788, "HTML": 658} | package it.bot.repository
import io.quarkus.hibernate.orm.panache.kotlin.PanacheRepository
import it.bot.model.entity.UserEntity
import javax.enterprise.context.ApplicationScoped
@ApplicationScoped
class UserRepository : PanacheRepository<UserEntity> {
fun findUser(telegramUserId: Long): UserEntity? {
return find("telegramUserId = ?1", telegramUserId).firstResult()
}
fun findUser(telegramUserId: Long, chatId: Long, orderName: String): UserEntity? {
val query = """
select u
from UserEntity u
join OrderEntity o on o.orderId = u.orderId
where u.telegramUserId = ?1
and o.chatId = ?2
and o.name = ?3
"""
return find(query, telegramUserId, chatId, orderName).firstResult()
}
fun findUsers(telegramUserId: Long): List<UserEntity> {
val query = "telegramUserId = ?1"
return find(query, telegramUserId).list()
}
fun findUsers(telegramUserId: Long, chatId: Long): List<UserEntity> {
val query = """
select u
from UserEntity u
join OrderEntity o on o.orderId = u.orderId
where u.telegramUserId = ?1
and o.chatId = ?2
"""
return find(query, telegramUserId, chatId).list()
}
fun deleteOrderUsers(orderId: Long) {
val query = """orderId = ?1"""
delete(query, orderId)
}
}
| 0 | Kotlin | 0 | 0 | af641c01ff1ca4e7dda9f04b4fae99c55e2ea8b7 | 1,432 | all-you-can-eat-bot | MIT License |
2020-apps/project-app-folder/app/src/main/java/shortcourse/legere/view/LoginActivity.kt | kevin2-cyber | 437,880,493 | false | null | package shortcourse.legere.view
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Patterns
import androidx.core.widget.addTextChangedListener
import androidx.databinding.DataBindingUtil
import shortcourse.legere.R
import shortcourse.legere.databinding.ActivityLoginBinding
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,
R.layout.activity_login
)
// Bind properties
binding.run {
// Listen for changes in the user's input
// and update the login button respectively
emailField.addTextChangedListener { content ->
val userEmail: String? = content?.toString()
loginButton.isEnabled = !userEmail.isNullOrEmpty() && Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()
}
passwordField
loginButton.setOnClickListener {
// TODO: 2/23/20 Sign in with email & password
println("Hello world")
}
}
}
} | 0 | Kotlin | 0 | 1 | 182147dada04b383097d461d64e184048e5c3b66 | 1,240 | ug-short-course | MIT License |
library/src/main/java/in/nitin/library/FloatingLoaderButton.kt | NitinPraksash9911 | 258,980,609 | false | null | package `in`.nitin.library
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.content.res.TypedArray
import android.graphics.*
import android.graphics.drawable.Drawable
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RoundRectShape
import android.os.Build
import android.util.AttributeSet
import androidx.annotation.ColorInt
import androidx.annotation.FloatRange
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.view.ViewCompat
import androidx.databinding.BindingMethod
import androidx.databinding.BindingMethods
import androidx.vectordrawable.graphics.drawable.Animatable2Compat
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
/**
* [MustBeDocumented]
* @author <NAME>
*
* @since 25 April 2020
*
* @property:- * it can use to show loading status for an API, background task or anything
*
* */
@BindingMethods(
BindingMethod(
type = FloatingLoaderButton::class,
attribute = "app:loadingStatus",
method = "setLoadingStatus"
),
BindingMethod(
type = FloatingLoaderButton::class,
attribute = "app:loadingIconColor",
method = "setLoadingIconColor"
), BindingMethod(
type = FloatingLoaderButton::class,
attribute = "app:loaderBackgroundColor",
method = "setLoaderBgColor"
)
)
class FloatingLoaderButton : AppCompatImageView {
enum class LoaderStatus {
LOADING,
FINISH,
NONE
}
private enum class LoaderFabSize {
SMALL,
MEDIUM,
LARGE
}
private var iconColor: Int = 0
private var loaderStatus = LoaderStatus.NONE
private var loaderSize = LoaderFabSize.MEDIUM
private var loaderbgColor: Int = 0
var isLoading: Boolean = false
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
initViewRes(context, attrs, defStyleAttr)
}
@SuppressLint("CustomViewStyleable")
private fun initViewRes(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int
) {
val styleAttributesArray =
context.obtainStyledAttributes(
attrs,
R.styleable.FabLoader,
defStyleAttr,
0
)
iconColor =
styleAttributesArray.getColor(R.styleable.FabLoader_loadingIconColor, Color.WHITE)
loaderbgColor =
styleAttributesArray.getColor(R.styleable.FabLoader_loaderBackgroundColor, Color.BLACK)
loaderStatus =
styleAttributesArray.getEnum(R.styleable.FabLoader_loadingStatus, LoaderStatus.NONE)
loaderSize =
styleAttributesArray.getEnum(R.styleable.FabLoader_loaderFabSize, LoaderFabSize.MEDIUM)
setLoadingStatus(loaderStatus)
setLoaderBgColor(loaderbgColor)
setElevation()
setLoaderPadding()
styleAttributesArray.recycle()
}
private fun setElevation() {
val mElevation = getDimens(resources, R.dimen.loader_elevation).toFloat()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.elevation = mElevation
} else {
ViewCompat.setElevation(this, mElevation)
}
}
private fun setLoaderBgColor(@ColorInt bgColor: Int) {
when (loaderSize) {
LoaderFabSize.SMALL -> {
this.background = getRoundCornerShapeRect(
getDimens(
resources,
R.dimen.small_fab_loader
).toFloat(), bgColor
)
}
LoaderFabSize.MEDIUM -> {
this.background = getRoundCornerShapeRect(
getDimens(
resources,
R.dimen.medium_fab_loader
).toFloat(), bgColor
)
}
LoaderFabSize.LARGE -> {
this.background = getRoundCornerShapeRect(
getDimens(
resources,
R.dimen.large_fab_loader
).toFloat(), bgColor
)
}
}
}
private fun setLoaderPadding() {
val pad = getDimens(
resources,
R.dimen.loader_padding
)
this.setPadding(pad, pad, pad, pad)
}
@SuppressLint("ResourceType")
private fun setLoadingIconColor(@ColorInt iconColor: Int) {
setColorFilter(this.drawable, iconColor)
}
private fun setColorFilter(drawable: Drawable, color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
drawable.colorFilter = BlendModeColorFilter(color, BlendMode.SRC_ATOP)
} else {
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
when (loaderSize) {
LoaderFabSize.SMALL -> {
setFabButtonSize(getDimens(resources, R.dimen.small_fab_loader))
}
LoaderFabSize.MEDIUM -> {
setFabButtonSize(getDimens(resources, R.dimen.medium_fab_loader))
}
LoaderFabSize.LARGE -> {
setFabButtonSize(getDimens(resources, R.dimen.large_fab_loader))
}
}
}
private fun setFabButtonSize(size: Int) {
setMeasuredDimension(size, size)
}
/**
* set Loader status
* */
fun setLoadingStatus(value: LoaderStatus) {
when (value) {
LoaderStatus.LOADING -> {
startLoadingAnim()
}
LoaderStatus.FINISH -> {
isLoading = false
}
LoaderStatus.NONE -> {
getAnimatedDrawable(R.drawable.start_loading_56dp)
}
}
}
/**
* Use for start loading animation
* */
private fun startLoadingAnim() {
isLoading = true
this.isClickable = false
val anim = getAnimatedDrawable(R.drawable.start_loading_56dp)
anim.start()
anim.registerAnimationCallback(object : Animatable2Compat.AnimationCallback() {
override fun onAnimationEnd(drawable: Drawable?) {
super.onAnimationEnd(drawable)
/**
* [infinite] Loader
* */
startCircularLoaderAnim()
}
})
}
/**
* Execute immediately when startLoading anim finish
* */
private fun startCircularLoaderAnim() {
val loading = getAnimatedDrawable(R.drawable.progress_56dp)
loading.start()
loading.registerAnimationCallback(object : Animatable2Compat.AnimationCallback() {
override fun onAnimationEnd(drawable: Drawable?) {
super.onAnimationEnd(drawable)
if (!isLoading) {
finishLoadingAnim()
} else {
loading.start()
}
}
})
}
/**
* Execute when user end the loading animation
* */
private fun finishLoadingAnim() {
getAnimatedDrawable(R.drawable.end_loading_56dp).start()
this.isClickable = true
}
/**
* convert background as AnimatedVectorDrawable and return it
* */
private fun getAnimatedDrawable(animatedVectorDrawable: Int): Animatable2Compat {
val drawable = AnimatedVectorDrawableCompat.create(context, animatedVectorDrawable)
this.setImageDrawable(drawable)
setLoadingIconColor(iconColor)
return this.drawable as Animatable2Compat
}
/*get paint object with color*/
private fun getPaint(@ColorInt bgColor: Int): Paint {
val paint = Paint()
paint.isAntiAlias = true
paint.color = bgColor
return paint
}
/*get rounded corner rectangle with given corner radius*/
private fun getRoundCornerShapeRect(
@FloatRange cornerRadius: Float,
@ColorInt bgColor: Int
): ShapeDrawable {
val shape = ShapeDrawable(
RoundRectShape(
floatArrayOf(
cornerRadius,
cornerRadius,
cornerRadius,
cornerRadius,
cornerRadius,
cornerRadius,
cornerRadius,
cornerRadius
),
null, null
)
)
shape.paint.set(getPaint(bgColor))
return shape
}
private fun getDimens(resources: Resources, id: Int): Int {
return resources.getDimension(id).toInt()
}
/**
* get Enum for loader
* */
private inline fun <reified T : Enum<T>> TypedArray.getEnum(index: Int, default: T) =
getInt(index, -1).let {
if (it >= 0) enumValues<T>()[it] else default
}
} | 0 | Kotlin | 0 | 0 | b7d27e8b49fc44952073546d0dfc78b5fd2e638c | 9,348 | floating-loader-button | Apache License 2.0 |
app/src/main/java/com/jowney/adhdgames/dotsandboxs/DotsUiState.kt | JOwney96 | 778,646,411 | false | {"Kotlin": 88859} | package com.jowney.adhdgames.dotsandboxs
data class DotsUiState(
val edgeMap: Map<DotsEdge, DotsOwnerEnum>,
val squares: List<DotsSquare>,
val player1Score: Int,
val player2Score: Int,
val gameOver: Boolean,
val xSize: Int,
val ySize: Int,
val selectedPoints: List<DotsCoordinate>,
val turn: DotsOwnerEnum,
) | 0 | Kotlin | 0 | 0 | ffcfc9f0001593f38820f2487259b64b713da26f | 345 | ADHD-Games | Apache License 2.0 |
app/src/main/java/com/example/project_03_flixster_part_01/FlixsterFragment.kt | TosnEula | 543,336,305 | false | {"Kotlin": 8015} | package com.example.project_03_flixster_part_01
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.ContentLoadingProgressBar
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.codepath.asynchttpclient.AsyncHttpClient
import com.codepath.asynchttpclient.RequestParams
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Headers
import org.json.JSONArray
import org.json.JSONObject
private const val API_KEY = "a07e22bc18f5cb106bfe4cc1f83ad8ed"
/*
* The class for the only fragment in the app, which contains the progress bar
*/
class FlixsterFragment : Fragment() {
/*
* Constructing the view
*/
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_flixster_list, container, false)
val progressBar = view.findViewById<View>(R.id.progress) as ContentLoadingProgressBar
val recyclerView = view.findViewById<View>(R.id.movieListRW) as RecyclerView
val context = view.context
recyclerView.layoutManager = LinearLayoutManager(context)
updateAdapter(progressBar, recyclerView)
return view
}
/*
* Updates the RecyclerView adapter with new data.
*/
private fun updateAdapter(progressBar: ContentLoadingProgressBar, recyclerView: RecyclerView) {
progressBar.show()
// Create and set up an AsyncHTTPClient() here
val client = AsyncHttpClient()
val params = RequestParams()
params["api-key"] = API_KEY
// Using the client, perform the HTTP request
client[
"https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed&language=en-US&page=1",
params,
object : JsonHttpResponseHandler()
{
/*
* The onSuccess function gets called when
* HTTP response status is "200 OK"
*/
override fun onSuccess(
statusCode: Int,
headers: Headers,
json: JsonHttpResponseHandler.JSON
) {
// The wait for a response is over
progressBar.hide()
//Parse JSON into Models
val resultsJSON : JSONArray = json.jsonObject.get("results") as JSONArray
val moviesRawJSON : String = resultsJSON.toString()
val gson = Gson()
val arrayMovieType = object : TypeToken<List<MovieItem>>() {}.type
val models : List<MovieItem> = gson.fromJson(moviesRawJSON, arrayMovieType)
recyclerView.adapter = FlixsterRecyclerViewAdapter(models, this@FlixsterFragment)
// Look for this in Logcat:
Log.d("FlixsterFragment", "response successful")
}
/*
* The onFailure function gets called when
* HTTP response status is "4XX" (eg. 401, 403, 404)
*/
override fun onFailure(
statusCode: Int,
headers: Headers?,
errorResponse: String,
t: Throwable?
) {
// The wait for a response is over
progressBar.hide()
// If the error is not null, log it!
t?.message?.let {
Log.e("FlixsterFragment", errorResponse)
}
}
}]
}
}
| 0 | Kotlin | 0 | 0 | 29424ad273351b9181942de0dec19699550f9d0b | 4,149 | Project_03_Flixster_Part_01 | Apache License 2.0 |
09-Android/app/src/main/java/com/saehyun/a09_android/viewModel/auth/ReissueViewModel.kt | 09-Project | 400,092,415 | false | null | package com.saehyun.a09_android.viewModel.auth
import android.content.Context
import android.content.Intent
import android.os.Handler
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.saehyun.a09_android.model.response.AuthReissueResponse
import com.saehyun.a09_android.repository.Repository
import com.saehyun.a09_android.ui.activity.LoginActivity
import com.saehyun.a09_android.util.ACCESS_TOKEN
import com.saehyun.a09_android.util.REFRESH_TOKEN
import com.saehyun.a09_android.util.ToastUtil
import kotlinx.coroutines.launch
import retrofit2.Response
class ReissueViewModel(private val repository: Repository, private val context: Context) : ViewModel() {
val authReissueResponse : MutableLiveData<Response<AuthReissueResponse>> = MutableLiveData()
fun authReissue(refreshToken: String) {
viewModelScope.launch {
val response = repository.authReissue(refreshToken)
authReissueResponse.value = response
if (response.isSuccessful) {
REFRESH_TOKEN = response.body()?.refreshToken.toString()
ACCESS_TOKEN = response.body()?.accessToken.toString()
} else {
when (response.code()) {
401 -> {
ToastUtil.print(context, "토큰이 만료되어 로그아웃 되었습니다.")
Handler().postDelayed({
val intent = Intent(context, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
ACCESS_TOKEN = "default"
REFRESH_TOKEN = "default"
context.startActivity(intent)
}, 2000L)
}
404 -> ToastUtil.print(context, "예기치 못한 오류가 발생했습니다.\n고객센터에 문의해주세요.")
}
}
}
}
} | 0 | Kotlin | 1 | 3 | 58ba1108eb54eee94fb9c52b64341e2b03903507 | 1,946 | 09-Android | MIT License |
buildSrc/src/main/kotlin/Versions.kt | mbobiosio | 324,425,383 | false | null | object Versions {
object Android {
const val BUILD_TOOLS = "30.0.3"
const val COMPILE_SDK = 30
object DefaultConfig {
const val APPLICATION_ID = "com.cerminnovations.moviesboard"
const val MIN_ANDROID_SDK = 21
const val TARGET_ANDROID_SDK = 30
const val VERSION_CODE = 1
const val VERSION_NAME = "1.0"
const val TEST_INSTRUMENTATION_RUNNER = "androidx.test.runner.AndroidJUnitRunner"
}
object BuildTypes {
const val DEBUG = "debug"
const val RELEASE = "release"
}
}
object Gradle {
const val FIREBASE_CRASHLYTICS = "2.4.1"
const val GRADLE_VERSION = "4.2.2"
const val KOTLIN = "1.4.32"
const val MAVEN_PLUGIN = "2.1"
const val GOOGLE_SERVICES = "4.3.8"
const val REMAL_PLUGIN = "1.1.5"
}
object Kotlin {
const val JDK = Gradle.KOTLIN
}
object Google {
object Androidx {
const val APP_COMPAT = "1.2.0"
const val CONSTRAINT_LAYOUT = "2.0.4"
const val CORE_KTX = "1.3.2"
const val CORE_TESTING = "2.1.0"
const val ESPRESSO = "3.3.0"
const val JUNIT_EXT = "1.1.2"
const val LIFECYCLE = "2.2.0"
const val RECYCLERVIEW = "1.2.0-alpha04"
const val TEST_RULES = "1.3.0"
const val TEST_RUNNER = "1.2.0"
const val ROOM = "2.2.5"
const val WORK_MANAGER = "2.4.0"
const val NAV_KTX = "2.3.2"
const val PAGING = "3.0.0-alpha07"
const val MULTI_DEX = "2.0.1"
}
object Firebase {
const val ANALYTICS = "18.0.0"
const val CRASHLYTICS = "17.3.0"
}
object Material {
const val DESIGN = "1.2.0"
}
object Test {
const val TRUTH = "1.1"
}
}
object Square {
const val OK_HTTP = "4.9.0"
const val RETROFIT = "2.9.0"
const val RETROFIT_CONVERTER_MOSHI = "2.9.0"
const val RETROFIT_ADAPTER = "2.9.0"
const val MOSHI = "1.11.0"
}
object RxJava {
const val RX_JAVA = "2.1.1"
}
object Glide {
const val GLIDE_LIB = "4.10.0"
}
object Coroutines {
const val CORE = "1.4.2"
const val ANDROID = "1.4.2"
}
object Test {
const val COROUTINES = "1.4.2"
const val JUNIT = "4.13.1"
const val MOCKITO_KOTLIN = "2.2.0"
const val MOCK = "1.10.2"
}
object Detekt {
const val DETEKT_LIB = "1.14.2"
const val DETEKT_FORMATTING = "1.12.0"
}
object Others {
const val TIMBER = "4.7.1"
const val INTUIT = "1.0.6"
const val LIFECYCLE_CONNECTIVITY = "1.0.1"
const val LOADING_INDICATOR = "2.1.3"
const val POWER_SPINNER = "1.1.7"
const val YOUTUBE_PLAYER = "10.0.5"
const val LOADING_OVERLAY = "1.0.0"
}
} | 0 | null | 3 | 7 | 07270aa17f45edabfb6792fd529c212e1c585ce4 | 3,028 | MoviesBoard | MIT License |
app/src/main/java/com/pieterbommele/dunkbuzz/model/Match.kt | piebom | 736,048,297 | false | {"Kotlin": 119324} | package com.pieterbommele.dunkbuzz.model
/**
* Represents a basketball match with details about the teams involved and the match's specifics.
*
* @property id The unique identifier for the match.
* @property date The date when the match is scheduled to occur.
* @property homeTeam An instance of [Team] representing the home team.
* @property homeTeamScore The score achieved by the home team. This may be final or current, depending on the match status.
* @property period The period or stage of the match (e.g., quarter, half, etc.).
* @property postseason Indicates whether the match is part of the postseason (playoffs).
* @property season The season year the match is part of.
* @property status The current status of the match (e.g., scheduled, in progress, completed).
* @property time The scheduled start time for the match.
* @property visitorTeam An instance of [Team] representing the visiting team.
* @property visitorTeamScore The score achieved by the visiting team. This may be final or current, depending on the match status.
*/
data class Match(
val id: Int,
val date: String,
val homeTeam: Team,
val homeTeamScore: Int,
val period: Int,
val postseason: Boolean,
val season: Int,
val status: String,
val time: String,
val visitorTeam: Team,
val visitorTeamScore: Int
)
| 0 | Kotlin | 0 | 0 | ca19c01340a3fa11f079aa92fff776601adffb84 | 1,345 | DunkBuzz | MIT License |
app/src/main/java/com/aliernfrog/pftool/ui/screen/PermissionsScreen.kt | aliernfrog | 491,592,330 | false | {"Kotlin": 215219} | package com.aliernfrog.lactool.ui.screen
import android.net.Uri
import android.os.Environment
import android.provider.DocumentsContract
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.aliernfrog.lactool.R
import com.aliernfrog.lactool.data.PermissionData
import com.aliernfrog.lactool.filesAppMightBlockAndroidData
import com.aliernfrog.lactool.ui.component.AppScaffold
import com.aliernfrog.lactool.ui.component.CardWithActions
import com.aliernfrog.lactool.ui.component.FilesDowngradeNotice
import com.aliernfrog.lactool.ui.dialog.ChooseFolderIntroDialog
import com.aliernfrog.lactool.ui.dialog.NotRecommendedFolderDialog
import com.aliernfrog.lactool.util.extension.appHasPermissions
import com.aliernfrog.lactool.util.extension.resolvePath
import com.aliernfrog.lactool.util.extension.takePersistablePermissions
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PermissionsScreen(
vararg permissionsData: PermissionData,
content: @Composable () -> Unit
) {
val context = LocalContext.current
fun getMissingPermissions(): List<PermissionData> {
return permissionsData.filter {
!Uri.parse(it.getUri()).appHasPermissions(context)
}
}
var missingPermissions by remember { mutableStateOf(
getMissingPermissions()
) }
Crossfade(targetState = missingPermissions.isEmpty()) { hasPermissions ->
if (hasPermissions) content()
else AppScaffold(
title = stringResource(R.string.permissions)
) {
PermissionsList(
missingPermissions = missingPermissions,
onUpdateState = {
missingPermissions = getMissingPermissions()
}
)
}
}
}
@Composable
private fun PermissionsList(
missingPermissions: List<PermissionData>,
onUpdateState: () -> Unit
) {
val context = LocalContext.current
var activePermissionData by remember { mutableStateOf<PermissionData?>(null) }
var unrecommendedPathWarningUri by remember { mutableStateOf<Uri?>(null) }
val showFilesAppWarning = filesAppMightBlockAndroidData && missingPermissions.any {
it.recommendedPath?.startsWith("${Environment.getExternalStorageDirectory()}/Android/data") == true
}
fun takePersistableUriPermissions(uri: Uri) {
uri.takePersistablePermissions(context)
activePermissionData?.onUriUpdate?.invoke(uri)
onUpdateState()
}
val uriPermsLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.OpenDocumentTree(), onResult = {
if (it == null) return@rememberLauncherForActivityResult
val recommendedPath = activePermissionData?.recommendedPath
if (recommendedPath != null) {
val resolvedPath = it.resolvePath()
val isRecommendedPath = resolvedPath.equals(recommendedPath, ignoreCase = true)
if (!isRecommendedPath) unrecommendedPathWarningUri = it
else takePersistableUriPermissions(it)
} else {
takePersistableUriPermissions(it)
}
})
fun openFolderPicker(permissionData: PermissionData) {
val starterUri = if (permissionData.recommendedPath != null) DocumentsContract.buildDocumentUri(
"com.android.externalstorage.documents",
"primary:"+permissionData.recommendedPath.removePrefix("${Environment.getExternalStorageDirectory()}/")
) else null
uriPermsLauncher.launch(starterUri)
activePermissionData = permissionData
}
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
if (showFilesAppWarning) item {
FilesDowngradeNotice(
Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
)
}
items(missingPermissions) { permissionData ->
var introDialogShown by remember { mutableStateOf(false) }
if (introDialogShown) ChooseFolderIntroDialog(
permissionData = permissionData,
onDismissRequest = { introDialogShown = false },
onConfirm = {
openFolderPicker(permissionData)
introDialogShown = false
}
)
CardWithActions(
title = stringResource(permissionData.titleId),
buttons = {
Button(
onClick = {
if (permissionData.recommendedPath != null && permissionData.recommendedPathDescriptionId != null)
introDialogShown = true
else openFolderPicker(permissionData)
}
) {
Text(stringResource(R.string.permissions_chooseFolder))
}
},
content = permissionData.content,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
)
}
}
unrecommendedPathWarningUri?.let { uri ->
NotRecommendedFolderDialog(
permissionData = activePermissionData!!,
onDismissRequest = { unrecommendedPathWarningUri = null },
onUseUnrecommendedFolderRequest = {
takePersistableUriPermissions(uri)
unrecommendedPathWarningUri = null
},
onChooseFolderRequest = {
activePermissionData?.let { openFolderPicker(it) }
unrecommendedPathWarningUri = null
}
)
}
} | 4 | Kotlin | 0 | 3 | 494f30f4718a52836cbba1b7c183296a2e545f62 | 6,169 | pf-tool | MIT License |
sha512/src/commonTest/kotlin/org/komputing/khash/sha512/Sha512Tests.kt | komputing | 97,332,286 | false | {"Kotlin": 755449} | package org.komputing.khash.sha512
import org.komputing.khex.extensions.toNoPrefixHexString
import kotlin.test.Test
import kotlin.test.assertEquals
class Sha512Tests {
@Test
fun testDigest1() {
testHash(
"".encodeToByteArray(),
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
)
}
@Test
fun testDigest2() {
testHash(
"Hello world!".encodeToByteArray(),
"f6cde2a0f819314cdde55fc227d8d7dae3d28cc556222a0a8ad66d91ccad4aad6094f517a2182360c9aacf6a3dc323162cb6fd8cdffedb0fe038f55e85ffb5b6"
)
}
@Test
fun testDigest3() {
val loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Proin pulvinar turpis purus, sit amet dapibus magna commodo quis metus."
testHash(
loremIpsum.encodeToByteArray(),
"de94877cc9711605dcdc09d85bd3080f74398d5e1ad8f0dcd1726c54ac93f2b4b781c3f56de1fbc725ac261a2c09d1d5bb24d0afa7449e4ffe4b2a7e6d09f40d"
)
}
private fun testHash(input: ByteArray, expected: String) {
assertEquals(expected, Sha512.digest(input).toNoPrefixHexString())
}
@Test
fun testHashRawBytes() {
val b = ByteArray(256)
for (i in b.indices) {
b[i] = i.toByte()
}
testHash(
b,
"1e7b80bc8edc552c8feeb2780e111477e5bc70465fac1a77b29b35980c3f0ce4a036a6c9462036824bd56801e62af7e9feba5c22ed8a5af877bf7de117dcac6d"
)
}
}
| 7 | Kotlin | 13 | 50 | 6bf79393e1ed4d1ef1f4e0790fe874824ca33b79 | 1,592 | KHash | MIT License |
device/src/main/java/org/watsi/device/managers/SessionManagerImpl.kt | Meso-Health | 227,514,539 | false | {"Gradle": 7, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 4, "Markdown": 1, "Proguard": 2, "JSON": 25, "Kotlin": 419, "YAML": 3, "XML": 153, "Java": 1} | package org.watsi.device.managers
import io.reactivex.Completable
import okhttp3.Credentials
import org.watsi.device.api.CoverageApi
import org.watsi.device.managers.SessionManager.Companion.ALLOWED_HEALTH_CENTER_ROLES
import org.watsi.device.managers.SessionManager.Companion.ALLOWED_HOSPITAL_ROLES
import org.watsi.domain.entities.AuthenticationToken
import org.watsi.domain.entities.User
class SessionManagerImpl(
private val preferencesManager: PreferencesManager,
private val api: CoverageApi,
private val logger: Logger
) : SessionManager {
private var token: AuthenticationToken? = preferencesManager.getAuthenticationToken()
override fun login(username: String, password: String): Completable {
return Completable.fromAction {
val apiAuthorizationHeader = Credentials.basic(username, password)
val newTokenApi = api.login(apiAuthorizationHeader).blockingGet()
if (!isUserAllowed(newTokenApi.user.toUser())) {
throw SessionManager.PermissionException()
}
val newToken = newTokenApi.toAuthenticationToken()
preferencesManager.setAuthenticationToken(newToken)
logger.setUser(newToken.user)
token = newToken
}
}
override fun logout() {
preferencesManager.setPreviousUser(token?.user)
preferencesManager.setAuthenticationToken(null)
logger.clearUser()
token = null
}
override fun isUserAllowed(user: User): Boolean {
return if (user.isHospitalUser()) {
ALLOWED_HOSPITAL_ROLES.contains(user.role)
} else {
ALLOWED_HEALTH_CENTER_ROLES.contains(user.role)
}
}
override fun shouldClearUserData(): Boolean {
val previousUser = preferencesManager.getPreviousUser()
val currentUser = token?.user
return previousUser != null && currentUser != null && previousUser != currentUser && previousUser.providerId != currentUser.providerId
}
override fun shouldClearPageKey(currentMemberCount: Int): Boolean {
val previousMemberCount = preferencesManager.getMembersCountForCurrentPageKey()
return previousMemberCount != 0 && previousMemberCount > currentMemberCount
}
override fun currentAuthenticationToken(): AuthenticationToken? = token
override fun currentUser(): User? = currentAuthenticationToken()?.user
override fun userHasPermission(permission: SessionManager.Permissions): Boolean {
return currentUser()?.let { user ->
if (isUserAllowed(user)) {
if (user.isHospitalUser()) {
SessionManager.HOSPITAL_ROLE_PERMISSIONS.contains(permission)
} else {
SessionManager.HEALTH_CENTER_ROLE_PERMISSIONS.contains(permission)
}
} else {
false
}
} ?: false
}
}
| 2 | Kotlin | 3 | 6 | 6e1da182073088f28230fe60a2e09d6f38aab957 | 2,935 | meso-clinic | Apache License 2.0 |
components/core/test/src/commonMain/kotlin/com/flipperdevices/core/test/DecomposeViewModelCoroutineScopeProviderKtx.kt | flipperdevices | 288,258,832 | false | {"Kotlin": 4167715, "FreeMarker": 10352, "CMake": 1780, "C++": 1152, "Fluent": 21} | package com.flipperdevices.core.test
import com.flipperdevices.core.ui.lifecycle.DecomposeViewModelCoroutineScopeProvider
import io.mockk.every
import io.mockk.mockkObject
import kotlinx.coroutines.CoroutineScope
fun DecomposeViewModelCoroutineScopeProvider.mockScope(scope: CoroutineScope) {
mockkObject(DecomposeViewModelCoroutineScopeProvider) {
every {
provideCoroutineScope(any(), any())
} returns scope
}
}
| 21 | Kotlin | 174 | 1,528 | 8f293e596741a6c97409acbc8de10c7ae6e8d8b0 | 451 | Flipper-Android-App | MIT License |
yorumluyorum/app/src/main/java/com/gorkemozcan/yorumluyorum/model/UserModel.kt | Gorkzcan | 596,579,666 | false | null | package com.gorkemozcan.yorumluyorum.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class UserModel (
var uid: String? =null,
var fullname : String? = null,
var userName: String? =null,
var bio :String?=null,
var photoURL :String?=null,
var following :ArrayList<String>? = arrayListOf(),
var followers: ArrayList<String>?= arrayListOf()
): Parcelable | 0 | Kotlin | 0 | 0 | 8a5337a9ad0ddedde7eafc9167f0674f32a5db39 | 424 | Yorumluyorum-SocialMediaApp-Kotlin | MIT License |
ChatCloak/app/src/main/java/be/senne/chatcloak/screen/EstablishConnectionScreen.kt | SenneS | 572,484,903 | false | null | package be.senne.chatcloak.screen
import android.content.Context
import android.net.wifi.WifiManager
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import be.senne.chatcloak.KeyContainer
import be.senne.chatcloak.compose.navigation
import be.senne.chatcloak.viewmodel.EstablishConnectionVM
import java.net.InetAddress
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.*
//accetabele limitaties voor mij.
private fun checkifValidIp(ip : String) : Boolean {
val split = ip.split(".")
if(split.size != 4) { return false }
for(chunk in split) {
val alsNummer = chunk.toIntOrNull()
if(alsNummer == null || alsNummer < 0 || alsNummer > 255) { return false }
}
return true
}
@Composable
fun createEstablishConnectionScreen(nav: NavController, key_container : KeyContainer, vm : EstablishConnectionVM = viewModel()) {
vm.key_container = key_container
val openAlert = remember { mutableStateOf(false) }
val nextEnabled = remember { mutableStateOf(false) }
if(openAlert.value) {
AlertDialog(
title = {Text("Connection Type")},
text = { Text(text = "Select whether you want to be the host of the conversation or the client (whatever you pick should be the opposite of what your friend picked/picks")},
onDismissRequest = {
openAlert.value = false
},
confirmButton = {
Button(onClick = {
val kc = vm.key_container
val ip = vm.ip
val is_host = true
nav.navigate("chat_screen/$kc/$ip/$is_host")
}) {
Text(text = "Host")
}
}, dismissButton = {
Button(onClick = {
val kc = vm.key_container
val ip = vm.ip
val is_host = false
nav.navigate("chat_screen/$kc/$ip/$is_host")
}) {
Text(text = "Client")
}
})
}
Scaffold(topBar = {
TopAppBar(title = {
Row(verticalAlignment = Alignment.CenterVertically) {
Text("Establish Connection")
Spacer(Modifier.weight(1f))
Button(onClick = {
openAlert.value = true
}, enabled = nextEnabled.value) {
Text("Next")
}
}
})
}, content = { padding ->
Column(modifier = Modifier
.padding(padding)
.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) {
var text by remember { mutableStateOf(TextFieldValue("")) }
TextField(
value = text,
onValueChange = { tfv ->
text = tfv
if(checkifValidIp(tfv.text)) {
nextEnabled.value = true
vm.ip = tfv.text
}else {
nextEnabled.value = false
}
},
label = { Text(text = "Your friend's IP address") },
placeholder = { Text(text = "192.168.1.12") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(5.dp))
val context: Context = LocalContext.current
val manager: WifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
val ip: String = InetAddress.getByAddress(
ByteBuffer
.allocate(Integer.BYTES)
.order(ByteOrder.LITTLE_ENDIAN)
.putInt(manager.connectionInfo.ipAddress)
.array()
).hostAddress as String
var myIpText by remember { mutableStateOf(TextFieldValue(ip)) }
TextField(
value = myIpText,
enabled = false,
onValueChange = {},
label = { Text(text = "Your IP address: ") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
modifier = Modifier.fillMaxWidth()
)
}
})
} | 0 | Kotlin | 0 | 0 | 6ebedc417048e4a1d6d36c6ae156340d6066ff16 | 5,072 | ChatCloak | Apache License 2.0 |
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/opengl/GlMediaData.kt | chromeos | 419,334,870 | false | null | /*
* Copyright (c) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 dev.chromeos.videocompositionsample.presentation.opengl
import dev.chromeos.videocompositionsample.presentation.media.MediaTrack
data class GlMediaData(
val mediaTrackList: List<MediaTrack>,
val textures: IntArray
) | 0 | Kotlin | 2 | 7 | 7a91156a14bd4a735a9bcaa42b8e09c1ad92e08f | 842 | video-composition-sample | Apache License 2.0 |
fashion_week/android/app/src/main/kotlin/com/example/fashion_week/MainActivity.kt | ufukhawk | 405,360,089 | false | null | package com.example.fashion_week
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 12 | 32 | b7f5a778a4bbad4bdc9c4b962d526b7d85c2631f | 129 | flutter_fashion_week | MIT License |
libs/usb/src/commonMain/kotlin/kosh/libs/usb/UsbConfig.kt | niallkh | 855,100,709 | false | {"Kotlin": 1920679, "Swift": 25684} | package kosh.libs.usb
data class UsbConfig(
val vendorIds: List<Int>,
val productIds: List<Int>,
val usbInterfaceNumber: Int,
val packetSize: Int,
)
| 0 | Kotlin | 0 | 3 | 1581392a0bdf9f075941125373b8d1bed937ab43 | 166 | kosh | MIT License |
lcc-data/src/main/kotlin/com/joshmanisdabomb/lcc/data/factory/asset/block/RotationBlockAssetFactory.kt | joshmanisdabomb | 537,458,013 | false | {"Kotlin": 2724329, "Java": 138822} | package com.joshmanisdabomb.lcc.data.factory.asset.block
import com.joshmanisdabomb.lcc.data.DataAccessor
import com.joshmanisdabomb.lcc.data.factory.asset.ModelProvider
import net.minecraft.block.Block
import net.minecraft.data.client.BlockStateVariant
import net.minecraft.data.client.VariantSettings
import net.minecraft.data.client.VariantsBlockStateSupplier
open class RotationBlockAssetFactory(val x: List<Int> = listOf(0), val y: List<Int> = (0..3).toList(), val model: ModelProvider.ModelFactory<Block> = ModelProvider.block.cubeAll()) : BlockAssetFactory {
override fun apply(data: DataAccessor, entry: Block) {
val variants = mutableListOf<BlockStateVariant>()
val model = model.create(data, entry)
for (i in x) {
for (j in y) {
variants.add(BlockStateVariant.create().put(VariantSettings.MODEL, model).put(VariantSettings.X, VariantSettings.Rotation.values()[i]).put(VariantSettings.Y, VariantSettings.Rotation.values()[j]))
}
}
stateVariant(data, entry, { VariantsBlockStateSupplier.create(it, *variants.toTypedArray()) }) {}
}
companion object : RotationBlockAssetFactory()
} | 0 | Kotlin | 0 | 0 | a836162eaf64a75ca97daffa02c1f9e66bdde1b4 | 1,185 | loosely-connected-concepts | Creative Commons Zero v1.0 Universal |
buildSrc/src/main/kotlin/BuildHelpers.kt | codepunk | 778,937,591 | false | {"Kotlin": 80039} | import com.android.build.gradle.api.ApplicationVariant
import java.util.Properties
import org.gradle.api.Project
/**
* Version 1 of keys/intents/etc. logic:
* https://github.com/codepunk/codepunk-legacy-android-app-core-codepunk/blob/master/app/build.gradle
*
* Version 2 of keys/intents/etc. logic:
* https://github.com/codepunk/codepunk-android-app-core-2021/blob/main/app/helpers.gradle
*/
fun ApplicationVariant.makeKeys() {
// TODO Make some useful methods here (see comments above)
println("**************************************************")
println(" Yerrrrrr: variant=${this.name}")
println("**************************************************")
}
fun ApplicationVariant.extractLocalProperty(
project: Project,
name: String,
defaultValue: String = "[$name is missing from local.properties]",
type: String = "String",
formatValue: (String) -> String = { "\"$it\"" }
) {
val properties = Properties()
properties.load(project.file("local.properties").inputStream())
val propertyValue = properties.getProperty(name) ?: defaultValue
println("**************************************************")
println(" Yerrrrrr: variant=${this.name}, propertyValue=$propertyValue")
println("**************************************************")
buildConfigField(type, name, formatValue(propertyValue))
} | 0 | Kotlin | 0 | 0 | d71d9b50d287005a715c382c6e79b5ca235876ef | 1,369 | codepunk-android-app-core-2024-03 | Apache License 2.0 |
src/main/kotlin/com/github/creeper123123321/viaaas/command/sub/ConnectionsSubCommand.kt | Camotoy | 340,811,792 | true | {"Kotlin": 108622, "JavaScript": 18139, "HTML": 6912, "CSS": 35} | package com.github.creeper123123321.viaaas.command.sub
import com.github.creeper123123321.viaaas.handler.MinecraftHandler
import us.myles.ViaVersion.api.Via
import us.myles.ViaVersion.api.command.ViaCommandSender
import us.myles.ViaVersion.api.command.ViaSubCommand
import us.myles.ViaVersion.api.protocol.ProtocolVersion
object ConnectionsSubCommand : ViaSubCommand() {
override fun name(): String = "connections"
override fun description(): String = "Lists VIAaaS connections"
override fun execute(p0: ViaCommandSender, p1: Array<out String>): Boolean {
p0.sendMessage("List of player connections: ")
Via.getPlatform().connectionManager.connections.forEach {
val backAddr = it.channel?.remoteAddress()
val pVer = it.protocolInfo?.protocolVersion?.let {
ProtocolVersion.getProtocol(it)
}
val backName = it.protocolInfo?.username
val backVer = it.protocolInfo?.serverProtocolVersion?.let {
ProtocolVersion.getProtocol(it)
}
val pAddr =
it.channel?.pipeline()?.get(MinecraftHandler::class.java)?.other?.remoteAddress()
p0.sendMessage("$pAddr $pVer -> $backVer ($backName) $backAddr")
}
return true
}
} | 0 | null | 0 | 0 | 738997f12a01e2cf3a4d408e627896571b08850b | 1,294 | VIAaaS | MIT License |
app/src/main/java/com/amit/ui/BottomAppBarItemView.kt | amitjangid80 | 129,866,990 | false | null | package com.amit.ui
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.animation.TranslateAnimation
import android.widget.FrameLayout
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.Animation
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import com.amit.dbapilibrary.R
/**
* Created by <NAME> on 12/03/2019.
**/
class BottomAppBarItemView @JvmOverloads constructor(context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0) :
FrameLayout(context, attrs, defStyleAttr)
{
private val layoutView = LayoutInflater.from(context).inflate(R.layout.bottom_app_bar_layout, this, true)
private val textView = layoutView.findViewById<AppCompatTextView>(R.id.textView)
private val imageView = layoutView.findViewById<AppCompatImageView>(R.id.imageView)
private val layoutImageView = layoutView.findViewById<FrameLayout>(R.id.layoutImageView)
private var translateUpAnimation: TranslateAnimation? = null
private var translateDownAnimation: TranslateAnimation?= null
private lateinit var bottomAppBarItemConfig: BottomAppBarItemConfig
init
{
setOnClickListener {
if (bottomAppBarItemConfig.selected)
{
return@setOnClickListener
}
select()
bottomAppBarItemConfig.selected = true
}
}
fun setItemConfig(bottomAppBarItemConfig: BottomAppBarItemConfig)
{
this.bottomAppBarItemConfig = bottomAppBarItemConfig
textView.text = bottomAppBarItemConfig.text
imageView.setImageDrawable(bottomAppBarItemConfig.drawable)
layoutImageView.visibility = if (bottomAppBarItemConfig.selected) View.VISIBLE else View.INVISIBLE
}
fun setTabColor(tabColor: Int)
{
layoutImageView.setBackgroundColor(tabColor)
}
fun setTextSize(textSize: Float)
{
textView.textSize = textSize
}
fun setTextColor(textColor: Int)
{
textView.setTextColor(textColor)
}
fun getItemIndex(): Int = bottomAppBarItemConfig.index
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int)
{
super.onSizeChanged(w, h, oldw, oldh)
initializeAnimations()
}
fun select()
{
layoutImageView.startAnimation(translateUpAnimation)
}
fun deselect()
{
layoutImageView.startAnimation(translateDownAnimation)
}
private fun initializeAnimations()
{
translateUpAnimation = TranslateAnimation(0f, 0f, height.toFloat(), 0f).apply {
duration = ANIMATION_DURATION
interpolator = AccelerateDecelerateInterpolator()
setAnimationListener(object : Animation.AnimationListener
{
override fun onAnimationRepeat(animation: Animation?)
{
}
override fun onAnimationEnd(animation: Animation?)
{
}
override fun onAnimationStart(animation: Animation?)
{
layoutImageView.visibility = View.VISIBLE
}
})
}
translateDownAnimation = TranslateAnimation(0f, 0f, 0f, height.toFloat()).apply {
duration = ANIMATION_DURATION
interpolator = AccelerateDecelerateInterpolator()
setAnimationListener(object : Animation.AnimationListener
{
override fun onAnimationRepeat(animation: Animation?)
{
}
override fun onAnimationEnd(animation: Animation?)
{
layoutImageView.visibility = View.INVISIBLE
}
override fun onAnimationStart(animation: Animation?)
{
}
})
}
}
companion object
{
private const val ANIMATION_DURATION = 300L
}
}
| 1 | null | 1 | 2 | cec5e4f8c337ed07e8ca9b33a6b2c0ee196c4066 | 4,192 | DBApiLib | Apache License 2.0 |
src/main/kotlin/edu/kit/compiler/backend/MolkiAssembler.kt | compilerpraktikum | 418,499,542 | false | {"Kotlin": 669262, "Dockerfile": 817, "Shell": 718, "C": 306} | package edu.kit.compiler.backend
import edu.kit.compiler.CompilationException
import edu.kit.compiler.utils.Logger
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import kotlin.io.path.absolutePathString
object MolkiAssembler {
fun assemble(molkiFile: Path, assemblyFile: Path) {
val processBuilder = ProcessBuilder(
"molki.py",
"-o", assemblyFile.absolutePathString(),
"assemble",
molkiFile.absolutePathString()
).inheritIO()
Logger.debug { "Generating assembly file using molki ..." }
try {
val process = processBuilder.start()
val exitCode = process.waitFor()
if (exitCode != 0) {
throw CompilationException("molki returned non-zero exit code $exitCode $molkiFile")
}
val actualAssemblyFile = assemblyFile.absolutePathString() + ".s"
Files.move(Path.of(actualAssemblyFile), assemblyFile, StandardCopyOption.REPLACE_EXISTING)
} catch (e: IOException) {
throw CompilationException("failed generate assembly file: ${e.message}. Is molki.py not in \$PATH?")
}
}
}
| 4 | Kotlin | 1 | 3 | adac6790a5c43a7748d82c8be2284b871c898aea | 1,242 | compiler | MIT License |
app/src/test/java/com/dicodingjetpackpro/moviecatalogue/presentation/ListUpdateCallback.kt | aydbtiko24 | 373,626,629 | false | null | package com.dicodingjetpackpro.moviecatalogue.presentation
import androidx.recyclerview.widget.ListUpdateCallback
val testListUpdateCallback = object : ListUpdateCallback {
override fun onInserted(position: Int, count: Int) {}
override fun onRemoved(position: Int, count: Int) {}
override fun onMoved(fromPosition: Int, toPosition: Int) {}
override fun onChanged(position: Int, count: Int, payload: Any?) {}
}
| 0 | Kotlin | 1 | 5 | e8d05a9e17782d39fad02f2f4a327b1003c2066e | 428 | movie-catalogue | Apache License 2.0 |
src/main/kotlin/ru/ereshkin_a_v/deanerybackend/rating/repository/RatingListElementRepository.kt | AlexEreh | 793,810,424 | false | {"Kotlin": 55276} | package ru.ereshkin_a_v.deanerybackend.rating.repository
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import ru.ereshkin_a_v.deanerybackend.rating.entities.RatingListElement
@Repository
interface RatingListElementRepository : JpaRepository<RatingListElement, Long> {
fun findAllByRatingListId(id: Long): MutableSet<RatingListElement>
} | 0 | Kotlin | 0 | 0 | d4e4dcb831d3c9653caa90725a85ba406deae32d | 406 | deanery-backend | Do What The F*ck You Want To Public License |
client/src/androidMain/kotlin/main.kt | VANTAGAMES | 665,892,334 | false | {"Kotlin": 77540, "Shell": 1210, "Dockerfile": 444} | import metron.*
import korlibs.io.file.std.resourcesVfs
import korlibs.io.lang.readProperties
import korlibs.render.*
import korlibs.io.net.*
class Main
suspend fun runMain() {
main()
}
suspend fun main() {
val clientProps = resourcesVfs["client.properties"].readProperties()
currentUrl = clientProps["server"]!!
version = clientProps["version"]!!
redirector = { korlibs.korge.view.views().gameWindow.browse(URL(it)) }
startMain()
}
| 9 | Kotlin | 0 | 3 | 2139f44a680b9229f89100ecdddcac027519d637 | 458 | metronKt | MIT License |
aula13/app/src/main/java/br/edu/ifb/android/MainActivity.kt | JeronimoHermano | 279,355,548 | false | null | package br.edu.ifb.android
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
class MainActivity : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.btAula).setOnClickListener(this)
findViewById<Button>(R.id.btBusca).setOnClickListener(this)
findViewById<Button>(R.id.btMapa).setOnClickListener(this)
findViewById<Button>(R.id.btPin).setOnClickListener(this)
}
override fun onClick(p0: View?) {
var i : Intent? = when(p0!!.id){
R.id.btAula -> Intent(this, AulaMapsActivity::class.java)
R.id.btBusca -> Intent(this, SearchMapsActivity::class.java)
R.id.btMapa -> Intent(this, MapsActivity::class.java)
R.id.btPin -> Intent(this, MarkerMapsActivity::class.java)
else -> null
}
if(i != null){
startActivity(i)
// finish()
}
}
}
| 0 | Kotlin | 0 | 0 | 893011459c1a9d1e6be9eb8551eb55d43929a8c1 | 1,162 | ifb-android | MIT License |
aula13/app/src/main/java/br/edu/ifb/android/MainActivity.kt | JeronimoHermano | 279,355,548 | false | null | package br.edu.ifb.android
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
class MainActivity : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.btAula).setOnClickListener(this)
findViewById<Button>(R.id.btBusca).setOnClickListener(this)
findViewById<Button>(R.id.btMapa).setOnClickListener(this)
findViewById<Button>(R.id.btPin).setOnClickListener(this)
}
override fun onClick(p0: View?) {
var i : Intent? = when(p0!!.id){
R.id.btAula -> Intent(this, AulaMapsActivity::class.java)
R.id.btBusca -> Intent(this, SearchMapsActivity::class.java)
R.id.btMapa -> Intent(this, MapsActivity::class.java)
R.id.btPin -> Intent(this, MarkerMapsActivity::class.java)
else -> null
}
if(i != null){
startActivity(i)
// finish()
}
}
}
| 0 | Kotlin | 0 | 0 | 893011459c1a9d1e6be9eb8551eb55d43929a8c1 | 1,162 | ifb-android | MIT License |
app/src/main/java/io/cricket/app/model/Response/UserResponse.kt | amirishaque | 375,128,729 | false | null | package io.cricket.app.model.Response
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import io.cricket.app.model.BaseModel
import kotlinx.android.parcel.Parcelize
data class UserResponse(
@SerializedName("Data")
val user: User,
@SerializedName("message")
val responseMessage: String,
@SerializedName("teamObject")
val team: TeamObject
) : BaseModel {
@Parcelize
class User(
@SerializedName("access_token") val accessToken: String,
@SerializedName("phone_privacy") val phonePrivacy: Int,
@SerializedName("address") val address: String,
@SerializedName("city") val city: String,
@SerializedName("confirmation_code") val confirmationCode: String,
@SerializedName("created_at") val createdAt: String,
@SerializedName("Description") val description: String,
@SerializedName("dob") val dob: String,
@SerializedName("email") val email: String,
@SerializedName("firsttime") val firsttime: Int,
@SerializedName("image") val image: String,
@SerializedName("name") val name: String,
@SerializedName("newphone") val newphone: String,
@SerializedName("password") val password: String,
@SerializedName("phone") val phone: String,
@SerializedName("playerAs") val playerAs: Int,
@SerializedName("playerID") val playerID: Int,
@SerializedName("shirtNo") val shirtNo: String,
@SerializedName("status") val status: Int,
@SerializedName("teamId") val teamId: Int?,
@SerializedName("teamStatus") val teamStatus: Int,
@SerializedName("uniqueId") val uniqueId: String,
@SerializedName("token") val token: String,
@SerializedName("player_for") val playerFor: String?
) : BaseModel, Parcelable
data class TeamObject(
@SerializedName("city")
val city: String,
@SerializedName("created_at")
val createdAt: String,
@SerializedName("logo")
val logo: String,
@SerializedName("name")
val name: String,
@SerializedName("profileImage")
val profileImage: String,
@SerializedName("teamID")
val teamID: Int,
@SerializedName("teamUnique")
val teamUnique: String
) : BaseModel
data class UpdateTokenResponse(
@SerializedName("status")
val status: String,
@SerializedName("message")
val message: String
) : BaseModel
data class HttpResponse(
@SerializedName("Data")
val `data`: Data,
@SerializedName("message")
val message: String,
@SerializedName("status")
val status: String
) : BaseModel
class Data(
)
}
| 0 | Kotlin | 0 | 0 | 42808ddd775b5ac6f7bff0d8cf518091588df844 | 2,759 | Cricklub_livecode | MIT License |
server/jvm/genesis-site-specific/src/main/resources/cfg/genesis-system-definition.kts | genesiscommunitysuccess | 537,375,508 | false | null | package genesis.cfg
systemDefinition {
global {
item(name = "DEPLOYED_PRODUCT", value = "{{appName}}")
item(name = "MqLayer", value = "ZeroMQ")
item(name = "DbLayer", value = "FDB")
item(name = "DictionarySource", value = "DB")
item(name = "AliasSource", value = "DB")
item(name = "MetricsEnabled", value = "false")
item(name = "ZeroMQProxyInboundPort", value = "5001")
item(name = "ZeroMQProxyOutboundPort", value = "5000")
item(name = "DbHost", value = "localhost")
item(name = "DbMode", value = "VANILLA")
item(name = "GenesisNetProtocol", value = "V2")
item(name = "ResourcePollerTimeout", value = "5")
item(name = "ReqRepTimeout", value = "60")
item(name = "MetadataChronicleMapAverageKeySizeBytes", value = "128")
item(name = "MetadataChronicleMapAverageValueSizeBytes", value = "1024")
item(name = "MetadataChronicleMapEntriesCount", value = "512")
item(name = "DaemonServerPort", value = "4568")
item(
name = "JVM_OPTIONS",
value = "-XX:MaxHeapFreeRatio=70 -XX:MinHeapFreeRatio=30 -XX:+UseG1GC -XX:+UseStringDeduplication -XX:OnOutOfMemoryError=\"handleOutOfMemoryError.sh %p\""
)
}
systems {
system(name = "DEV") {
hosts {
host(LOCAL_HOST)
}
item(name = "DbNamespace", value = "{{appName}}")
item(name = "ClusterPort", value = "6000")
item(name = "location", value = "LO")
item(name = "LogFramework", value = "LOG4J2")
item(name = "LogFrameworkConfig", value = "log4j2-default.xml")
}
}
} | 4 | Kotlin | 1 | 3 | fad6001eb4bc88c07e9f6cb003650ed0f35211e2 | 1,712 | blank-app-seed | Apache License 2.0 |
src/main/kotlin/belicfr/exercise/sbkotblog/properties/BlogProperties.kt | belicfr | 784,094,811 | false | {"Kotlin": 13805, "Mustache": 1907} | package belicfr.exercise.sbkotblog.properties
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties("blog")
data class BlogProperties(var title: String,
var banner: Banner) {
data class Banner(val title: String? = null,
var content: String)
}
| 0 | Kotlin | 0 | 0 | ca31d2f4f76b556d306d446742bacb8018a5ccc3 | 344 | sboot-kotlin-blog | MIT License |
src/main/kotlin/belicfr/exercise/sbkotblog/properties/BlogProperties.kt | belicfr | 784,094,811 | false | {"Kotlin": 13805, "Mustache": 1907} | package belicfr.exercise.sbkotblog.properties
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties("blog")
data class BlogProperties(var title: String,
var banner: Banner) {
data class Banner(val title: String? = null,
var content: String)
}
| 0 | Kotlin | 0 | 0 | ca31d2f4f76b556d306d446742bacb8018a5ccc3 | 344 | sboot-kotlin-blog | MIT License |
src/main/kotlin/ru/lebe/dev/mrjanitor/usecase/GetFileItemsForCleanUp.kt | lebe-dev | 195,414,491 | false | null | package ru.lebe.dev.mrjanitor.usecase
import arrow.core.Either
import arrow.core.None
import arrow.core.Option
import arrow.core.Some
import org.slf4j.LoggerFactory
import ru.lebe.dev.mrjanitor.domain.FileItem
import ru.lebe.dev.mrjanitor.domain.OperationError
import ru.lebe.dev.mrjanitor.domain.OperationResult
import ru.lebe.dev.mrjanitor.domain.PathFileIndex
import ru.lebe.dev.mrjanitor.domain.Profile
class GetFileItemsForCleanUp(
private val createFileIndex: CreateFileIndex,
private val checkIfFileItemValid: CheckIfFileItemValid
) {
private val log = LoggerFactory.getLogger(javaClass)
fun getItems(profile: Profile): OperationResult<List<FileItem>> {
log.info("get file items for clean up for profile '${profile.name}'")
log.info("- path: '${profile.path}'")
return if (profile.keepItemsQuantity > 0) {
when(val fileIndex = createFileIndex.create(profile)) {
is Either.Right -> {
val validatedFileItems = getValidatedItems(profile, fileIndex.b)
val validFilePaths = validatedFileItems.filter { it.valid }
.sortedBy { it.path.toFile().lastModified() }
.takeLast(profile.keepItemsQuantity)
.map { it.path.toString() }
val results = when {
profile.cleanUpPolicy.allInvalidItems -> getAllInvalidItems(validatedFileItems, validFilePaths)
profile.cleanUpPolicy.invalidItemsBeyondOfKeepQuantity ->
getInvalidItemsBeyondKeepRange(validatedFileItems, profile.keepItemsQuantity)
else -> listOf()
}
Either.right(results)
}
is Either.Left -> Either.left(OperationError.ERROR)
}
} else {
log.error("misconfiguration - keep-items-quantity equals zero")
Either.left(OperationError.MISCONFIGURATION)
}
}
private fun getValidatedItems(profile: Profile, pathFileIndex: PathFileIndex): List<FileItem> =
pathFileIndex.fileItems.map { fileItem ->
fileItem.copy(
valid = checkIfFileItemValid.isValid(
fileItem = fileItem,
previousFileItem = getPreviousFileItem(pathFileIndex.fileItems, fileItem.path.toString()),
validationConfig = profile.fileItemValidationConfig
)
)
}
private fun getAllInvalidItems(fileItems: List<FileItem>, validFilePaths: List<String>): List<FileItem> =
fileItems.filterNot { it.path.toString() in validFilePaths }
private fun getInvalidItemsBeyondKeepRange(fileItems: List<FileItem>, keepItemsQuantity: Int): List<FileItem> {
var lastValidItemsFound = 0
val excludeItems = fileItems.takeLastWhile {
if (isValidItemInKeepRange(it, keepItemsQuantity, lastValidItemsFound)) {
lastValidItemsFound++
true
} else {
lastValidItemsFound < keepItemsQuantity
}
}.map { it.path.toString() }
return fileItems.filterNot { it.path.toString() in excludeItems }
}
private fun isValidItemInKeepRange(fileItem: FileItem, keepItemsQuantity: Int, currentItemQuantity: Int): Boolean =
fileItem.valid && (currentItemQuantity < keepItemsQuantity)
private fun getPreviousFileItem(fileItems: List<FileItem>, fileItemPath: String): Option<FileItem> {
val itemsBeforeCurrent = fileItems.takeWhile { it.path.toString() != fileItemPath }
return if (itemsBeforeCurrent.isNotEmpty()) {
Some(itemsBeforeCurrent.last())
} else {
None
}
}
}
| 0 | Kotlin | 0 | 0 | 4f714a50f192a422f619de6d3ad49212fb8921b1 | 3,930 | mr-janitor | MIT License |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/Evaluator.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: Evaluator
*
* Full name: System`Evaluator
*
* Usage: Evaluator is an option for objects such as Button, Dynamic, and Cell that gives the name of the kernel to use to evaluate their contents.
*
* Options: None
*
* Attributes: Protected
*
* local: paclet:ref/Evaluator
* Documentation: web: http://reference.wolfram.com/language/ref/Evaluator.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun evaluator(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("Evaluator", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,014 | mathemagika | Apache License 2.0 |
ocs-ktc/src/test/kotlin/org/ostelco/prime/ocs/core/OnlineChargingTest.kt | ostelco | 112,729,477 | false | null | package org.ostelco.prime.ocs.core
import io.grpc.stub.StreamObserver
import kotlinx.coroutines.runBlocking
import org.junit.Ignore
import org.junit.Test
import org.ostelco.ocs.api.CreditControlAnswerInfo
import org.ostelco.ocs.api.CreditControlRequestInfo
import org.ostelco.ocs.api.MultipleServiceCreditControl
import org.ostelco.ocs.api.ServiceUnit
import java.util.*
import java.util.concurrent.CountDownLatch
import kotlin.system.measureTimeMillis
import kotlin.test.fail
@ExperimentalUnsignedTypes
class OnlineChargingTest {
@Ignore
@Test
fun `load test OnlineCharging directly`() = runBlocking {
// Add delay to DB call and skip analytics and low balance notification
OnlineCharging.loadUnitTest = true
// count down latch to wait for all responses to return
val cdl = CountDownLatch(COUNT)
// response handle which will count down on receiving response
val creditControlAnswerInfo: StreamObserver<CreditControlAnswerInfo> = object : StreamObserver<CreditControlAnswerInfo> {
override fun onNext(value: CreditControlAnswerInfo?) {
// count down on receiving response
cdl.countDown()
}
override fun onError(t: Throwable?) {
fail(t?.message)
}
override fun onCompleted() {
}
}
// Sample request which will be sent repeatedly
val request = CreditControlRequestInfo.newBuilder()
.setRequestId(UUID.randomUUID().toString())
.setMsisdn(MSISDN)
.addMscc(0, MultipleServiceCreditControl.newBuilder()
.setRequested(ServiceUnit.newBuilder().setTotalOctets(100))
.setUsed(ServiceUnit.newBuilder().setTotalOctets(80)))
.build()
val durationInMillis = measureTimeMillis {
// Send the same request COUNT times
repeat(COUNT) {
OnlineCharging.creditControlRequestEvent(
request = request,
returnCreditControlAnswer = creditControlAnswerInfo::onNext)
}
// Wait for all the responses to be returned
println("Waiting for all responses to be returned")
@Suppress("BlockingMethodInNonBlockingContext")
cdl.await()
}
// Print load test results
println("Time duration: %,d milli sec".format(durationInMillis))
val rate = COUNT * 1000.0 / durationInMillis
println("Rate: %,.2f req/sec".format(rate))
}
companion object {
private const val COUNT = 1_000_000
private const val MSISDN = "4790300147"
}
} | 23 | null | 13 | 37 | b072ada4aca8c4bf5c3c2f6fe0d36a5ff16c11af | 2,740 | ostelco-core | Apache License 2.0 |
app/src/main/java/org/sxczst/enjoyedu/course/frameworktopic/dispatchtouchevent/bad/BadViewPager.kt | BakerYw | 360,380,503 | false | {"Kotlin": 62472} | package org.sxczst.enjoyedu.course.frameworktopic.dispatchtouchevent.bad
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager
import kotlin.math.abs
/**
* @author sxczst
* @date 2021/4/3 12:25
*/
class BadViewPager : ViewPager {
private var mLastX: Int = 0
private var mLastY: Int = 0
constructor(context: Context) : super(context)
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
// 内部拦截法
// if (ev.action == MotionEvent.ACTION_DOWN) {
// super.onInterceptTouchEvent(ev)
// return false
// }
// return true
// 外部拦截法
val x = ev.x.toInt()
val y = ev.y.toInt()
when (ev.action) {
MotionEvent.ACTION_DOWN -> {
mLastX = ev.x.toInt()
mLastY = ev.y.toInt()
}
MotionEvent.ACTION_MOVE -> {
val deltaX = x - mLastX
val deltaY = y - mLastY
if (abs(deltaX) > abs(deltaY)) {
return true
}
}
}
return super.onInterceptTouchEvent(ev)
}
} | 0 | null | 0 | 1 | e89f955f5e7756b66ff9848bc81d6eee291d0280 | 1,322 | EnjoyEdu | Apache License 2.0 |
react-kotlin/src/jsMain/kotlin/react/dom/events/UIEvent.kt | karakum-team | 393,199,102 | false | null | // Automatically generated - do not modify!
package react.dom.events
import web.dom.Element
import web.window.Window
external interface UIEvent<out T : Element, out E : NativeUIEvent> : SyntheticEvent<T, E> {
val detail: Int
val view: Window
}
| 0 | null | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 255 | types-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.