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
idea/testData/quickfix/variables/changeToPropertyAccess/propertyCallWithArguments.kt
yusuke
54,976,085
true
{"Java": 15858891, "Kotlin": 13092817, "JavaScript": 177557, "Protocol Buffer": 42724, "HTML": 31546, "Lex": 16598, "ANTLR": 9689, "CSS": 9358, "Groovy": 7182, "IDL": 4786, "Shell": 4704, "Batchfile": 3703}
// "Change to property access" "false" // ERROR: Expression 'fd' of type 'String' cannot be invoked as a function. The function invoke() is not found class A(val fd: String) fun x() { val y = A("").f<caret>d("") }
0
Java
0
0
cbb6f7ed6344cc524478fb0d762e61854474afce
219
kotlin
Apache License 2.0
shared/src/test/kotlin/at/yawk/javabrowser/SourceAnnotationTest.kt
yawkat
135,326,421
false
null
package at.yawk.javabrowser import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import com.fasterxml.jackson.module.kotlin.SingletonSupport import org.testng.Assert import org.testng.annotations.Test class SourceAnnotationTest { private val objectMapper = ObjectMapper().registerModule(KotlinModule(singletonSupport = SingletonSupport.CANONICALIZE)) private inline fun <reified T> testDeser(o: T) { val s = objectMapper.writerFor(T::class.java).writeValueAsString(o) val d = objectMapper.readerFor(T::class.java).readValue<T>(s) Assert.assertEquals(d, o) } @Test fun testDeser() { testDeser(BindingRef( BindingRefType.SUPER_TYPE, BindingId(123), 234, false )) testDeser(BindingDecl( id = BindingId(123), binding = "abc", description = BindingDecl.Description.Package, modifiers = 456, superBindings = emptyList(), parent = BindingId(789), corresponding = mapOf(Realm.BYTECODE to BindingId(456)) )) testDeser(BindingDecl.Description.Type( BindingDecl.Description.Type.Kind.CLASS, BindingId(123), "abc", emptyList() )) testDeser(BindingDecl.Super( "abc", BindingId(123) )) } }
17
null
3
35
b9233824bf594bacffaee2efbf12ab9ea941763e
1,489
java-browser
Apache License 2.0
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/execution/LineAndColumnFromRangeTest.kt
JohanWranker
121,043,472
false
null
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.gradle.kotlin.dsl.execution import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class LineAndColumnFromRangeTest(val given: Given) { data class Given(val range: IntRange, val expected: Pair<Int, Int>) companion object { const val text = "line 1\nline 2\nline 3" @Parameterized.Parameters(name = "{0}") @JvmStatic fun testCases(): Iterable<Given> = listOf( Given(0..0, 1 to 1), Given(1..1, 1 to 2), Given(7..7, 2 to 1), Given(8..8, 2 to 2), Given(19..19, 3 to 6)) } @Test fun test() { assertThat( text.lineAndColumnFromRange(given.range), equalTo(given.expected)) } }
2,663
null
4552
2
e089307757e7ee7e1a898e84841bd2100ff7ef27
1,535
gradle
Apache License 2.0
src/test/kotlin/org/openasr/idiolect/recognizer/CustomMicrophoneTest.kt
OpenASR
37,895,115
false
null
package org.openasr.idiolect.recognizer import org.junit.Assert.* import org.junit.Test import java.util.Arrays import javax.sound.sampled.DataLine class CustomMicrophoneTest { // @Test // fun testUseDefaultLine() { // val mic = CustomMicrophone() // // // When // mic.useDefaultLine() // var line = mic.getLine() // // val dataLineInfo = line?.lineInfo as DataLine.Info // // Arrays.stream(dataLineInfo.formats) // .forEach { format -> System.out.println(" " + format.toString()) } // // // Then // assertNotNull("microphone should select default line", mic.getLine()) // } // @Test // fun testRecordFromMic() { // val mic = CustomMicrophone() // // mic.open() // println("Recording...") // val file = mic.recordFromMic(5000) // mic.close() // // println("Recorded to " + file.absoluteFile) // } }
10
null
10
93
c3f5ede3f4c5b43f7231faeab8f20f8147bf66dc
934
idiolect
Apache License 2.0
zircon.core/src/main/kotlin/org/codetome/zircon/internal/component/listener/MouseListener.kt
opencollective
119,803,967
true
{"Kotlin": 697338, "Java": 71250}
package org.codetome.zircon.internal.component.listener import org.codetome.zircon.api.input.MouseAction interface MouseListener { fun onMouseEvent(mouseAction: MouseAction) }
0
Kotlin
1
1
3c1cd8aa4b6ddcbc39b9873c54ac64e3ec6cda4d
182
zircon
MIT License
idea/testData/codeInsight/generate/secondaryConstructors/javaSupers.kt
JakeWharton
99,388,807
false
null
// ACTION_CLASS: org.jetbrains.kotlin.idea.actions.generate.KotlinGenerateSecondaryConstructorAction class Foo : Base {<caret> val x = 1 fun foo() { } fun bar() { } }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
190
kotlin
Apache License 2.0
core/src/main/kotlin/cn/netdiscovery/adbd/device/AbstractAdbDevice.kt
fengzhizi715
372,844,804
false
null
package cn.netdiscovery.adbd.device import cn.netdiscovery.adbd.AdbChannelInitializer import cn.netdiscovery.adbd.domain.AdbChannelAddress import cn.netdiscovery.adbd.domain.DeviceInfo import cn.netdiscovery.adbd.domain.PendingWriteEntry import cn.netdiscovery.adbd.domain.enum.DeviceMode import cn.netdiscovery.adbd.domain.enum.DeviceType import cn.netdiscovery.adbd.domain.enum.Feature import cn.netdiscovery.adbd.domain.sync.SyncDent import cn.netdiscovery.adbd.domain.sync.SyncQuit import cn.netdiscovery.adbd.domain.sync.SyncStat import cn.netdiscovery.adbd.exception.AdbException import cn.netdiscovery.adbd.netty.channel.AdbChannel import cn.netdiscovery.adbd.netty.channel.TCPReverse import cn.netdiscovery.adbd.netty.codec.* import cn.netdiscovery.adbd.netty.connection.AdbChannelProcessor import cn.netdiscovery.adbd.netty.handler.* import cn.netdiscovery.adbd.utils.buildShellCmd import cn.netdiscovery.adbd.utils.getChannelName import cn.netdiscovery.adbd.utils.logger import io.netty.bootstrap.ServerBootstrap import io.netty.buffer.PooledByteBufAllocator import io.netty.channel.* import io.netty.channel.socket.SocketChannel import io.netty.channel.socket.nio.NioServerSocketChannel import io.netty.handler.codec.LineBasedFrameDecoder import io.netty.handler.codec.string.StringDecoder import io.netty.handler.codec.string.StringEncoder import io.netty.util.concurrent.Future import io.netty.util.concurrent.GenericFutureListener import io.netty.util.concurrent.Promise import java.io.InputStream import java.io.OutputStream import java.nio.charset.StandardCharsets import java.security.interfaces.RSAPrivateCrtKey import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.RejectedExecutionException import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicInteger /** * * @FileName: * cn.netdiscovery.adbd.device.AbstractAdbDevice * @author: <NAME> * @date: 2022/4/2 2:58 下午 * @version: V1.0 adb 协议支持的命令可以查看:https://android.googlesource.com/platform/packages/modules/adb/+/HEAD/SERVICES.TXT */ abstract class AbstractAdbDevice protected constructor( private val serial: String, private val privateKey: RSAPrivateCrtKey, private val publicKey: ByteArray, private val factory: cn.netdiscovery.adbd.ChannelFactory ) : AdbDevice { private val logger = logger<AbstractAdbDevice>() private val channelIdGen: AtomicInteger = AtomicInteger(1) private val reverseMap: MutableMap<CharSequence, AdbChannelInitializer> = ConcurrentHashMap<CharSequence, AdbChannelInitializer>() private val forwards: MutableSet<Channel> = ConcurrentHashMap.newKeySet() @Volatile private var listeners: MutableSet<DeviceListener> = ConcurrentHashMap.newKeySet() @Volatile private lateinit var channel: Channel @Volatile var deviceInfo: DeviceInfo?=null init { try { newConnection()[30, TimeUnit.SECONDS] // 30秒超时 } catch (e:Exception) { logger.error("[{}] device disconnected,error={}", serial(), e.message, e) throw AdbException("connect exception") } } private fun newConnection(): ChannelFuture { val future:ChannelFuture = factory.invoke(object : ChannelInitializer<Channel>() { override fun initChannel(ch: Channel) { val pipeline = ch.pipeline() pipeline.addLast(object : ChannelInboundHandlerAdapter() { @Throws(Exception::class) override fun channelInactive(ctx: ChannelHandlerContext) { logger.info("[{}] device disconnected", serial()) listeners.forEach{ listener -> try { listener.onDisconnected(this@AbstractAdbDevice) } catch (e: Exception) { logger.error("[{}] call disconnect handler failed, error={}", serial(), e.message, e) } } super.channelInactive(ctx) } }) .addLast("codec", AdbPacketCodec()) .addLast("auth", AdbAuthHandler(privateKey, publicKey)) .addLast("connect", ConnectHandler(this@AbstractAdbDevice)) } }) channel = future.channel() logger.info("[{}] device connected", serial()) return future } protected fun factory(): cn.netdiscovery.adbd.ChannelFactory = factory protected fun privateKey(): RSAPrivateCrtKey = privateKey protected fun publicKey(): ByteArray = publicKey override fun eventLoop(): EventLoop = channel.eventLoop() override fun serial() = serial override fun type(): DeviceType? = deviceInfo?.type?:null override fun model(): String? = deviceInfo?.model?:null override fun product(): String? = deviceInfo?.product?:null override fun device(): String? = deviceInfo?.device?:null override fun features(): Set<Feature>? = deviceInfo?.features?:null override fun open(destination: String, timeoutMs: Int, initializer: AdbChannelInitializer?): ChannelFuture { val localId = channelIdGen.getAndIncrement() val channelName = getChannelName(localId) val adbChannel = AdbChannel(channel, localId, 0) adbChannel.config().connectTimeoutMillis = timeoutMs initializer?.invoke(adbChannel) channel.pipeline().addLast(channelName, adbChannel) return adbChannel.connect(AdbChannelAddress(destination, localId)) } override fun exec(destination: String, timeoutMs: Int): Future<String> { val promise = eventLoop().newPromise<String>() val future = open(destination, timeoutMs, object:AdbChannelInitializer { override fun invoke(channel: Channel) { channel.pipeline() .addLast(StringDecoder(StandardCharsets.UTF_8)) .addLast(StringEncoder(StandardCharsets.UTF_8)) .addLast(ExecHandler(promise)) } }) future.addListener { f: Future<in Void> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } } promise.addListener { f: Future<in String> -> future.channel().close() } if (timeoutMs > 0) { eventLoop().schedule({ val cause = TimeoutException("exec timeout: " + destination.trim { it <= ' ' }) promise.tryFailure(cause) }, timeoutMs.toLong(), TimeUnit.MILLISECONDS) } return promise } override fun shell(cmd: String, timeoutMs: Int, vararg args: String): Future<String> { val shellCmd: String = buildShellCmd(cmd, *args) return exec(shellCmd, timeoutMs) } override fun shell(lineFramed: Boolean, handler: ChannelInboundHandler): ChannelFuture { return open("shell:\u0000", object:AdbChannelInitializer{ override fun invoke(channel: Channel) { if (lineFramed) { channel.pipeline().addLast(LineBasedFrameDecoder(8192)) } channel.pipeline() .addLast(StringDecoder(StandardCharsets.UTF_8)) .addLast(StringEncoder(StandardCharsets.UTF_8)) .addLast(handler) } }) } override fun shell( cmd: String, args: Array<String>, lineFramed: Boolean, handler: ChannelInboundHandler ): ChannelFuture { val shellCmd: String = buildShellCmd(cmd, *args) return open(shellCmd, object:AdbChannelInitializer{ override fun invoke(channel: Channel) { if (lineFramed) { channel.pipeline().addLast(LineBasedFrameDecoder(8192)) } channel.pipeline() .addLast(StringDecoder(StandardCharsets.UTF_8)) .addLast(StringEncoder(StandardCharsets.UTF_8)) .addLast(handler) } }) } private fun <T> sync(promise: Promise<T>, initializer: AdbChannelInitializer) { val future = open("sync:\u0000", initializer) future.addListener { f: Future<in Void> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } } promise.addListener { f: Future<in T> -> future.channel() .writeAndFlush(SyncQuit()) .addListener { f0: Future<in Void> -> future.channel().close() } } } override fun stat(path: String): Future<SyncStat> { val promise = eventLoop().newPromise<SyncStat>() sync(promise, object:AdbChannelInitializer{ override fun invoke(channel: Channel) { channel.pipeline() .addLast(SyncStatDecoder()) .addLast(SyncEncoder()) .addLast(SyncStatHandler(this@AbstractAdbDevice, path, promise)) } }) return promise } override fun list(path: String): Future<Array<SyncDent>> { val promise = eventLoop().newPromise<Array<SyncDent>>() sync<Array<SyncDent>>(promise, object:AdbChannelInitializer { override fun invoke(channel: Channel) { channel.pipeline() .addLast(SyncDentDecoder()) .addLast(SyncDentAggregator()) .addLast(SyncEncoder()) .addLast(SyncListHandler(this@AbstractAdbDevice, path, promise)) } }) return promise } override fun pull(src: String, dest: OutputStream): Future<Any> { val promise = eventLoop().newPromise<Any>() sync<Any>(promise, object: AdbChannelInitializer { override fun invoke(channel: Channel) { channel.pipeline() .addLast(SyncDataDecoder()) .addLast(SyncEncoder()) .addLast(SyncPullHandler(this@AbstractAdbDevice, src, dest, promise)) } }) return promise } override fun push(src: InputStream, dest: String, mode: Int, mtime: Int): Future<Any> { val promise = eventLoop().newPromise<Any>() sync<Any>(promise, object: AdbChannelInitializer { override fun invoke(channel: Channel) { channel.pipeline() .addLast(SyncDecoder()) .addLast(SyncEncoder()) .addLast(SyncPushHandler(this@AbstractAdbDevice, src, dest, mode, mtime, promise)) } }) return promise } override fun root(): Future<*> { val promise = eventLoop().newPromise<Any>() val handler = RestartHandler(promise) addListener(handler) exec("root:\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { val s: String = f.now.trim() if (s == "adbd is already running as root") { removeListener(handler) promise.trySuccess(null) } else if (s.startsWith("adbd cannot run as root")) { removeListener(handler) promise.tryFailure(AdbException(s)) } } }) return promise } override fun unroot(): Future<*> { val promise = eventLoop().newPromise<Any>() val handler = RestartHandler(promise) addListener(handler) exec("unroot:\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { val s: String = f.now.trim() if (s == "adbd not running as root") { removeListener(handler) promise.trySuccess(null) } } }) return promise } override fun remount(): Future<*> { val promise = eventLoop().newPromise<Any>() exec("remount:\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { val s: String = f.now.trim() if (s == "remount succeeded") { promise.trySuccess(null) } else { promise.tryFailure(AdbException(s)) } } }) return promise } override fun reverse(destination: String, initializer: AdbChannelInitializer): Future<String> { val cmd = "reverse:forward:$destination;$destination\u0000" val promise = eventLoop().newPromise<String>() exec(cmd).addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { try { val result: String = readResult(f.now)?:"" reverseMap[destination] = initializer promise.trySuccess(result) } catch (cause: Throwable) { promise.tryFailure(cause) } } }) return promise } override fun reverse(remote: String, local: String): Future<String> { val addr = local.split(":").toTypedArray() val protocol: String val host: String val port: Int if (addr.size == 2) { protocol = addr[0] host = "127.0.0.1" port = Integer.valueOf(addr[1]) } else if (addr.size == 3) { protocol = addr[0] host = addr[1] port = Integer.valueOf(addr[2]) } else { throw IllegalArgumentException("local") } require("tcp" == protocol) { "local" } val cmd = "reverse:forward:$remote;$local\u0000" val promise = eventLoop().newPromise<String>() exec(cmd).addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { try { val result: String = readResult(f.now)?:"" reverseMap[local] = TCPReverse(host, port, eventLoop()) promise.trySuccess(result) } catch (cause: Throwable) { promise.tryFailure(cause) } } }) return promise } @Throws(AdbException::class) private fun readResult(result: String): String? { return if (result.isEmpty()) { null } else if (result.startsWith("FAIL")) { val len = Integer.valueOf(result.substring(4, 8), 16) throw AdbException(result.substring(8, 8 + len)) } else if (result.startsWith("OKAY")) { if (result.length > 4) { val len = Integer.valueOf(result.substring(4, 8), 16) result.substring(8, 8 + len) } else { null } } else { val len = Integer.valueOf(result.substring(0, 4), 16) result.substring(4, 4 + len) } } override fun reverseList(): Future<Array<String>> { val promise = eventLoop().newPromise<Array<String>>() exec("reverse:list-forward\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { try { val result: String = readResult(f.now)?.trim()?:"" val revs: Array<String> = if (result.isNullOrEmpty()) { mutableListOf<String>().toTypedArray() } else { result.split("\r\n|\n|\r").toTypedArray() } promise.trySuccess(revs) } catch (cause: Throwable) { promise.tryFailure(cause) } } }) return promise } override fun reverseRemove(destination: String): Future<Any> { val promise = eventLoop().newPromise<Any>() exec("reverse:killforward:$destination\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { try { val result: String = readResult(f.now)?:"" reverseMap.remove(destination) promise.trySuccess(result) } catch (cause: Throwable) { promise.tryFailure(cause) } } }) return promise } override fun reverseRemoveAll(): Future<Any> { val promise = eventLoop().newPromise<Any>() exec("reverse:killforward-all\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { try { val result: String = readResult(f.now)?:"" reverseMap.clear() promise.trySuccess(result) } catch (cause: Throwable) { promise.tryFailure(cause) } } }) return promise } override fun forward(destination: String, port: Int): ChannelFuture { val bootstrap = ServerBootstrap() return bootstrap.group(eventLoop()) .channel(NioServerSocketChannel::class.java) .option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(object : ChannelInitializer<SocketChannel>() { @Throws(java.lang.Exception::class) override fun initChannel(ch: SocketChannel) { val future = open(destination, 30000, object: AdbChannelInitializer { override fun invoke(channel: Channel) { channel.pipeline().addLast(object : ChannelInboundHandlerAdapter() { @Throws(java.lang.Exception::class) override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { ch.writeAndFlush(msg) } @Throws(java.lang.Exception::class) override fun channelInactive(ctx: ChannelHandlerContext) { ch.close() } }) } }).addListener { f: Future<in Void> -> if (f.cause() != null) { ch.close() } } ch.pipeline().addLast(object : ChannelInboundHandlerAdapter() { @Throws(java.lang.Exception::class) override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { future.channel().writeAndFlush(msg) } @Throws(java.lang.Exception::class) override fun channelInactive(ctx: ChannelHandlerContext) { future.channel().close() } }) } }) .bind(port) .addListener(GenericFutureListener { f: ChannelFuture -> if (f.cause() != null) { forwards.add(f.channel()) } }) } @Throws(java.lang.Exception::class) override fun reboot(mode: DeviceMode): Future<*> { return open("reboot:" + mode.name + "\u0000", null) } override fun reconnect(): ChannelFuture { val channel = this.channel check(!(channel.isOpen || channel.isActive)) { "channel is open or active" } return newConnection() } override fun addListener(listener: DeviceListener) { listeners.add(listener) } override fun removeListener(listener: DeviceListener) { listeners.remove(listener) } @Throws(java.lang.Exception::class) override fun close() { try { //关闭reverse reverseRemoveAll()[30, TimeUnit.SECONDS] } catch (e: java.lang.Exception) { } //关闭forward for (forward in forwards) { try { forward.close()[30, TimeUnit.SECONDS] } catch (e: java.lang.Exception) { } } channel.close()[30, TimeUnit.SECONDS] } private class RestartHandler(private val promise: Promise<*>) : DeviceListener { override fun onConnected(device: AdbDevice) { } override fun onDisconnected(device: AdbDevice) { device.removeListener(this) (device as AbstractAdbDevice).newConnection().addListener{ f1 -> if (f1.cause() != null) { promise.tryFailure(f1.cause()) } else { promise.trySuccess(null) } } } } private class ConnectHandler(val device: AbstractAdbDevice) : ChannelDuplexHandler() { private val pendingWriteEntries: Queue<PendingWriteEntry> = LinkedList() @Throws(Exception::class) override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { if (msg is DeviceInfo) { ctx.pipeline() .remove(this) .addAfter("codec", "processor", AdbChannelProcessor(device.channelIdGen, device.reverseMap)) device.deviceInfo = msg while (true) { val entry: PendingWriteEntry = pendingWriteEntries.poll() ?: break ctx.channel().write(entry.msg).addListener { f: Future<in Void> -> if (f.cause() != null) { entry.promise.tryFailure(f.cause()) } else { entry.promise.trySuccess() } } } ctx.channel().flush() device.listeners.forEach{ listener -> try { listener.onConnected(device) } catch (e: Exception) { } } } else { super.channelRead(ctx, msg) } } @Throws(Exception::class) override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable?) { ctx.close() } @Throws(Exception::class) override fun write(ctx: ChannelHandlerContext?, msg: Any, promise: ChannelPromise) { if (!pendingWriteEntries.offer(PendingWriteEntry(msg, promise))) { promise.tryFailure(RejectedExecutionException("queue is full")) } } } }
2
null
15
58
9f85fd055296db10cedafd44587c4cb14ffba346
23,662
adbd
Apache License 2.0
core/src/main/kotlin/cn/netdiscovery/adbd/device/AbstractAdbDevice.kt
fengzhizi715
372,844,804
false
null
package cn.netdiscovery.adbd.device import cn.netdiscovery.adbd.AdbChannelInitializer import cn.netdiscovery.adbd.domain.AdbChannelAddress import cn.netdiscovery.adbd.domain.DeviceInfo import cn.netdiscovery.adbd.domain.PendingWriteEntry import cn.netdiscovery.adbd.domain.enum.DeviceMode import cn.netdiscovery.adbd.domain.enum.DeviceType import cn.netdiscovery.adbd.domain.enum.Feature import cn.netdiscovery.adbd.domain.sync.SyncDent import cn.netdiscovery.adbd.domain.sync.SyncQuit import cn.netdiscovery.adbd.domain.sync.SyncStat import cn.netdiscovery.adbd.exception.AdbException import cn.netdiscovery.adbd.netty.channel.AdbChannel import cn.netdiscovery.adbd.netty.channel.TCPReverse import cn.netdiscovery.adbd.netty.codec.* import cn.netdiscovery.adbd.netty.connection.AdbChannelProcessor import cn.netdiscovery.adbd.netty.handler.* import cn.netdiscovery.adbd.utils.buildShellCmd import cn.netdiscovery.adbd.utils.getChannelName import cn.netdiscovery.adbd.utils.logger import io.netty.bootstrap.ServerBootstrap import io.netty.buffer.PooledByteBufAllocator import io.netty.channel.* import io.netty.channel.socket.SocketChannel import io.netty.channel.socket.nio.NioServerSocketChannel import io.netty.handler.codec.LineBasedFrameDecoder import io.netty.handler.codec.string.StringDecoder import io.netty.handler.codec.string.StringEncoder import io.netty.util.concurrent.Future import io.netty.util.concurrent.GenericFutureListener import io.netty.util.concurrent.Promise import java.io.InputStream import java.io.OutputStream import java.nio.charset.StandardCharsets import java.security.interfaces.RSAPrivateCrtKey import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.RejectedExecutionException import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicInteger /** * * @FileName: * cn.netdiscovery.adbd.device.AbstractAdbDevice * @author: <NAME> * @date: 2022/4/2 2:58 下午 * @version: V1.0 adb 协议支持的命令可以查看:https://android.googlesource.com/platform/packages/modules/adb/+/HEAD/SERVICES.TXT */ abstract class AbstractAdbDevice protected constructor( private val serial: String, private val privateKey: RSAPrivateCrtKey, private val publicKey: ByteArray, private val factory: cn.netdiscovery.adbd.ChannelFactory ) : AdbDevice { private val logger = logger<AbstractAdbDevice>() private val channelIdGen: AtomicInteger = AtomicInteger(1) private val reverseMap: MutableMap<CharSequence, AdbChannelInitializer> = ConcurrentHashMap<CharSequence, AdbChannelInitializer>() private val forwards: MutableSet<Channel> = ConcurrentHashMap.newKeySet() @Volatile private var listeners: MutableSet<DeviceListener> = ConcurrentHashMap.newKeySet() @Volatile private lateinit var channel: Channel @Volatile var deviceInfo: DeviceInfo?=null init { try { newConnection()[30, TimeUnit.SECONDS] // 30秒超时 } catch (e:Exception) { logger.error("[{}] device disconnected,error={}", serial(), e.message, e) throw AdbException("connect exception") } } private fun newConnection(): ChannelFuture { val future:ChannelFuture = factory.invoke(object : ChannelInitializer<Channel>() { override fun initChannel(ch: Channel) { val pipeline = ch.pipeline() pipeline.addLast(object : ChannelInboundHandlerAdapter() { @Throws(Exception::class) override fun channelInactive(ctx: ChannelHandlerContext) { logger.info("[{}] device disconnected", serial()) listeners.forEach{ listener -> try { listener.onDisconnected(this@AbstractAdbDevice) } catch (e: Exception) { logger.error("[{}] call disconnect handler failed, error={}", serial(), e.message, e) } } super.channelInactive(ctx) } }) .addLast("codec", AdbPacketCodec()) .addLast("auth", AdbAuthHandler(privateKey, publicKey)) .addLast("connect", ConnectHandler(this@AbstractAdbDevice)) } }) channel = future.channel() logger.info("[{}] device connected", serial()) return future } protected fun factory(): cn.netdiscovery.adbd.ChannelFactory = factory protected fun privateKey(): RSAPrivateCrtKey = privateKey protected fun publicKey(): ByteArray = publicKey override fun eventLoop(): EventLoop = channel.eventLoop() override fun serial() = serial override fun type(): DeviceType? = deviceInfo?.type?:null override fun model(): String? = deviceInfo?.model?:null override fun product(): String? = deviceInfo?.product?:null override fun device(): String? = deviceInfo?.device?:null override fun features(): Set<Feature>? = deviceInfo?.features?:null override fun open(destination: String, timeoutMs: Int, initializer: AdbChannelInitializer?): ChannelFuture { val localId = channelIdGen.getAndIncrement() val channelName = getChannelName(localId) val adbChannel = AdbChannel(channel, localId, 0) adbChannel.config().connectTimeoutMillis = timeoutMs initializer?.invoke(adbChannel) channel.pipeline().addLast(channelName, adbChannel) return adbChannel.connect(AdbChannelAddress(destination, localId)) } override fun exec(destination: String, timeoutMs: Int): Future<String> { val promise = eventLoop().newPromise<String>() val future = open(destination, timeoutMs, object:AdbChannelInitializer { override fun invoke(channel: Channel) { channel.pipeline() .addLast(StringDecoder(StandardCharsets.UTF_8)) .addLast(StringEncoder(StandardCharsets.UTF_8)) .addLast(ExecHandler(promise)) } }) future.addListener { f: Future<in Void> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } } promise.addListener { f: Future<in String> -> future.channel().close() } if (timeoutMs > 0) { eventLoop().schedule({ val cause = TimeoutException("exec timeout: " + destination.trim { it <= ' ' }) promise.tryFailure(cause) }, timeoutMs.toLong(), TimeUnit.MILLISECONDS) } return promise } override fun shell(cmd: String, timeoutMs: Int, vararg args: String): Future<String> { val shellCmd: String = buildShellCmd(cmd, *args) return exec(shellCmd, timeoutMs) } override fun shell(lineFramed: Boolean, handler: ChannelInboundHandler): ChannelFuture { return open("shell:\u0000", object:AdbChannelInitializer{ override fun invoke(channel: Channel) { if (lineFramed) { channel.pipeline().addLast(LineBasedFrameDecoder(8192)) } channel.pipeline() .addLast(StringDecoder(StandardCharsets.UTF_8)) .addLast(StringEncoder(StandardCharsets.UTF_8)) .addLast(handler) } }) } override fun shell( cmd: String, args: Array<String>, lineFramed: Boolean, handler: ChannelInboundHandler ): ChannelFuture { val shellCmd: String = buildShellCmd(cmd, *args) return open(shellCmd, object:AdbChannelInitializer{ override fun invoke(channel: Channel) { if (lineFramed) { channel.pipeline().addLast(LineBasedFrameDecoder(8192)) } channel.pipeline() .addLast(StringDecoder(StandardCharsets.UTF_8)) .addLast(StringEncoder(StandardCharsets.UTF_8)) .addLast(handler) } }) } private fun <T> sync(promise: Promise<T>, initializer: AdbChannelInitializer) { val future = open("sync:\u0000", initializer) future.addListener { f: Future<in Void> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } } promise.addListener { f: Future<in T> -> future.channel() .writeAndFlush(SyncQuit()) .addListener { f0: Future<in Void> -> future.channel().close() } } } override fun stat(path: String): Future<SyncStat> { val promise = eventLoop().newPromise<SyncStat>() sync(promise, object:AdbChannelInitializer{ override fun invoke(channel: Channel) { channel.pipeline() .addLast(SyncStatDecoder()) .addLast(SyncEncoder()) .addLast(SyncStatHandler(this@AbstractAdbDevice, path, promise)) } }) return promise } override fun list(path: String): Future<Array<SyncDent>> { val promise = eventLoop().newPromise<Array<SyncDent>>() sync<Array<SyncDent>>(promise, object:AdbChannelInitializer { override fun invoke(channel: Channel) { channel.pipeline() .addLast(SyncDentDecoder()) .addLast(SyncDentAggregator()) .addLast(SyncEncoder()) .addLast(SyncListHandler(this@AbstractAdbDevice, path, promise)) } }) return promise } override fun pull(src: String, dest: OutputStream): Future<Any> { val promise = eventLoop().newPromise<Any>() sync<Any>(promise, object: AdbChannelInitializer { override fun invoke(channel: Channel) { channel.pipeline() .addLast(SyncDataDecoder()) .addLast(SyncEncoder()) .addLast(SyncPullHandler(this@AbstractAdbDevice, src, dest, promise)) } }) return promise } override fun push(src: InputStream, dest: String, mode: Int, mtime: Int): Future<Any> { val promise = eventLoop().newPromise<Any>() sync<Any>(promise, object: AdbChannelInitializer { override fun invoke(channel: Channel) { channel.pipeline() .addLast(SyncDecoder()) .addLast(SyncEncoder()) .addLast(SyncPushHandler(this@AbstractAdbDevice, src, dest, mode, mtime, promise)) } }) return promise } override fun root(): Future<*> { val promise = eventLoop().newPromise<Any>() val handler = RestartHandler(promise) addListener(handler) exec("root:\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { val s: String = f.now.trim() if (s == "adbd is already running as root") { removeListener(handler) promise.trySuccess(null) } else if (s.startsWith("adbd cannot run as root")) { removeListener(handler) promise.tryFailure(AdbException(s)) } } }) return promise } override fun unroot(): Future<*> { val promise = eventLoop().newPromise<Any>() val handler = RestartHandler(promise) addListener(handler) exec("unroot:\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { val s: String = f.now.trim() if (s == "adbd not running as root") { removeListener(handler) promise.trySuccess(null) } } }) return promise } override fun remount(): Future<*> { val promise = eventLoop().newPromise<Any>() exec("remount:\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { val s: String = f.now.trim() if (s == "remount succeeded") { promise.trySuccess(null) } else { promise.tryFailure(AdbException(s)) } } }) return promise } override fun reverse(destination: String, initializer: AdbChannelInitializer): Future<String> { val cmd = "reverse:forward:$destination;$destination\u0000" val promise = eventLoop().newPromise<String>() exec(cmd).addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { try { val result: String = readResult(f.now)?:"" reverseMap[destination] = initializer promise.trySuccess(result) } catch (cause: Throwable) { promise.tryFailure(cause) } } }) return promise } override fun reverse(remote: String, local: String): Future<String> { val addr = local.split(":").toTypedArray() val protocol: String val host: String val port: Int if (addr.size == 2) { protocol = addr[0] host = "127.0.0.1" port = Integer.valueOf(addr[1]) } else if (addr.size == 3) { protocol = addr[0] host = addr[1] port = Integer.valueOf(addr[2]) } else { throw IllegalArgumentException("local") } require("tcp" == protocol) { "local" } val cmd = "reverse:forward:$remote;$local\u0000" val promise = eventLoop().newPromise<String>() exec(cmd).addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { try { val result: String = readResult(f.now)?:"" reverseMap[local] = TCPReverse(host, port, eventLoop()) promise.trySuccess(result) } catch (cause: Throwable) { promise.tryFailure(cause) } } }) return promise } @Throws(AdbException::class) private fun readResult(result: String): String? { return if (result.isEmpty()) { null } else if (result.startsWith("FAIL")) { val len = Integer.valueOf(result.substring(4, 8), 16) throw AdbException(result.substring(8, 8 + len)) } else if (result.startsWith("OKAY")) { if (result.length > 4) { val len = Integer.valueOf(result.substring(4, 8), 16) result.substring(8, 8 + len) } else { null } } else { val len = Integer.valueOf(result.substring(0, 4), 16) result.substring(4, 4 + len) } } override fun reverseList(): Future<Array<String>> { val promise = eventLoop().newPromise<Array<String>>() exec("reverse:list-forward\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { try { val result: String = readResult(f.now)?.trim()?:"" val revs: Array<String> = if (result.isNullOrEmpty()) { mutableListOf<String>().toTypedArray() } else { result.split("\r\n|\n|\r").toTypedArray() } promise.trySuccess(revs) } catch (cause: Throwable) { promise.tryFailure(cause) } } }) return promise } override fun reverseRemove(destination: String): Future<Any> { val promise = eventLoop().newPromise<Any>() exec("reverse:killforward:$destination\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { try { val result: String = readResult(f.now)?:"" reverseMap.remove(destination) promise.trySuccess(result) } catch (cause: Throwable) { promise.tryFailure(cause) } } }) return promise } override fun reverseRemoveAll(): Future<Any> { val promise = eventLoop().newPromise<Any>() exec("reverse:killforward-all\u0000").addListener(GenericFutureListener { f: Future<String> -> if (f.cause() != null) { promise.tryFailure(f.cause()) } else { try { val result: String = readResult(f.now)?:"" reverseMap.clear() promise.trySuccess(result) } catch (cause: Throwable) { promise.tryFailure(cause) } } }) return promise } override fun forward(destination: String, port: Int): ChannelFuture { val bootstrap = ServerBootstrap() return bootstrap.group(eventLoop()) .channel(NioServerSocketChannel::class.java) .option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(object : ChannelInitializer<SocketChannel>() { @Throws(java.lang.Exception::class) override fun initChannel(ch: SocketChannel) { val future = open(destination, 30000, object: AdbChannelInitializer { override fun invoke(channel: Channel) { channel.pipeline().addLast(object : ChannelInboundHandlerAdapter() { @Throws(java.lang.Exception::class) override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { ch.writeAndFlush(msg) } @Throws(java.lang.Exception::class) override fun channelInactive(ctx: ChannelHandlerContext) { ch.close() } }) } }).addListener { f: Future<in Void> -> if (f.cause() != null) { ch.close() } } ch.pipeline().addLast(object : ChannelInboundHandlerAdapter() { @Throws(java.lang.Exception::class) override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { future.channel().writeAndFlush(msg) } @Throws(java.lang.Exception::class) override fun channelInactive(ctx: ChannelHandlerContext) { future.channel().close() } }) } }) .bind(port) .addListener(GenericFutureListener { f: ChannelFuture -> if (f.cause() != null) { forwards.add(f.channel()) } }) } @Throws(java.lang.Exception::class) override fun reboot(mode: DeviceMode): Future<*> { return open("reboot:" + mode.name + "\u0000", null) } override fun reconnect(): ChannelFuture { val channel = this.channel check(!(channel.isOpen || channel.isActive)) { "channel is open or active" } return newConnection() } override fun addListener(listener: DeviceListener) { listeners.add(listener) } override fun removeListener(listener: DeviceListener) { listeners.remove(listener) } @Throws(java.lang.Exception::class) override fun close() { try { //关闭reverse reverseRemoveAll()[30, TimeUnit.SECONDS] } catch (e: java.lang.Exception) { } //关闭forward for (forward in forwards) { try { forward.close()[30, TimeUnit.SECONDS] } catch (e: java.lang.Exception) { } } channel.close()[30, TimeUnit.SECONDS] } private class RestartHandler(private val promise: Promise<*>) : DeviceListener { override fun onConnected(device: AdbDevice) { } override fun onDisconnected(device: AdbDevice) { device.removeListener(this) (device as AbstractAdbDevice).newConnection().addListener{ f1 -> if (f1.cause() != null) { promise.tryFailure(f1.cause()) } else { promise.trySuccess(null) } } } } private class ConnectHandler(val device: AbstractAdbDevice) : ChannelDuplexHandler() { private val pendingWriteEntries: Queue<PendingWriteEntry> = LinkedList() @Throws(Exception::class) override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { if (msg is DeviceInfo) { ctx.pipeline() .remove(this) .addAfter("codec", "processor", AdbChannelProcessor(device.channelIdGen, device.reverseMap)) device.deviceInfo = msg while (true) { val entry: PendingWriteEntry = pendingWriteEntries.poll() ?: break ctx.channel().write(entry.msg).addListener { f: Future<in Void> -> if (f.cause() != null) { entry.promise.tryFailure(f.cause()) } else { entry.promise.trySuccess() } } } ctx.channel().flush() device.listeners.forEach{ listener -> try { listener.onConnected(device) } catch (e: Exception) { } } } else { super.channelRead(ctx, msg) } } @Throws(Exception::class) override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable?) { ctx.close() } @Throws(Exception::class) override fun write(ctx: ChannelHandlerContext?, msg: Any, promise: ChannelPromise) { if (!pendingWriteEntries.offer(PendingWriteEntry(msg, promise))) { promise.tryFailure(RejectedExecutionException("queue is full")) } } } }
2
null
15
58
9f85fd055296db10cedafd44587c4cb14ffba346
23,662
adbd
Apache License 2.0
core/core-api/src/main/kotlin/io/dodn/springboot/core/api/controller/v1/response/ExampleResponseDto.kt
team-dodn
592,888,685
false
null
package io.dodn.springboot.core.api.controller.v1.response data class ExampleResponseDto( val result: String )
1
null
15
75
2a2869e1d956907b6acffa14a9bbd47311555c63
116
spring-boot-kotlin-template
Apache License 2.0
gooom_app/app/src/main/java/js/pekah/gooom_app/config/ApplicationClass.kt
JosephNaa
437,180,010
false
{"Java": 41748, "Kotlin": 26221}
package js.pekah.gooom_app.config import android.app.Application import js.pekah.gooom_app.util.SharedPreferencesUtil import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit private const val TAG = "ApplicationClass_gooom" class ApplicationClass : Application() { companion object { const val SERVER_URL = "http://10.0.2.2:8080/" lateinit var sharedPreferencesUtil: SharedPreferencesUtil lateinit var retrofit: Retrofit } override fun onCreate() { super.onCreate() sharedPreferencesUtil = SharedPreferencesUtil(applicationContext) val okHttpClient = OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS).build() retrofit = Retrofit.Builder() .baseUrl(SERVER_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build() } }
1
null
1
1
e5ee846b06b2dabf163352289d9a185b81567df8
984
gooom
MIT License
app/src/main/java/com/kryptkode/farmz/navigation/NavControllerProvider.kt
KryptKode
304,291,186
false
null
package com.kryptkode.farmz.navigation import android.view.View import androidx.navigation.NavController interface NavControllerProvider { fun getNavController(): NavController fun getNavView(): View? }
1
null
1
2
5a4e9ed3b762f5a3cf6562b6cfd38210e78af69b
212
Farmz
MIT License
loopingviewpager/src/main/java/com/asksira/loopingviewpager/LoopingViewPager.kt
siralam
114,742,656
false
null
package com.asksira.loopingviewpager import android.content.Context import android.os.Handler import android.os.Looper import android.util.AttributeSet import androidx.viewpager.widget.PagerAdapter import androidx.viewpager.widget.ViewPager /** * A ViewPager that auto-scrolls, and supports infinite scroll. * For infinite Scroll, you may use LoopingPagerAdapter. */ class LoopingViewPager : ViewPager { protected var isInfinite = true protected var isAutoScroll = false protected var wrapContent = true //AutoScroll private var interval = 5000 private var currentPagePosition = 0 private var isAutoScrollResumed = false private val autoScrollHandler = Handler(Looper.getMainLooper()) private val autoScrollRunnable = Runnable { if (adapter == null || !isAutoScroll || adapter?.count ?: 0 < 2) return@Runnable if (!isInfinite && adapter?.count ?: 0 - 1 == currentPagePosition) { currentPagePosition = 0 } else { currentPagePosition++ } setCurrentItem(currentPagePosition, true) } //For Indicator var onIndicatorProgress: ((selectingPosition: Int, progress: Float) -> Unit)? = null private var previousScrollState = SCROLL_STATE_IDLE private var scrollState = SCROLL_STATE_IDLE constructor(context: Context) : super(context) { init() } constructor( context: Context, attrs: AttributeSet? ) : super(context, attrs) { val a = context.theme.obtainStyledAttributes(attrs, R.styleable.LoopingViewPager, 0, 0) try { isInfinite = a.getBoolean(R.styleable.LoopingViewPager_isInfinite, false) isAutoScroll = a.getBoolean(R.styleable.LoopingViewPager_autoScroll, false) wrapContent = a.getBoolean(R.styleable.LoopingViewPager_wrap_content, true) interval = a.getInt(R.styleable.LoopingViewPager_scrollInterval, 5000) isAutoScrollResumed = isAutoScroll } finally { a.recycle() } init() } protected fun init() { addOnPageChangeListener(object : OnPageChangeListener { override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int ) { if (onIndicatorProgress == null) return onIndicatorProgress?.invoke( getRealPosition(position), positionOffset ) } override fun onPageSelected(position: Int) { currentPagePosition = position if (isAutoScrollResumed) { autoScrollHandler.removeCallbacks(autoScrollRunnable) autoScrollHandler.postDelayed(autoScrollRunnable, interval.toLong()) } } override fun onPageScrollStateChanged(state: Int) { previousScrollState = scrollState scrollState = state if (state == SCROLL_STATE_IDLE) { //Below are code to achieve infinite scroll. //We silently and immediately flip the item to the first / last. if (isInfinite) { if (adapter == null) return val itemCount = adapter?.count ?: 0 if (itemCount < 2) { return } val index = currentItem if (index == 0) { setCurrentItem(itemCount - 2, false) //Real last item } else if (index == itemCount - 1) { setCurrentItem(1, false) //Real first item } } } } }) if (isInfinite) setCurrentItem(1, false) } override fun setAdapter(adapter: PagerAdapter?) { super.setAdapter(adapter) if (isInfinite) setCurrentItem(1, false) } fun resumeAutoScroll() { isAutoScrollResumed = true autoScrollHandler.postDelayed(autoScrollRunnable, interval.toLong()) } fun pauseAutoScroll() { isAutoScrollResumed = false autoScrollHandler.removeCallbacks(autoScrollRunnable) }//Dummy first item is selected. Indicator should be at the first one//Dummy last item is selected. Indicator should be at the last one /** * A method that helps you integrate a ViewPager Indicator. * This method returns the expected count of indicators. */ val indicatorCount: Int get() = if (adapter is LoopingPagerAdapter<*>) { (adapter as LoopingPagerAdapter<*>).listCount } else { adapter?.count ?: 0 } /** * This function needs to be called if dataSet has changed, * in order to reset current selected item and currentPagePosition and autoPageSelectionLock. */ fun reset() { currentPagePosition = if (isInfinite) { setCurrentItem(1, false) 1 } else { setCurrentItem(0, false) 0 } } fun setInterval(interval: Int) { this.interval = interval resetAutoScroll() } private fun resetAutoScroll() { pauseAutoScroll() resumeAutoScroll() } private fun getRealPosition(position: Int): Int { if (!isInfinite || adapter == null) return position return if (position == 0) { adapter!!.count - 1 - 2 //First item is a dummy of last item } else if (position > adapter!!.count - 2) { 0 //Last item is a dummy of first item } else { position - 1 } } }
9
Kotlin
65
508
60a65ca8502211ea3fd6e41360cc3d99bb7f1ef0
5,818
LoopingViewPager
The Unlicense
src/main/kotlin/org/elm/ide/components/ElmFormatOnFileSaveComponent.kt
intellij-elm
104,530,474
false
{"Kotlin": 1475967, "Elm": 19420, "Lex": 5823, "HTML": 2289}
package org.elm.ide.components import com.intellij.AppTopics import com.intellij.notification.NotificationType import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileDocumentManagerListener import com.intellij.openapi.project.Project import org.elm.ide.notifications.showBalloon import org.elm.lang.core.psi.isElmFile import org.elm.workspace.commandLineTools.ElmFormatCLI import org.elm.workspace.commandLineTools.ElmFormatCLI.ElmFormatResult import org.elm.workspace.elmSettings import org.elm.workspace.elmToolchain import org.elm.workspace.elmWorkspace class ElmFormatOnFileSaveComponent(val project: Project) { init { with(project.messageBus.connect()) { subscribe( AppTopics.FILE_DOCUMENT_SYNC, object : FileDocumentManagerListener { override fun beforeDocumentSaving(document: Document) { if (!project.elmSettings.toolchain.isElmFormatOnSaveEnabled) return val vFile = FileDocumentManager.getInstance().getFile(document) ?: return if (!vFile.isElmFile) return val elmVersion = ElmFormatCLI.getElmVersion(project, vFile) ?: return val elmFormat = project.elmToolchain.elmFormatCLI ?: return val result = elmFormat.formatDocumentAndSetText(project, document, elmVersion, addToUndoStack = false) when (result) { is ElmFormatResult.BadSyntax -> project.showBalloon(result.msg, NotificationType.WARNING) is ElmFormatResult.FailedToStart -> project.showBalloon(result.msg, NotificationType.ERROR, "Configure" to { project.elmWorkspace.showConfigureToolchainUI() } ) is ElmFormatResult.UnknownFailure -> project.showBalloon(result.msg, NotificationType.ERROR) is ElmFormatResult.Success -> return } } } ) } } }
180
Kotlin
70
390
7c0c3fac666735bc5170fe1878165ed19bda99c3
2,344
intellij-elm
MIT License
subprojects/test-runner/report-viewer/src/main/kotlin/com/avito/reportviewer/internal/ReportsFetchApiImpl.kt
avito-tech
230,265,582
false
null
package com.avito.reportviewer.internal import com.avito.android.Result import com.avito.android.test.annotations.TestCaseBehavior import com.avito.android.test.annotations.TestCasePriority import com.avito.jsonrpc.JsonRpcClient import com.avito.jsonrpc.RfcRpcRequest import com.avito.jsonrpc.RpcResult import com.avito.report.model.Flakiness import com.avito.report.model.Kind import com.avito.report.model.Stability import com.avito.report.model.TestStatus import com.avito.reportviewer.ReportsFetchApi import com.avito.reportviewer.internal.model.ConclusionStatus import com.avito.reportviewer.internal.model.GetReportResult import com.avito.reportviewer.internal.model.ListResult import com.avito.reportviewer.internal.model.ReportViewerStatus import com.avito.reportviewer.model.Report import com.avito.reportviewer.model.ReportCoordinates import com.avito.reportviewer.model.SimpleRunTest import com.avito.test.model.TestName internal class ReportsFetchApiImpl( private val client: JsonRpcClient, ) : ReportsFetchApi { override fun getReport(reportCoordinates: ReportCoordinates): Result<Report> { return when (val result = getReportInternal(reportCoordinates)) { is GetReportResult.Error -> Result.Failure(result.exception) is GetReportResult.Found -> Result.Success(result.report) is GetReportResult.NotFound -> Result.Failure( Exception("Report not found $reportCoordinates", result.exception) ) } } override fun getTestsForRunCoordinates(reportCoordinates: ReportCoordinates): Result<List<SimpleRunTest>> { return when (val result = getReportInternal(reportCoordinates)) { is GetReportResult.Found -> getTestData(result.report.id) is GetReportResult.NotFound -> Result.Failure( Exception("Report not found $reportCoordinates", result.exception) ) is GetReportResult.Error -> Result.Failure(result.exception) } } override fun getTestsForRunId(reportId: String): Result<List<SimpleRunTest>> { return getTestData(reportId) } private fun getReportInternal(reportCoordinates: ReportCoordinates): GetReportResult { return Result.tryCatch { client.jsonRpcRequest<RpcResult<Report>>( RfcRpcRequest( method = "Run.GetByParams", params = mapOf( "plan_slug" to reportCoordinates.planSlug, "job_slug" to reportCoordinates.jobSlug, "run_id" to reportCoordinates.runId ) ) ).result }.fold( { report -> GetReportResult.Found(report) }, { exception -> val isNotFoundError = exception.message?.contains("\"data\":\"not found\"") ?: false if (isNotFoundError) { GetReportResult.NotFound(exception) } else { GetReportResult.Error(exception) } } ) } private fun getTestData(reportId: String): Result<List<SimpleRunTest>> { return Result.tryCatch { client.jsonRpcRequest<RpcResult<List<ListResult>?>>( RfcRpcRequest( method = "RunTest.List", params = mapOf("run_id" to reportId) ) ).result?.map { listResult -> val testName = TestName(listResult.className, listResult.methodName) SimpleRunTest( id = listResult.id, reportId = reportId, deviceName = requireNotNull(listResult.environment) { "deviceName(environment) is null for test $testName, that's illegal!" }, testCaseId = getTestCaseId(listResult), name = testName, status = deserializeStatus(listResult), stability = determineStability(listResult), groupList = listResult.groupList ?: emptyList(), startTime = listResult.startTime ?: 0, endTime = listResult.endTime ?: 0, buildId = listResult.preparedData?.lastOrNull()?.tcBuild, skipReason = listResult.preparedData?.lastOrNull()?.skipReason, isFinished = listResult.isFinished ?: false, lastAttemptDurationInSeconds = listResult.preparedData?.lastOrNull()?.runDuration ?: -1, externalId = listResult.preparedData?.lastOrNull()?.externalId, description = getDescription(listResult), dataSetNumber = getDataSetNumber(listResult), features = listResult.preparedData?.lastOrNull()?.features ?: emptyList(), tagIds = listResult.preparedData?.lastOrNull()?.tagId ?: emptyList(), featureIds = listResult.preparedData?.lastOrNull()?.featureIds ?: emptyList(), priority = getPriority(listResult), behavior = getBehavior(listResult), kind = listResult.kind?.let { Kind.fromTmsId(it) } ?: Kind.UNKNOWN, flakiness = getFlakiness(listResult) ) } ?: emptyList() } } private fun deserializeStatus(reportModel: ListResult): TestStatus { return when (reportModel.status) { ReportViewerStatus.OK -> TestStatus.Success ReportViewerStatus.FAILURE, ReportViewerStatus.ERROR -> if (reportModel.lastConclusion == ConclusionStatus.OK) { TestStatus.Success } else { val verdict = reportModel.preparedData?.lastOrNull()?.verdict if (verdict.isNullOrBlank()) { // todo fallback TestStatus.Failure("Can't get verdict") } else { TestStatus.Failure(verdict) } } ReportViewerStatus.OTHER, ReportViewerStatus.PANIC, ReportViewerStatus.LOST, null -> TestStatus.Lost ReportViewerStatus.MANUAL -> TestStatus.Manual ReportViewerStatus.SKIP -> TestStatus.Skipped("test ignored") // todo нужен более подробный reason } } private fun determineStability(reportModel: ListResult): Stability { return when { reportModel.attemptsCount == null || reportModel.successCount == null -> Stability.Stable(0, 0) reportModel.attemptsCount < 1 -> // на самом деле не совсем, репортим эту ситуацию как невероятную Stability.Failing(reportModel.attemptsCount) reportModel.successCount > reportModel.attemptsCount -> // на самом деле не совсем, репортим эту ситуацию как невероятную Stability.Stable( reportModel.attemptsCount, reportModel.successCount ) reportModel.successCount == 0 -> Stability.Failing(reportModel.attemptsCount) reportModel.successCount == reportModel.attemptsCount -> Stability.Stable( reportModel.attemptsCount, reportModel.successCount ) // FIXME тут может быть ошибка, т.к. attempt может быть skipped или какой-то другой не-success статус reportModel.successCount < reportModel.attemptsCount -> Stability.Flaky( reportModel.attemptsCount, reportModel.successCount ) else -> Stability.Unknown(reportModel.attemptsCount, reportModel.successCount) } } private fun getDescription(listResult: ListResult): String? { return if (listResult.description.isNullOrBlank()) { listResult.preparedData?.lastOrNull()?.cthulhuTestCase?.description } else { listResult.description } } private fun getDataSetNumber(listResult: ListResult): Int? { return if (listResult.dataSetNumber != null && listResult.dataSetNumber > 0) { listResult.dataSetNumber } else { null } } private fun getTestCaseId(listResult: ListResult): Int? { return try { listResult.testCaseId?.toInt() } catch (e: Exception) { null } } private fun getPriority(listResult: ListResult): TestCasePriority? { return try { listResult.preparedData?.lastOrNull()?.priorityId?.let { TestCasePriority.fromId(it) } } catch (e: Exception) { null } } private fun getBehavior(listResult: ListResult): TestCaseBehavior? { return try { listResult.preparedData?.lastOrNull()?.behaviorId?.let { TestCaseBehavior.fromId(it) } } catch (e: Exception) { null } } private fun getFlakiness(listResult: ListResult) = listResult.preparedData?.lastOrNull()?.let { if (it.isFlaky == true) { Flakiness.Flaky(it.flakyReason ?: "") } else { Flakiness.Stable } } ?: Flakiness.Stable }
8
null
49
412
244c6a588abe14367f927746a8e4832abbc067fa
9,354
avito-android
MIT License
app/src/main/java/com/example/registrationpage/User.kt
MindlessMuse666
855,329,687
false
{"Kotlin": 11825, "Java": 275}
package com.example.registrationpage class User(val id: String?, val login: String, val email: String, val password: String)
0
Kotlin
0
0
e5947301ee5e7bef592eadce04b2a12af6f63609
125
RestaurantApp
MIT License
compiler/testData/ir/irText/types/castsInsideCoroutineInference.kt
brianPlummer
242,364,593
true
{"Markdown": 62, "Gradle": 650, "Gradle Kotlin DSL": 373, "Java Properties": 14, "Shell": 10, "Ignore List": 11, "Batchfile": 9, "Git Attributes": 7, "Protocol Buffer": 11, "Java": 6456, "Kotlin": 56029, "Proguard": 12, "XML": 1574, "Text": 11026, "JavaScript": 270, "JAR Manifest": 2, "Roff": 211, "Roff Manpage": 36, "INI": 147, "AsciiDoc": 1, "SVG": 31, "HTML": 479, "Groovy": 32, "JSON": 106, "JFlex": 3, "Maven POM": 97, "CSS": 4, "JSON with Comments": 7, "Ant Build System": 50, "Graphviz (DOT)": 48, "C": 1, "YAML": 9, "Ruby": 3, "Objective-C": 4, "OpenStep Property List": 2, "Swift": 2, "Scala": 1}
// WITH_RUNTIME import kotlin.experimental.ExperimentalTypeInference private fun CoroutineScope.asFairChannel(flow: Flow<*>): ReceiveChannel<Any> = produce { val channel = channel as ChannelCoroutine<Any> flow.collect { value -> return@collect channel.sendFair(value ?: Any()) } } suspend inline fun <T> Flow<T>.collect(crossinline action: suspend (value: T) -> Unit) {} open class ChannelCoroutine<E> { suspend fun sendFair(element: E) {} } interface CoroutineScope interface Flow<out T> { suspend fun collect(collector: FlowCollector<T>) } interface FlowCollector<in T> { suspend fun emit(value: T) } interface ReceiveChannel<out E> @OptIn(ExperimentalTypeInference::class) fun <E> CoroutineScope.produce( @BuilderInference block: suspend ProducerScope<E>.() -> Unit ): ReceiveChannel<E> = TODO() interface ProducerScope<in E> : CoroutineScope, SendChannel<E> { val channel: SendChannel<E> } interface SendChannel<in E>
0
null
0
0
f487118be5050eac6a8215d3a6667ac7b1b5a337
971
kotlin
Apache License 2.0
libraries/csm.cloud.project.avro/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/topicattachment/message/TopicAttachmentEventAvro.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2021 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.projectmanagement.topicattachment.message import com.bosch.pt.csm.cloud.projectmanagement.topic.messages.TopicAttachmentEventAvro fun TopicAttachmentEventAvro.getIdentifier() = getAggregate().getIdentifier() fun TopicAttachmentEventAvro.getLastModifiedDate() = getAggregate().getLastModifiedDate() fun TopicAttachmentEventAvro.getLastModifiedByUserIdentifier() = getAggregate().getLastModifiedByUserIdentifier() fun TopicAttachmentEventAvro.getTopicIdentifier() = getAggregate().getTopicIdentifier() fun TopicAttachmentEventAvro.getTopicVersion() = getAggregate().getTopicVersion()
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
847
bosch-pt-refinemysite-backend
Apache License 2.0
app/src/main/java/com/redbeanlatte11/factchecker/data/source/local/FactCheckerDataBaseMigration.kt
RedbeanLatte
211,312,029
false
null
package com.redbeanlatte11.factchecker.data.source.local import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase class FactCheckerDataBaseMigration { companion object { val MIGRATION_2_3 = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL(""" CREATE TABLE new_Channels ( kind TEXT NOT NULL, etag TEXT NOT NULL, id TEXT PRIMARY KEY NOT NULL, createdAt TEXT, title TEXT NOT NULL, description TEXT NOT NULL, publishedAt TEXT NOT NULL, thumbnails TEXT NOT NULL, localized TEXT NOT NULL, country TEXT DEFAULT 'KR', viewCount BIGINT NOT NULL, commentCount INTEGER NOT NULL, subscriberCount INTEGER NOT NULL, hiddenSubscriberCount INTEGER NOT NULL, videoCount INTEGER NOT NULL ) """.trimIndent()) database.execSQL(""" INSERT INTO new_Channels ( kind, etag, id, createdAt, title, description, publishedAt, thumbnails, localized, country, viewCount, commentCount, subscriberCount, hiddenSubscriberCount, videoCount ) SELECT kind, etag, id, createdAt, title, description, publishedAt, thumbnails, localized, country, viewCount, commentCount, subscriberCount, hiddenSubscriberCount, videoCount FROM Channels """.trimIndent()) database.execSQL("DROP TABLE Channels") database.execSQL("ALTER TABLE new_Channels RENAME TO Channels") } } } }
0
Kotlin
0
0
0d42e78c809f75455420d4adb0d65b4a6ee9780d
2,149
FactChecker
Apache License 2.0
acornui-utils/src/commonMain/kotlin/com/acornui/math/ColorTransformation.kt
gitter-badger
190,776,981
true
{"Kotlin": 2963922, "JavaScript": 15366, "HTML": 5956, "Java": 4507}
/* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.math import com.acornui.graphic.Color import com.acornui.graphic.ColorRo interface ColorTransformationRo { val matrix: Matrix4Ro val offset: ColorRo } /** * Shaders may support a color transformation matrix. */ class ColorTransformation : ColorTransformationRo { private val _matrix = Matrix4() private val _offset = Color() override var matrix: Matrix4Ro get() = _matrix set(value) { _matrix.set(value) } override var offset: ColorRo get() = _offset set(value) { _offset.set(value) } fun offset(r: Float = 0f, g: Float = 0f, b: Float = 0f, a: Float = 0f): ColorTransformation { _offset.set(r, g, b, a) return this } /** * Sets the transformation matrix values. */ fun setTransformValues(values: FloatArray) { _matrix.set(values) } /** * Sets the transformation matrix values. */ fun setTransformValues(values: List<Float>) { _matrix.set(values) } /** * Multiplies the tint by the given color. */ fun mul(value: ColorRo): ColorTransformation = mul(value.r, value.g, value.b, value.a) /** * Multiplies the tint by the given color. */ fun mul(r: Float = 1f, g: Float = 1f, b: Float = 1f, a: Float = 1f): ColorTransformation { _matrix[Matrix4.M00] *= r _matrix[Matrix4.M11] *= g _matrix[Matrix4.M22] *= b _matrix[Matrix4.M33] *= a return this } fun mul(value: ColorTransformationRo): ColorTransformation { _matrix.mul(value.matrix) _offset.add(value.offset) return this } /** * Sets the tint to the given color. */ fun tint(value: ColorRo): ColorTransformation = tint(value.r, value.g, value.b, value.a) /** * Sets the tint to the given color. */ fun tint(r: Float = 1f, g: Float = 1f, b: Float = 1f, a: Float = 1f): ColorTransformation { _matrix[Matrix4.M00] = r _matrix[Matrix4.M11] = g _matrix[Matrix4.M22] = b _matrix[Matrix4.M33] = a return this } fun idt(): ColorTransformation { _matrix.idt() _offset.clear() return this } fun set(other: ColorTransformationRo): ColorTransformation { _matrix.set(other.matrix) _offset.set(other.offset) return this } companion object { val IDENTITY: ColorTransformationRo = ColorTransformation() } } /** * Sets this color transformation to a sepia transform. */ fun ColorTransformation.sepia(): ColorTransformation { setTransformValues(floatArrayOf( 0.769f, 0.686f, 0.534f, 0.0f, 0.393f, 0.349f, 0.272f, 0.0f, 0.189f, 0.168f, 0.131f, 0.0f, 0.000f, 0.000f, 0.000f, 1.0f )) offset = Color.CLEAR return this } /** * Sets this color transformation to a grayscale transform. */ fun ColorTransformation.grayscale(): ColorTransformation { setTransformValues(floatArrayOf( 0.33f, 0.33f, 0.33f, 0.0f, 0.59f, 0.59f, 0.59f, 0.0f, 0.11f, 0.11f, 0.11f, 0.0f, 0.00f, 0.00f, 0.00f, 1.0f )) offset = Color.CLEAR return this } /** * Sets this color transformation to an invert transform. */ fun ColorTransformation.invert(): ColorTransformation { setTransformValues(floatArrayOf( -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f )) offset = Color(1.0f, 1.0f, 1.0f, 0.0f) return this }
0
Kotlin
0
0
a57100f894721ee342d23fe8cacb3fcbcedbe6dc
3,764
acornui
Apache License 2.0
app/src/main/java/com/coder/ffmpegtest/service/FFmpegCommandService2.kt
AnJoiner
228,573,666
false
null
package com.coder.ffmpegtest.service import android.app.IntentService import android.app.Service import android.content.Intent import android.os.IBinder import com.coder.ffmpeg.jni.FFmpegCommand import java.io.File import java.util.* /** * @author: AnJoiner * @datetime: 20-6-28 */ class FFmpegCommandService2 : IntentService("") { override fun onBind(intent: Intent): IBinder? { return null } override fun onHandleIntent(intent: Intent?) { val videoPath = File(externalCacheDir, "test.mp4").absolutePath val output = File(externalCacheDir, "output3.yuv").absolutePath val cmd = "ffmpeg -y -i %s -an -c:v rawvideo -pixel_format yuv420p %s" val result = String.format(Locale.CHINA, cmd, videoPath, output) val strings: Array<String?> = result.split(" ").toTypedArray() FFmpegCommand.runCmd(strings) } }
28
null
154
820
2e48031c833e37156cd26e3d7c3491ba1c53bdd1
880
FFmpegCommand
Apache License 2.0
PortifolioRusso2/app/src/main/java/com/example/portifoliorusso/TelaPrincipal.kt
BrunTitoWars
727,645,958
false
{"Kotlin": 24990}
package com.example.portifoliorusso import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import java.security.Principal @Composable fun TelaPrincipal(){ val selectedItem = rememberSaveable{ mutableStateOf(0) } Column( verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxSize() ){ BottomNavigation( backgroundColor = Color.White ){ BottomNavigationItem( selected = selectedItem.value == 0, onClick = { selectedItem.value = 0 }, icon = { Icon( painter = painterResource(id = R.drawable.home), contentDescription = "Home", tint = if(selectedItem.value == 0) Color.LightGray else Color.Black ) }, label = { Text( text = "Home", color = if (selectedItem.value == 0) Color.LightGray else Color.Black ) } ) BottomNavigationItem( selected = selectedItem.value == 1, onClick = { selectedItem.value = 1 }, icon = { Icon( painter = painterResource(id = R.drawable.projetos), contentDescription = "Projetos", tint = if(selectedItem.value == 1) Color.LightGray else Color.Black ) }, label = { Text( text = "Projetos", color = if (selectedItem.value == 1) Color.LightGray else Color.Black ) } ) BottomNavigationItem( selected = selectedItem.value == 2, onClick = { selectedItem.value = 2 }, icon = { Icon( painter = painterResource(id = R.drawable.contato), contentDescription = "Contato", tint = if(selectedItem.value == 2) Color.LightGray else Color.Black ) }, label = { Text( text = "Contato", color = if (selectedItem.value == 2) Color.LightGray else Color.Black ) } ) } } when(selectedItem.value){ 0 -> Principal() 1 -> TelasProjetos() 2 -> Tela() } }
0
Kotlin
0
0
a1bdd9ab9f99ac2b9b1d2df63637cca200bd2bc6
3,292
MobileProgramation
MIT License
core/domain/src/main/kotlin/app/surgo/core/domain/observers/ObserveRecommendedArtistSongs.kt
tsukiymk
382,220,719
false
{"Kotlin": 889558, "Shell": 553, "CMake": 252, "C++": 166}
package app.surgo.core.domain.observers import app.surgo.core.data.mappers.DatabaseMapper import app.surgo.core.database.daos.RecommendedDao import app.surgo.core.database.models.Recommended import app.surgo.core.domain.SubjectInteractor import app.surgo.core.model.Song import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.mapLatest import javax.inject.Inject class ObserveRecommendedArtistSongs @Inject constructor( private val recommendedDao: RecommendedDao ) : SubjectInteractor<ObserveRecommendedArtistSongs.Parameters, List<Song>>() { @OptIn(ExperimentalCoroutinesApi::class) override fun createObservable( params: Parameters ): Flow<List<Song>> { return recommendedDao.getObservableRecommendedSongsByParentId( Recommended.ARTIST_SONGS, params.artistId, params.pageSize ).mapLatest { it.map(DatabaseMapper::transformSong) } } data class Parameters( val artistId: Long, val pageSize: Int ) }
0
Kotlin
0
0
99038e0621ecc17e47965c3b352391c6a780f26c
1,070
surgo
Apache License 2.0
app/src/main/java/com/babylon/wallet/android/domain/usecases/GetDAppWithResourcesUseCase.kt
radixdlt
513,047,280
false
{"Kotlin": 4847928, "HTML": 215350, "Ruby": 2757, "Shell": 1963}
package com.babylon.wallet.android.domain.usecases import com.babylon.wallet.android.data.repository.state.StateRepository import com.babylon.wallet.android.domain.model.DAppWithResources import com.radixdlt.sargon.AccountAddress import com.radixdlt.sargon.ResourceAddress import com.radixdlt.sargon.extensions.init import rdx.works.core.domain.resources.Resource import javax.inject.Inject class GetDAppWithResourcesUseCase @Inject constructor( private val stateRepository: StateRepository ) { suspend operator fun invoke( definitionAddress: AccountAddress, needMostRecentData: Boolean ): Result<DAppWithResources> = stateRepository.getDAppsDetails( definitionAddresses = listOf(definitionAddress), isRefreshing = needMostRecentData ).mapCatching { dApps -> val dApp = dApps.first() val claimedResources = dApp.claimedEntities.mapNotNull { runCatching { ResourceAddress.init(it) }.getOrNull() } val resources = stateRepository.getResources( addresses = claimedResources.toSet(), underAccountAddress = null, withDetails = false ).getOrNull().orEmpty() DAppWithResources( dApp = dApp, fungibleResources = resources.filterIsInstance<Resource.FungibleResource>(), nonFungibleResources = resources.filterIsInstance<Resource.NonFungibleResource>() ) } }
8
Kotlin
6
9
04554f86520d77f3e9f27786064c666ad45a3d7c
1,445
babylon-wallet-android
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnTemplateTableFieldLinkContentConfigurationPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.quicksight import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.quicksight.CfnTemplate /** * The URL content (text, icon) for the table link configuration. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.quicksight.*; * TableFieldLinkContentConfigurationProperty tableFieldLinkContentConfigurationProperty = * TableFieldLinkContentConfigurationProperty.builder() * .customIconContent(TableFieldCustomIconContentProperty.builder() * .icon("icon") * .build()) * .customTextContent(TableFieldCustomTextContentProperty.builder() * .fontConfiguration(FontConfigurationProperty.builder() * .fontColor("fontColor") * .fontDecoration("fontDecoration") * .fontSize(FontSizeProperty.builder() * .relative("relative") * .build()) * .fontStyle("fontStyle") * .fontWeight(FontWeightProperty.builder() * .name("name") * .build()) * .build()) * // the properties below are optional * .value("value") * .build()) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-template-tablefieldlinkcontentconfiguration.html) */ @CdkDslMarker public class CfnTemplateTableFieldLinkContentConfigurationPropertyDsl { private val cdkBuilder: CfnTemplate.TableFieldLinkContentConfigurationProperty.Builder = CfnTemplate.TableFieldLinkContentConfigurationProperty.builder() /** * @param customIconContent The custom icon content for the table link content configuration. */ public fun customIconContent(customIconContent: IResolvable) { cdkBuilder.customIconContent(customIconContent) } /** * @param customIconContent The custom icon content for the table link content configuration. */ public fun customIconContent( customIconContent: CfnTemplate.TableFieldCustomIconContentProperty ) { cdkBuilder.customIconContent(customIconContent) } /** * @param customTextContent The custom text content (value, font configuration) for the table * link content configuration. */ public fun customTextContent(customTextContent: IResolvable) { cdkBuilder.customTextContent(customTextContent) } /** * @param customTextContent The custom text content (value, font configuration) for the table * link content configuration. */ public fun customTextContent( customTextContent: CfnTemplate.TableFieldCustomTextContentProperty ) { cdkBuilder.customTextContent(customTextContent) } public fun build(): CfnTemplate.TableFieldLinkContentConfigurationProperty = cdkBuilder.build() }
3
null
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
3,093
awscdk-dsl-kotlin
Apache License 2.0
src/main/kotlin/org/kobdd/Clauses.kt
korifey
381,587,459
false
null
package org.kobdd import kotlin.math.absoluteValue fun popcnt1Cnf(vars: List<Int>) : List<List<Int>> { val res = mutableListOf(vars) for (i in vars.indices) for (j in (i+1) until vars.size) res.add(listOf(-vars[i], -vars[j])) return res } fun atMost1Cnf(vars: List<Int>) : List<List<Int>> { val res = mutableListOf<List<Int>>() for (i in vars.indices) for (j in (i+1) until vars.size) res.add(listOf(-vars[i], -vars[j])) return res } fun printLiteralUnicode(literal: Int) : String { val base = "\ud835\udc65"+ // Mathematical x if (literal < 0) "\u0305" else "" //underscore val subscript = literal.absoluteValue.toString().map { ((0x20 shl 8) + 0x80 + (it - '0')).toChar() //subscript char } return base + subscript.joinToString("") } fun printClauseUnicode(kind: ClauseKind, clause: List<Int>, literal: (Int) -> String = ::printLiteralUnicode) : String { if (clause.isEmpty()) return "\u22A5" //false else return clause.joinToString(kind.joinString) { literal(it)} } fun printCnfUnicode(cnfClauses: Array<List<Int>>, multiline : Boolean = false) : String { if (cnfClauses.isEmpty()) return "\u22A4" //true return cnfClauses.joinToString(ClauseKind.Conjunction.joinString + if (multiline) "\n" else "") { val c = printClauseUnicode(ClauseKind.Disjunction, it) if (multiline) c else "($c)" } }
0
Kotlin
0
2
0ec8dbf69a30407bbbb30ec3c8fe7acd1d0c331a
1,443
kobdd
MIT License
app/src/main/java/com/example/job_portal/recieve_job_list.kt
it-21360978
634,162,466
false
null
package com.example.job_portal import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class recieve_job_list : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_recieve_job_list) } }
0
Kotlin
0
0
032eb410552975eac7d2b0ff433e56dac6c4e3ba
319
Applied
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppselectronicmonitoringcreateanorderapi/client/SercoAuthClient.kt
ministryofjustice
852,871,729
false
{"Kotlin": 150797, "Dockerfile": 1173, "Shell": 630}
package uk.gov.justice.digital.hmpps.hmppselectronicmonitoringcreateanorderapi.client import org.apache.tomcat.util.json.JSONParser import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.web.reactive.function.BodyInserters import org.springframework.web.reactive.function.client.WebClient import reactor.core.publisher.Mono import uk.gov.justice.digital.hmpps.hmppselectronicmonitoringcreateanorderapi.exception.SercoConnectionException import java.util.* @Component class FmsAuthClient( @Value("\${services.serco.auth-url}") authUrl: String, @Value("\${services.serco.client-id}") clientId: String, @Value("\${services.serco.client-secret}") clientSecret: String, @Value("\${services.serco.username}") val username: String, @Value("\${services.serco.password}") val password: String, ) { private val webClient: WebClient = WebClient.builder().baseUrl(authUrl).defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE).build() private val encodedCredentials = Base64.getEncoder().encodeToString("$clientId:$clientSecret".toByteArray()) fun getClientToken(): String { val response = webClient .post() .uri("") .body( BodyInserters.fromFormData("username", username) .with("password", <PASSWORD>) .with("grant_type", "password"), ) .header("Authorization", "Basic $encodedCredentials") .retrieve() .onStatus({ t -> t.value() == 403 }, { Mono.error(SercoConnectionException("Invalid credentials used.")) }) .onStatus({ t -> t.value() == 503 }, { Mono.error(SercoConnectionException("Serco authentication service is unavailable.")) }) .bodyToMono(String::class.java) .block() return JSONParser(response).parseObject()["access_token"].toString() } }
0
Kotlin
0
0
274def026bd004d710b3d57ca62166cb3a872f88
1,986
hmpps-electronic-monitoring-create-an-order-api
MIT License
app/src/main/java/com/bpdsulteng/mobile/ui/login/LoginViewModel.kt
yefim94
440,978,331
false
{"Java Properties": 2, "Gradle": 3, "Shell": 1, "Batchfile": 1, "Text": 1, "Ignore List": 2, "XML": 34, "Proguard": 1, "JSON": 1, "Java": 31, "Kotlin": 47}
package com.bpdsulteng.mobile.ui.login import android.databinding.ObservableField import android.text.Editable import android.text.TextWatcher import android.util.Log import com.bpdsulteng.mobile.ui.base.BaseObservableViewModel import com.google.firebase.auth.FirebaseAuth class LoginViewModel(var auth: FirebaseAuth) : BaseObservableViewModel<LoginNavigator>() { private val email = ObservableField<String>() private val password = ObservableField<String>() fun login() { if (email.get().isNullOrEmpty() || password.get().isNullOrEmpty()) { navigator.onErorrLogin("All fileds are required") } else { auth.signInWithEmailAndPassword(email.get()!!, password.get()!!) .addOnCompleteListener { task -> if (task.isSuccessful) { navigator.onSuccessLogin() } else { Log.d("MessageError", task.exception?.message) navigator.onErorrLogin("Authentication failed!") } } } } fun getEmail() = object : TextWatcher { override fun afterTextChanged(p0: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { email.set(p0.toString()) } } fun getPassword() = object : TextWatcher { override fun afterTextChanged(p0: Editable?) {} override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { password.set(p0.toString()) } } }
1
null
1
1
0df2add1b8699a1f015fe28ef6f2b10a69df45d0
1,784
ChatAppFirebase-1
MIT License
examples/src/main/kotlin/examples/audio/PlayMusic.kt
hiperbou
77,711,558
false
{"Kotlin": 456816, "HTML": 335}
package examples.audio import Phaser.* class PauseAndResume: State() { //window.PhaserGlobal = { disableWebAudio: true } //var game = Phaser.Game(800, 600, Phaser.CANVAS, "phaser-example", { preload: preload, create: create, update: update, render: render }) override fun preload() { game.load.image("disk", "assets/sprites/ra_dont_crack_under_pressure.png") // Firefox doesn"t support mp3 files, so use ogg game.load.audio("boden", arrayOf("assets/audio/bodenstaendig_2000_in_rock_4bit.mp3", "assets/audio/bodenstaendig_2000_in_rock_4bit.ogg")) // game.load.audio("boden", ["assets/audio/time.mp3"]) } lateinit var s:Sprite lateinit var music:Sound override fun create() { game.stage.backgroundColor = "#182d3b" game.input.touch.preventDefault = false music = game.add.audio("boden") music.play() s = game.add.sprite(game.world.centerX, game.world.centerY, "disk") s.anchor.setTo(0.5, 0.5) game.input.onDown.add(this::changeVolume, this) } fun changeVolume(pointer:Pointer) { if (pointer.y < 300) { music.pause() } else { music.resume() } } override fun update() { s.rotation += 0.01 } override fun render() { game.debug.soundInfo(music, 20, 32) } }
2
Kotlin
11
55
18d247ecf44c32f5aca0560dce7727c10dfe196a
1,320
kotlin-phaser
MIT License
designsystem/src/main/java/com/fintonic/designsystem/components/button/Button.kt
carbaj03
505,699,663
false
null
package com.fintonic.designsystem.components.button import androidx.annotation.DrawableRes import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ButtonDefaults import androidx.compose.material.Icon import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Shape import androidx.compose.ui.res.painterResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.fintonic.designsystem.components.text.Text import com.fintonic.designsystem.foundation.* @Composable internal fun Button( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, color: AppColor, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, shape: Shape = RoundedCornerShape(48.dp), content: @Composable RowScope.() -> Unit, ) { ProvideTextStyle( value = AppTheme.typography.bodyM.copy(fontWeight = FontWeight.Bold) ) { Row( modifier = modifier .defaultMinSize( minWidth = ButtonDefaults.MinWidth, minHeight = ButtonDefaults.MinHeight ) .background(color.color, shape) .clip(shape) .clickable( interactionSource = interactionSource, indication = rememberRipple(), enabled = enabled, role = Role.Button, onClick = onClick ) .padding(horizontal = ButtonHorizontalPadding, vertical = ButtonVerticalPadding), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, content = content ) } } @Composable fun ButtonPrimary( text: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, @DrawableRes iconLeft: Int? = null, @DrawableRes iconRight: Int? = null, ) { val colorText = AppTheme.buttonColors.primary.colorFor(enabled) val color = AppTheme.buttonColors.primary(enabled) val textAlign = remember(iconRight, iconLeft) { if (iconRight == null && iconLeft == null) TextAlign.Center else null } Button(onClick = onClick, enabled = enabled, color = color, modifier = modifier) { iconLeft?.let { Icon(painter = painterResource(id = it), contentDescription = null, tint = colorText.color) Spacer(modifier = Modifier.width(8.dp)) } Text(style = appTypography.bodyM, text = text, color = colorText, textAlign = textAlign) iconRight?.let { Spacer(modifier = Modifier.width(8.dp)) Icon(painterResource(id = it), contentDescription = null, tint = colorText.color) } } } @Composable fun ButtonSecondary( text: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, @DrawableRes iconLeft: Int? = null, @DrawableRes iconRight: Int? = null, ) { val colorText = AppTheme.buttonColors.secondary.colorFor(enabled) val color = AppTheme.buttonColors.secondary(enabled) val textAlign = remember(iconRight, iconLeft) { if (iconRight == null && iconLeft == null) TextAlign.Center else null } Button(onClick = onClick, enabled = enabled, color = color, modifier = modifier.border(BorderStroke(1.dp, colorText.color), RoundedCornerShape(48.dp))) { iconLeft?.let { Icon(painter = painterResource(id = it), contentDescription = null, tint = colorText.color) Spacer(modifier = Modifier.width(8.dp)) } Text( style = appTypography.bodyM.copy(fontWeight = FontWeight.Bold), text = text, color = colorText, textAlign = textAlign ) iconRight?.let { Spacer(modifier = Modifier.width(8.dp)) Icon(painterResource(id = it), contentDescription = null, tint = colorText.color) } } } @Composable fun ButtonTertiary( text: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, @DrawableRes iconLeft: Int? = null, @DrawableRes iconRight: Int? = null, ) { val colorText = AppTheme.buttonColors.tertiary.colorFor(enabled) val color = AppTheme.buttonColors.tertiary(enabled) val textAlign = remember(iconRight, iconLeft) { if (iconRight == null && iconLeft == null) TextAlign.Center else null } Button(onClick = onClick, enabled = enabled, color = color, modifier = modifier) { iconLeft?.let { Icon(painter = painterResource(id = it), contentDescription = null, tint = colorText.color) Spacer(modifier = Modifier.width(8.dp)) } Text( style = appTypography.bodyM.copy(fontWeight = FontWeight.Bold), text = text, color = colorText, textAlign = textAlign, maxLines = 1 ) iconRight?.let { Spacer(modifier = Modifier.width(8.dp)) Icon(painterResource(id = it), contentDescription = null, tint = colorText.color) } } } @Composable fun ButtonIcon( @DrawableRes icon: Int, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, colorIcon: AppColor = AppTheme.buttonColors.primary.colorFor(enabled), color: AppColor = AppTheme.buttonColors.primary(enabled), shape: Shape = RoundedCornerShape(48.dp), ) { ButtonIcon(onClick, modifier, enabled, color, shape) { Icon(painter = painterResource(id = icon), contentDescription = null, tint = colorIcon.color) } } @Composable fun ButtonIcon( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, color: AppColor = AppTheme.buttonColors.primary(enabled), shape: Shape = RoundedCornerShape(48.dp), icon: @Composable () -> Unit, ) { Button(onClick = onClick, enabled = enabled, color = color, modifier = modifier, shape = shape) { icon() } } private val ButtonHorizontalPadding = 16.dp private val ButtonVerticalPadding = 12.dp
0
Kotlin
0
0
19caa0c9fcf585f4ff47be2faebbb04609a2d4c5
6,827
DesignSystem
Apache License 2.0
clients/algoliasearch-client-kotlin/client/src/commonMain/kotlin/com/algolia/client/model/predict/DeleteUserProfileResponse.kt
algolia
419,291,903
false
null
/** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */ package com.algolia.client.model.predict import kotlinx.serialization.* import kotlinx.serialization.json.* /** * DeleteUserProfileResponse * * @param user The ID of the user that was deleted. * @param deletedUntil The time the same user ID will be imported again when the data is ingested. */ @Serializable public data class DeleteUserProfileResponse( /** The ID of the user that was deleted. */ @SerialName(value = "user") val user: String, /** The time the same user ID will be imported again when the data is ingested. */ @SerialName(value = "deletedUntil") val deletedUntil: String, )
24
PHP
8
25
549499409f99d38f77b854e70243567e5bf7dae1
791
api-clients-automation
MIT License
animatedbutton/src/main/java/com/mis/animatedbutton/AnimatedButton.kt
Mahmoud-Ibrahim-750
726,336,142
false
{"Kotlin": 28052}
package com.mis.animatedbutton import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.view.View import android.widget.ImageView import android.widget.ProgressBar import android.widget.RelativeLayout import android.widget.TextView import androidx.core.view.setPadding import com.mis.animatedbutton.ViewProvider.createFailureImageView import com.mis.animatedbutton.ViewProvider.createProgressBar import com.mis.animatedbutton.ViewProvider.createSuccessImageView import com.mis.animatedbutton.ViewProvider.createTextView /** * AnimatedButton is a custom view that represents a button with various states and animations. * It includes features such as loading indicator, success, and failure states with corresponding animations. * * @param context The context in which the button is created. * @param attrs The AttributeSet containing custom attributes for the button. * @param defStyleAttr An attribute in the current theme that contains a reference to a style resource defining default values for the view. */ class AnimatedButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RelativeLayout(context, attrs, defStyleAttr), View.OnClickListener { /** * Button states. */ enum class ButtonState { NORMAL, LOADING, SUCCESS, FAILURE } /** * Button transition animation duration. */ private var animationDuration = DEFAULT_TRANSITION_ANIMATION_DURATION /** * Button fade animation duration. */ private var fadeAnimationDuration = DEFAULT_FADE_ANIMATION_DURATION /** * Button current state. */ private var currentState = ButtonState.NORMAL val state: ButtonState get() = currentState /** * Button animator responsible for handling animations. */ private var buttonAnimator: ButtonAnimator /** * Button click listener. */ private var onClickListener: OnClickListener? = null /** * Auto-loading when clicked (default true). */ private var autoLoading = DEFAULT_AUTO_LOADING /** * Button views with an immutable instance exposed for for accessing from the button instance.. */ private val _textView: TextView val textView get() = _textView private val _progressBar: ProgressBar val progressBar get() = _progressBar private val _successImageView: ImageView val successImageView get() = _successImageView private val _failureImageView: ImageView val failureImageView get() = _failureImageView /** * Initialize the AnimatedButton. */ init { // Initialize button isClickable = true isFocusable = true setPadding( TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 12f, resources.displayMetrics ).toInt() ) // Initialize and add child views _textView = createTextView(context, attrs) _progressBar = createProgressBar(context, attrs) _successImageView = createSuccessImageView(context, attrs) _failureImageView = createFailureImageView(context, attrs) addView(_textView) addView(_progressBar) addView(_successImageView) addView(_failureImageView) // set other attributes (e.g., animationDuration) setOtherAttributes(attrs) buttonAnimator = ButtonAnimator(animationDuration, fadeAnimationDuration) this.setOnClickListener(this) } /** * Sets other attributes for the button based on the provided AttributeSet. * * @param attrs The AttributeSet containing custom attributes for the button. */ private fun setOtherAttributes(attrs: AttributeSet?) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.AnimatedButton) typedArray.apply { animationDuration = getInteger(R.styleable.AnimatedButton_animationDuration, animationDuration) fadeAnimationDuration = animationDuration / 2 autoLoading = getBoolean(R.styleable.AnimatedButton_autoLoading, autoLoading) } typedArray.recycle() } /** * Sets the animation duration properties for the button. * * @param duration The duration for button animations. * @return The AnimatedButton instance. */ fun setAnimationDuration(duration: Int): AnimatedButton { animationDuration = duration fadeAnimationDuration = duration / 2 return this } /** * Sets the animation duration properties for the button. * * @param autoLoading The value to be set. * @return The AnimatedButton instance. */ fun setAutoLoading(autoLoading: Boolean): AnimatedButton { this.autoLoading = autoLoading return this } /** * A customizable click listener interface. Overrides the click behavior to apply a unique * behavior for the AnimatedButton */ fun interface OnClickListener { /** * Called when the button is clicked. * * @param view The view that was clicked. */ fun onClick(view: View) } /** * Sets the click listener for the button. * * @param listener The custom click listener to be set. */ fun setOnClickListener(listener: OnClickListener): AnimatedButton { onClickListener = listener return this } /** * Handles the click event for the button. * * @param view The view that was clicked. */ override fun onClick(view: View) { if (!autoLoading) { onClickListener?.onClick(view) return } when (currentState) { ButtonState.NORMAL -> showLoading() // un-reachable cases by default as the button gets disabled ButtonState.LOADING -> {} ButtonState.SUCCESS -> {} ButtonState.FAILURE -> {} } onClickListener?.onClick(view) } private var _isAnimating = false val isAnimating get() = _isAnimating private var nextAnimation: (() -> Unit)? = null /** * Initiates the animation to transition the button from the loading state to the normal state. */ private fun animateLoadingToNormalState() { _isAnimating = true buttonAnimator.buttonExpand(this) buttonAnimator.viewFadeIn(_progressBar) { buttonAnimator.viewFadeOut(_textView) { _isAnimating = false currentState = ButtonState.NORMAL nextAnimation?.invoke() this.isClickable = true } } } /** * Initiates the animation to transition the button from the normal state to the loading state. */ private fun animateNormalToLoadingState() { _isAnimating = true this.isClickable = false currentState = ButtonState.LOADING buttonAnimator.buttonShrink(this) buttonAnimator.viewFadeIn(_textView) { buttonAnimator.viewFadeOut(_progressBar) { _isAnimating = false nextAnimation?.invoke() } } } /** * Initiates the animation to transition the button from the done state to the normal state. */ private fun animateSuccessToNormalState() { _isAnimating = true buttonAnimator.buttonExpand(this) buttonAnimator.viewFadeIn(_successImageView) { buttonAnimator.viewFadeOut(_textView) { _isAnimating = false currentState = ButtonState.NORMAL nextAnimation?.invoke() this.isClickable = true } } } /** * Initiates the animation to transition the button from the loading state to the done state. */ private fun animateLoadingToSuccessState() { _isAnimating = true this.isClickable = false buttonAnimator.viewFadeIn(_progressBar) buttonAnimator.viewFadeOut(_successImageView) { _isAnimating = false currentState = ButtonState.SUCCESS nextAnimation?.invoke() } } /** * Initiates the animation to transition the button from the error state to the normal state. */ private fun animateFailureToNormalState() { _isAnimating = true buttonAnimator.buttonExpand(this) buttonAnimator.viewFadeIn(_failureImageView) { buttonAnimator.viewFadeOut(_textView) { _isAnimating = false currentState = ButtonState.NORMAL nextAnimation?.invoke() this.isClickable = true } } } /** * Initiates the animation to transition the button from the loading state to the error state. */ private fun animateLoadingToFailureState() { _isAnimating = true this.isClickable = false buttonAnimator.viewFadeIn(_progressBar) buttonAnimator.viewFadeOut(_failureImageView) { _isAnimating = false currentState = ButtonState.FAILURE nextAnimation?.invoke() } } fun showLoading() { if (currentState != ButtonState.NORMAL) return if (isAnimating) nextAnimation = { animateNormalToLoadingState() nextAnimation = null } else animateNormalToLoadingState() } fun showSuccess() { if (currentState != ButtonState.LOADING) return if (isAnimating) nextAnimation = { animateLoadingToSuccessState() nextAnimation = null } else animateLoadingToSuccessState() } fun showFailure() { if (currentState != ButtonState.LOADING) return if (isAnimating) nextAnimation = { animateLoadingToFailureState() nextAnimation = null } else animateLoadingToFailureState() } fun showNormal() { when (currentState) { ButtonState.NORMAL -> {} ButtonState.LOADING -> { if (isAnimating) nextAnimation = { animateLoadingToNormalState() nextAnimation = null } else animateLoadingToNormalState() } ButtonState.SUCCESS -> { if (isAnimating) nextAnimation = { animateSuccessToNormalState() nextAnimation = null } else animateSuccessToNormalState() } ButtonState.FAILURE -> { if (isAnimating) nextAnimation = { animateFailureToNormalState() nextAnimation = null } else animateFailureToNormalState() } } } }
0
Kotlin
0
0
8e805eb98f4e81a100d7475ada066cca71357060
11,023
AnimatedButton
MIT License
app/src/main/java/com/github/odaridavid/talkself/ui/user/UserFragmentViewModel.kt
Kod4black
265,308,043
false
null
package com.github.odaridavid.talkself.ui.user import androidx.lifecycle.ViewModel import androidx.lifecycle.asLiveData import com.github.odaridavid.talkself.domain.repository.UserRepository import com.github.odaridavid.talkself.ui.models.UserUiModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.map import javax.inject.Inject @HiltViewModel internal class UserFragmentViewModel @Inject constructor( private val userRepository: UserRepository ) : ViewModel() { // TODO Is this Viewmodel needed or is this done elsewhere too? looks familiar fun getUsersInConversation(conversationId: Int) = userRepository.getUsersInConversation(conversationId).map{ users-> users.map { user -> UserUiModel( conversationId = user.conversationId, userId = user.userId, color = user.color, imageUri = user.imageUri, name = user.name ) } }.asLiveData() }
9
Kotlin
0
3
da3d1c62d6b36fbd96b253521e73130b137c5917
1,059
TalkSelf
Apache License 2.0
app/src/main/java/com/suda/yzune/wakeupschedule/today_appwidget/TodayCourseAppWidget.kt
zxkmm
212,245,556
false
null
package com.suda.yzune.wakeupschedule.today_appwidget import android.annotation.SuppressLint import android.app.AlarmManager import android.app.NotificationManager import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.content.Context.ALARM_SERVICE import android.content.Context.NOTIFICATION_SERVICE import android.content.Intent import android.graphics.BitmapFactory import android.os.Build import androidx.core.app.NotificationCompat import com.suda.yzune.wakeupschedule.AppDatabase import com.suda.yzune.wakeupschedule.R import com.suda.yzune.wakeupschedule.SplashActivity import com.suda.yzune.wakeupschedule.utils.AppWidgetUtils import com.suda.yzune.wakeupschedule.utils.CourseUtils import com.suda.yzune.wakeupschedule.utils.PreferenceUtils import kotlinx.coroutines.* import java.util.* /** * Implementation of App Widget functionality. */ class TodayCourseAppWidget : AppWidgetProvider() { private var job: Job? = null private var calendar = Calendar.getInstance() @SuppressLint("NewApi") override fun onReceive(context: Context, intent: Intent) { if (intent.action == "WAKEUP_REMIND_COURSE") { if (PreferenceUtils.getBooleanFromSP(context, "course_reminder", false)) { val courseName = intent.getStringExtra("courseName") var room = intent.getStringExtra("room") val time = intent.getStringExtra("time") val weekDay = intent.getStringExtra("weekDay") val index = intent.getIntExtra("index", 0) if (room == "") { room = "未知" } val manager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager val cancelIntent = Intent(context, TodayCourseAppWidget::class.java).apply { action = "WAKEUP_CANCEL_REMINDER" putExtra("index", index) } val cancelPendingIntent: PendingIntent = PendingIntent.getBroadcast(context, index, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT) val openIntent = Intent(context, SplashActivity::class.java) val openPendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, openIntent, 0) val notification = NotificationCompat.Builder(context, "schedule_reminder") .setContentTitle("$time $courseName") .setSubText("上课提醒") .setContentText("$weekDay 地点:$room") .setWhen(System.currentTimeMillis()) .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.ic_launcher)) .setSmallIcon(R.drawable.wakeup) .setAutoCancel(false) .setOngoing(PreferenceUtils.getBooleanFromSP(context, "reminder_on_going", false)) .setPriority(NotificationCompat.PRIORITY_MAX) .setDefaults(NotificationCompat.DEFAULT_VIBRATE) .setDefaults(NotificationCompat.DEFAULT_LIGHTS) .setVibrate(longArrayOf(0, 5000, 500, 5000)) .addAction(R.drawable.wakeup, "记得给手机静音哦", cancelPendingIntent) .addAction(R.drawable.wakeup, "我知道啦", cancelPendingIntent) .setContentIntent(openPendingIntent) manager.notify(index, notification.build()) } } if (intent.action == "WAKEUP_CANCEL_REMINDER") { val manager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager manager.cancel(intent.getIntExtra("index", 0)) } super.onReceive(context, intent) } @SuppressLint("NewApi") override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { val dataBase = AppDatabase.getDatabase(context) val widgetDao = dataBase.appWidgetDao() val tableDao = dataBase.tableDao() val baseDao = dataBase.courseBaseDao() val timeDao = dataBase.timeDetailDao() job = GlobalScope.launch(Dispatchers.Main) { val table = async(Dispatchers.IO) { tableDao.getDefaultTableInThread() }.await() if (PreferenceUtils.getBooleanFromSP(context, "course_reminder", false)) { val week = CourseUtils.countWeek(table.startDate) val weekDay = CourseUtils.getWeekday() val before = PreferenceUtils.getIntFromSP(context, "reminder_min", 20) val courseList = async(Dispatchers.IO) { if (week % 2 == 0) { baseDao.getCourseByDayOfTableInThread(CourseUtils.getWeekdayInt(), week, 2, table.id) } else { baseDao.getCourseByDayOfTableInThread(CourseUtils.getWeekdayInt(), week, 1, table.id) } }.await() val timeList = async(Dispatchers.IO) { timeDao.getTimeListInThread(table.timeTable) }.await() val manager = context.getSystemService(ALARM_SERVICE) as AlarmManager courseList.forEachIndexed { index, courseBean -> val time = timeList[courseBean.startNode - 1].startTime val timeSplit = time.split(":") calendar.timeInMillis = System.currentTimeMillis() calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeSplit[0])) calendar.set(Calendar.MINUTE, Integer.parseInt(timeSplit[1])) calendar.add(Calendar.MINUTE, 0 - before) if (calendar.timeInMillis < System.currentTimeMillis()) { return@forEachIndexed } val i = Intent(context, TodayCourseAppWidget::class.java) i.putExtra("courseName", courseBean.courseName) i.putExtra("room", courseBean.room) i.putExtra("weekDay", weekDay) i.putExtra("index", index) i.putExtra("time", time) i.action = "WAKEUP_REMIND_COURSE" val pi = PendingIntent.getBroadcast(context, index, i, PendingIntent.FLAG_UPDATE_CURRENT) when { Build.VERSION.SDK_INT < 19 -> { manager.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pi) } Build.VERSION.SDK_INT in 19..22 -> { manager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pi) } Build.VERSION.SDK_INT >= 23 -> { manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pi) } } } } async(Dispatchers.IO) { for (appWidget in widgetDao.getWidgetsByTypesInThread(0, 1)) { AppWidgetUtils.refreshTodayWidget(context, appWidgetManager, appWidget.id, table) } }.await() job?.cancel() } } override fun onDeleted(context: Context, appWidgetIds: IntArray) { val dataBase = AppDatabase.getDatabase(context) val widgetDao = dataBase.appWidgetDao() job = GlobalScope.launch(Dispatchers.IO) { for (id in appWidgetIds) { widgetDao.deleteAppWidget(id) } job?.cancel() } } }
1
null
1
2
f02ace9de447001524519915b68d4384c725ea05
7,820
WakeupSchedule_Kotlin_Mod4SDAU
Apache License 2.0
server/src/main/kotlin/org/antop/todos/server/Todo.kt
antop-dev
266,660,000
false
{"Vue": 12658, "Kotlin": 11486, "JavaScript": 2286, "TypeScript": 1105, "HTML": 217}
package org.antop.todos.server import com.fasterxml.jackson.annotation.JsonFormat import com.fasterxml.jackson.annotation.JsonIgnore import org.mongodb.morphia.annotations.Entity import org.springframework.data.annotation.Id import org.springframework.hateoas.server.core.Relation import java.time.LocalDateTime /** * 할일 * * @author Antop */ @Entity @Relation(collectionRelation = "todos") class Todo { /** * 아이디 */ @Id var id: String? = null /** * 할일 제목 */ lateinit var title: String /** * 등록 일시 */ @JsonFormat(pattern = "yyyyMMddHHmmss") var created: LocalDateTime = LocalDateTime.now() /** * 완료 여부 */ var done = false /** * 완료 일시 */ @JsonIgnore var doned: LocalDateTime? = null /** * 삭제 여부 */ @JsonIgnore var delete = false /** * 삭제 일시 */ @JsonIgnore var deleted: LocalDateTime? = null override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Todo if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } override fun toString(): String { return "Todo(id=$id, title='$title', created=$created, done=$done, doned=$doned, delete=$delete, deleted=$deleted)" } }
1
Vue
0
0
105d383ef107a645691cfa23a84c0e00da716d2b
1,427
project-todos-202005
MIT License
generators/java/dto/generator/src/main/kotlin/io/github/fomin/oasgen/java/dto/jackson/wstatic/DecimalConverterMatcher.kt
fomin
251,523,799
false
null
package io.github.fomin.oasgen.java.dto.jackson.wstatic import io.github.fomin.oasgen.JsonSchema import io.github.fomin.oasgen.JsonType class DecimalConverterMatcher : ConverterMatcher { class Provider : ConverterMatcherProvider { override val id = "decimal" override fun provide(dtoPackage: String, routesPackage: String) = DecimalConverterMatcher() } override fun match(converterRegistry: ConverterRegistry, jsonSchema: JsonSchema): ConverterWriter? { return if (jsonSchema.type is JsonType.Scalar.STRING && jsonSchema.format == "decimal") object : ConverterWriter { override val jsonSchema = jsonSchema override fun valueType() = "java.math.BigDecimal" override fun parseExpression(valueExpression: String) = "io.github.fomin.oasgen.DecimalConverter.parse($valueExpression)" override fun writeExpression(jsonGeneratorName: String, valueExpression: String) = "io.github.fomin.oasgen.DecimalConverter.write($jsonGeneratorName, $valueExpression)" override fun stringParseExpression(valueExpression: String) = "new java.math.BigDecimal($valueExpression)" override fun stringWriteExpression(valueExpression: String) = "$valueExpression.toPlainString()" override fun generate() = ConverterWriter.Result(emptyList(), emptyList()) } else null } }
6
null
7
3
fad97adaaf88d1e0a65b006e97f6d5a9deaf81f7
1,416
oas-gen
Apache License 2.0
app/src/main/kotlin/lazy/of/go/to/domain/entity/SettingEntity.kt
PieceOfLazy
132,607,214
false
null
package lazy.of.go.to.domain.entity import lazy.of.go.to.type.WeekType data class SettingEntity( val idx: String, val referencePath: String, val recordIdx: String, val name: String, val location: LocationEntity, val monday: SettingTimeEntity, val tuesday: SettingTimeEntity, val wednesday: SettingTimeEntity, val thursday: SettingTimeEntity, val friday: SettingTimeEntity, val saturday: SettingTimeEntity, val sunday: SettingTimeEntity ) { fun getSettingTime(weekType: WeekType): SettingTimeEntity { return when(weekType) { WeekType.MONDAY -> monday WeekType.TUESDAY -> tuesday WeekType.WEDNESDAY -> wednesday WeekType.THURSDAY -> thursday WeekType.FRIDAY -> friday WeekType.SATURDAY -> saturday WeekType.SUNDAY -> sunday } } }
0
Kotlin
0
0
4dc7d0ec14cf1730ff09b9c0ff21801da8142ceb
933
Lazy-Of-Goto
Apache License 2.0
servers/graphql-kotlin-server/src/test/kotlin/com/expediagroup/graphql/server/types/GraphQLServerResponseTest.kt
ExpediaGroup
148,706,161
false
null
/* * Copyright 2021 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.graphql.server.types import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue class GraphQLServerResponseTest { class MyQuery(val foo: Int) private val mapper = jacksonObjectMapper() @Test fun `verify simple serialization`() { val response = GraphQLResponse( data = MyQuery(1) ) val expectedJson = """{"data":{"foo":1}}""" assertEquals(expectedJson, mapper.writeValueAsString(response)) } @Test fun `verify complete serialization`() { val request = GraphQLResponse( data = MyQuery(1), errors = listOf(GraphQLServerError("my error")), extensions = mapOf("bar" to 2) ) val expectedJson = """{"data":{"foo":1},"errors":[{"message":"my error"}],"extensions":{"bar":2}}""" assertEquals(expectedJson, mapper.writeValueAsString(request)) } @Test fun `verify batch response serialization`() { val batchResponse = GraphQLBatchResponse( responses = listOf( GraphQLResponse( data = MyQuery(1) ), GraphQLResponse( data = MyQuery(2), errors = listOf(GraphQLServerError("my error")), extensions = mapOf("bar" to 2) ) ) ) val expectedJson = """[{"data":{"foo":1}},{"data":{"foo":2},"errors":[{"message":"my error"}],"extensions":{"bar":2}}]""" assertEquals(expectedJson, mapper.writeValueAsString(batchResponse)) } @Test fun `verify simple deserialization`() { val input = """{"data":{"foo":1}}""" val response = mapper.readValue<GraphQLServerResponse>(input) assertTrue(response is GraphQLResponse<*>) val data = response.data as? Map<*, *>? assertNotNull(data) assertEquals(1, data["foo"]) assertNull(response.errors) assertNull(response.extensions) } @Test fun `verify complete deserialization`() { val input = """{"data":{"foo":1},"errors":[{"message":"my error"}],"extensions":{"bar":2}}""" val response = mapper.readValue<GraphQLServerResponse>(input) assertTrue(response is GraphQLResponse<*>) val data = response.data as? Map<*, *>? assertNotNull(data) assertEquals(1, data["foo"]) assertEquals(1, response.errors?.size) assertEquals("my error", response.errors?.first()?.message) val extensions = response.extensions assertNotNull(extensions) assertEquals(2, extensions["bar"]) } @Test fun `verify batch response deserialization`() { val serialized = """[{"data":{"foo":1},"errors":[{"message":"my error"}],"extensions":{"bar":2}},{"data":{"foo":2}}]""" val response = mapper.readValue<GraphQLServerResponse>(serialized) assertTrue(response is GraphQLBatchResponse) assertEquals(2, response.responses.size) val first = response.responses[0] val firstData = first.data as? Map<*, *>? assertNotNull(firstData) assertEquals(1, firstData["foo"]) assertEquals(1, first.errors?.size) assertEquals("my error", first.errors?.first()?.message) val extensions = first.extensions assertNotNull(extensions) assertEquals(2, extensions["bar"]) val second = response.responses[1] val secondData = second.data as? Map<*, *>? assertNotNull(secondData) assertEquals(2, secondData["foo"]) assertNull(second.errors) assertNull(second.extensions) } }
68
null
345
1,739
d3ad96077fc6d02471f996ef34c67066145acb15
4,553
graphql-kotlin
Apache License 2.0
app/src/main/java/com/marknkamau/justjava/ui/login/SignInActivity.kt
ashishkharcheiuforks
240,098,537
true
{"Kotlin": 215102}
package com.marknkamau.justjava.ui.login import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.common.api.ApiException import com.marknjunge.core.data.model.Resource import com.marknkamau.justjava.R import com.marknkamau.justjava.ui.completeSignUp.CompleteSignUpActivity import com.marknkamau.justjava.ui.signup.SignUpActivity import com.marknkamau.justjava.utils.* import kotlinx.android.synthetic.main.activity_sign_in.* import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel import timber.log.Timber class SignInActivity : AppCompatActivity() { private val RC_SIGN_IN = 99 private val googleSignInClient: GoogleSignInClient by inject() private val signInViewModel by viewModel<SignInViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_in) initializeLoading() tilEmail.resetErrorOnChange(etEmail) tilPassword.resetErrorOnChange(etPassword) btnSignInGoogle.setOnClickListener { startActivityForResult(googleSignInClient.signInIntent, RC_SIGN_IN) hideKeyboard() } llSignUp.setOnClickListener { startActivity(Intent(this, SignUpActivity::class.java)) finish() } btnSignIn.setOnClickListener { if (isValid()) { hideKeyboard() signIn() } } } private fun initializeLoading() { signInViewModel.loading.observe(this, Observer { loading -> pbLoading.visibility = if (loading) View.VISIBLE else View.GONE }) } public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == RC_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) try { task.getResult(ApiException::class.java)?.idToken?.let { token -> signInWithGoogle(token) } } catch (e: ApiException) { Timber.e("signInResult:failed code=${e.statusCode}") toast("Sign in with Google failed. Use password instead.") } } } private fun signIn() { signInViewModel.signIn(etEmail.trimmedText, etPassword.trimmedText).observe(this, Observer { resource -> when(resource){ is Resource.Success -> finish() is Resource.Failure -> toast(resource.message) } }) } private fun signInWithGoogle(idToken: String) { signInViewModel.signInWithGoogle(idToken).observe(this, Observer { resource -> when (resource) { is Resource.Success -> { if (resource.data.mobileNumber == null) { // Account has just been created CompleteSignUpActivity.start(this, resource.data) } finish() } is Resource.Failure -> { toast(resource.message) } } }) } private fun isValid(): Boolean { var valid = true if (etEmail.trimmedText.isEmpty()) { tilEmail.error = "Required" valid = false } else if (!etEmail.trimmedText.isValidEmail()) { tilEmail.error = "Incorrect email" valid = false } if (etPassword.trimmedText.isEmpty()) { tilPassword.error = "Required" valid = false } return valid } }
0
null
0
0
152ace09c6c807ef0d3ece36a45f71d1e9dd7f99
3,966
JustJava-Android
Apache License 2.0
intellij.tools.ide.starter.bus/testSrc/com/intellij/tools/ide/starter/bus/impl/SubscribingOnlyOnceTest.kt
JetBrains
499,194,001
false
{"Kotlin": 464953, "C++": 3610, "Makefile": 713}
package com.intellij.tools.ide.starter.bus.impl import com.intellij.tools.ide.starter.bus.StarterBus import com.intellij.tools.ide.starter.bus.events.Event import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.util.concurrent.atomic.AtomicInteger class SubscribingOnlyOnceTest { @AfterEach fun afterEach() { StarterBus.unsubscribeAll() } @Test fun `multiple subscription should not work if subscribed only once`() { val obj = Any() val eventProcessedTimes = AtomicInteger() val secondProcessedTimes = AtomicInteger() StarterBus .subscribe(this) { _: Event -> eventProcessedTimes.incrementAndGet() } .subscribe(this) { _: Event -> eventProcessedTimes.incrementAndGet() } .subscribe(obj) { _: Event -> secondProcessedTimes.incrementAndGet() } .subscribe(obj) { _: Event -> secondProcessedTimes.incrementAndGet() } StarterBus.postAndWaitProcessing(Event()) assertEquals(eventProcessedTimes.get(), 1) assertEquals(secondProcessedTimes.get(), 1) eventProcessedTimes.set(0) secondProcessedTimes.set(0) StarterBus.postAndWaitProcessing(Event()) assertEquals(eventProcessedTimes.get(), 1) assertEquals(secondProcessedTimes.get(), 1) } }
0
Kotlin
2
12
a97f38f5ff8b60a10d85491aaa74acec5300ac03
1,368
intellij-ide-starter
Apache License 2.0
app/src/main/java/com/example/project_flow_android/data/model/sign/chat/ChatErrorResponse.kt
DSM-JAVA-PROJECT
392,317,851
false
null
package com.example.project_flow_android.data.model.sign.chat data class ChatErrorResponse( val status : Int, val message : String )
0
Kotlin
0
12
c7b7dea550ffb7025cb1ffd8abc65e8f701ab0e1
141
Project-Flow_Android
MIT License
presentation/src/main/java/com/semicolon/walkhub/ui/challenge/ChallengeFragment.kt
Walkhub
443,006,389
false
null
package com.semicolon.walkhub.ui.challenge import com.semicolon.walkhub.R import com.semicolon.walkhub.databinding.FragmentChallengeBinding import com.semicolon.walkhub.ui.base.BaseFragment class ChallengeFragment : BaseFragment<FragmentChallengeBinding>( R.layout.fragment_challenge ) { override fun initView() { } }
30
Kotlin
1
15
c2d85ebb9ae8b200be22e9029dcfdcbfed19e473
331
walkhub_android
MIT License
analysis/symbol-light-classes/tests/org/jetbrains/kotlin/light/classes/symbol/source/AbstractSymbolLightClassesForSourceTest.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.light.classes.symbol.source import org.jetbrains.kotlin.analysis.api.fir.FirFrontendApiTestConfiguratorService import org.jetbrains.kotlin.light.classes.symbol.base.AbstractSymbolLightClassesTest abstract class AbstractSymbolLightClassesForSourceTest : AbstractSymbolLightClassesTest( FirFrontendApiTestConfiguratorService, EXTENSIONS.FIR_JAVA, stopIfCompilationErrorDirectivePresent = false )
135
Kotlin
4980
40,442
817f9f13b71d4957d8eaa734de2ac8369ad64770
666
kotlin
Apache License 2.0
mps-sync-plugin/src/main/kotlin/org/modelix/mps/sync/plugin/icons/LetterInSquareIcon.kt
modelix
716,210,628
false
{"Kotlin": 1321196, "Shell": 1104, "JavaScript": 497}
/* * Copyright (c) 2023-2024. * * 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.modelix.mps.sync.plugin.icons import com.intellij.ui.Gray import com.intellij.ui.JBColor import org.modelix.kotlin.utils.UnstableModelixFeature import java.awt.Color import java.awt.Component import java.awt.Font import java.awt.Graphics import java.awt.Graphics2D import java.awt.RenderingHints import java.awt.geom.RoundRectangle2D import javax.swing.Icon @UnstableModelixFeature(reason = "The new modelix MPS plugin is under construction", intendedFinalization = "This feature is finalized when the new sync plugin is ready for release.") class LetterInSquareIcon( private val letter: String, private val fontSize: Int, private val offsetX: Float, private val offsetY: Float, private val backgroundColor: Color, private val foregroundColor: Color, ) : Icon { constructor(letter: String, fontSize: Int, offsetX: Float, offsetY: Float) : this( letter, fontSize, offsetX, offsetY, JBColor.BLACK, Gray._200, ) override fun paintIcon(c: Component, graphics: Graphics, x: Int, y: Int) { val g = graphics.create() as Graphics2D try { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON) g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON) g.color = backgroundColor g.fill( RoundRectangle2D.Double( x.toDouble(), y.toDouble(), iconWidth.toDouble(), iconHeight.toDouble(), 5.0, 5.0, ), ) g.font = Font("Arial", Font.BOLD, fontSize) g.color = foregroundColor g.drawString(letter, x + offsetX, y + offsetY) } finally { g.dispose() } } override fun getIconWidth() = 16 override fun getIconHeight() = 16 }
3
Kotlin
0
0
ddaa2a0032ec42bf1a5655f6442a69ae1da70bec
2,683
modelix.mps-plugins
Apache License 2.0
src/main/kotlin/net/devoev/vanilla_cubed/world/gen/feature/ModPlacedFeatures.kt
Devoev
473,273,645
false
{"Kotlin": 259348, "Java": 37528}
package net.devoev.vanilla_cubed.world.gen.feature import net.devoev.vanilla_cubed.VanillaCubed import net.devoev.vanilla_cubed.util.MapInitializer import net.fabricmc.fabric.api.biome.v1.BiomeModifications import net.fabricmc.fabric.api.biome.v1.BiomeSelectionContext import net.fabricmc.fabric.api.biome.v1.BiomeSelectors import net.minecraft.registry.RegistryKey import net.minecraft.registry.RegistryKeys import net.minecraft.util.Identifier import net.minecraft.world.gen.GenerationStep import net.minecraft.world.gen.feature.PlacedFeature import java.util.function.Predicate /** * All placed features. */ object ModPlacedFeatures : MapInitializer<Identifier, PlacedFeatureData>() { init { createEndOreFeature("enderite_ore") } /** * Creates a new entry for the given [biomeSelectors] and [step] under the [name]. */ fun create( name: String, biomeSelectors: Predicate<BiomeSelectionContext>, step: GenerationStep.Feature ) { val id = VanillaCubed.id(name) ModPlacedFeatures[id] = Triple(biomeSelectors, step, placedFeatureKeyOf(id)) } /** * Creates a new placed feature of a [GenerationStep.Feature.UNDERGROUND_ORES] that generates in the end. */ private fun createEndOreFeature(name: String) = create(name, BiomeSelectors.foundInTheEnd(), GenerationStep.Feature.UNDERGROUND_ORES) override fun init() { ModPlacedFeatures.forEach { _, data -> BiomeModifications.addFeature(data.first, data.second, data.third) } } } typealias PlacedFeatureData = Triple<Predicate<BiomeSelectionContext>, GenerationStep.Feature, RegistryKey<PlacedFeature>> /** * Creates a [RegistryKeys.PLACED_FEATURE] for the given [id]. */ private fun placedFeatureKeyOf(id: Identifier) = RegistryKey.of(RegistryKeys.PLACED_FEATURE, id)
0
Kotlin
2
1
faad984d3da21910d0153a0a14b32666cf145751
1,857
vanilla-cubed
MIT License
src/main/kotlin/com/bydgoszcz/worldsimulation/interceptors/Interceptor.kt
mniami
118,100,266
false
null
package com.bydgoszcz.worldsimulation.interceptors import com.bydgoszcz.worldsimulation.worlds.World open class Interceptor { open fun execute(world: World) { } }
0
Kotlin
0
0
4d3e7d7edcb81e36a8eb9b57c86a8a9251a38ca8
173
wypieki
MIT License
src/net/eduard/api/server/EduardPlugin.kt
KingShelby
280,415,351
true
{"XML": 1, "YAML": 8, "Markdown": 2, "Git Attributes": 1, "Text": 2, "Ignore List": 1, "Java": 190, "Kotlin": 78}
package net.eduard.api.server import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit import net.eduard.api.lib.manager.CommandManager import net.eduard.api.lib.menu.Menu import org.bukkit.Bukkit import org.bukkit.configuration.file.FileConfiguration import org.bukkit.event.HandlerList import org.bukkit.plugin.Plugin import org.bukkit.plugin.java.JavaPlugin import net.eduard.api.lib.modules.Mine import net.eduard.api.lib.config.Config import net.eduard.api.lib.database.DBManager import net.eduard.api.lib.database.api.SQLEngineType import net.eduard.api.lib.database.api.SQLManager import net.eduard.api.lib.database.mysql.MySQLOption import net.eduard.api.lib.modules.BukkitTimeHandler import net.eduard.api.lib.modules.Extra import net.eduard.api.lib.storage.StorageAPI /** * Representa os plugins feitos pelo Eduard * * @author Eduard * @version 1.0 * @since 2.0 */ abstract class EduardPlugin : JavaPlugin(), BukkitTimeHandler { var isActivated = false var isLogEnabled = true var isErrorLogEnabled = true var isSQLManagerStarted = false var db = DBManager() @JvmName("getDB") get lateinit var sqlManager: SQLManager protected fun startSQLManager() { isSQLManagerStarted = true var type = if (db.useSQLite()) SQLEngineType.SQLITE else SQLEngineType.MYSQL sqlManager = SQLManager(db.connection, type) } lateinit var configs: Config protected set lateinit var messages: Config protected set /** * @return A [Config] Storage */ lateinit var storage: Config protected set var databaseFile = File(dataFolder, "database.db") /** * @return Se o Plugin é gratuito */ /** * Define se o Plugin é gratuito * * @param free */ var isFree: Boolean = false /** * Verifica se tem algo dentro da config.yml * * @return Se a a config.yml tem configurações */ val isEditable: Boolean get() = !configs.keys.isEmpty() val autoSaveSeconds: Long get() = configs.getLong("auto-save-seconds")!! val isAutoSaving: Boolean get() = configs.getBoolean("auto-save") val backupTime: Long get() = configs.getLong("backup-time")!! val backupLastTime: Long get() = configs.getLong("backup-lasttime")!! val autoSaveLastTime: Long get() = configs.getLong("auto-save-lasttime")!! val backupTimeUnitType: TimeUnit get() = TimeUnit.valueOf(configs.getString("backup-timeunit-type").toUpperCase()) val canBackup: Boolean get() = configs.getBoolean("backup") fun getString(path: String): String { return configs.message(path) } /** * Config padrão do spigot não funciona com Config */ override fun getConfig(): FileConfiguration? { return null } /** * Envia mensagem para o console caso as Log Normais esteja ativada para ele * * @param msg Mensagem */ fun log(msg: String) { if (isLogEnabled) Bukkit.getConsoleSender().sendMessage("§b[$name] §f$msg") } /** * Envia mensagem para o console caso as Log de Erros esteja ativada para ele * * @param msg Mensagem */ fun error(msg: String) { if (isErrorLogEnabled) Bukkit.getConsoleSender().sendMessage("§b[$name] §c$msg") } override fun getPluginConnected(): Plugin { return this } protected fun reloadVars() { configs = Config(this, "config.yml") messages = Config(this, "messages.yml") storage = Config(this, "storage.yml") } /** * Necessario fazer super.onEnable() para poder suportar os comandos do PlugMan * <br></br> /plugman unload NomePlugin * <br></br>/plugman load NomePlugin */ override fun onEnable() { reloadVars() mainConfig() reloadDBManager() log("Foi ativado na v" + description.version + " um plugin " + (if (isFree) "§aGratuito" else "§bPago") + "§f feito pelo Eduard") } protected fun mainConfig() { configs.add("auto-save", false) configs.add("auto-save-seconds", 60) configs.add("auto-save-lasttime", Extra.getNow()) configs.add("backup", false) configs.add("backup-lasttime", Extra.getNow()) configs.add("backup-time", 1) configs.add("backup-timeunit-type", "MINUTES") configs.add("database", db) configs.saveConfig() } fun reloadDBManager() { db = configs.get("database", DBManager::class.java) } fun registerPackage(packname: String) { StorageAPI.registerPackage(javaClass, packname) } fun getClasses(pack: String): List<Class<*>> { return Mine.getClasses(this, pack) } fun autosave() { configs.set("auto-save-lasttime", Extra.getNow()) save() } /** * Deleta os ultimos backups */ private fun deleteLastBackups() { val pasta = File(dataFolder, "/backup/") pasta.mkdirs() var lista = mutableListOf(*pasta.listFiles()!!) lista.sortBy { it.lastModified() } //lista = lista.stream().sorted(Comparator.comparing<File, Long>(Function<File, Long> { return@Function it.lastModified() })).collect<List<File>, Any>(Collectors.toList()) for (i in lista.size - 10 downTo 0) { val arquivo = lista[i] Extra.deleteFolder(arquivo) if (arquivo.exists()) arquivo.delete() } } /** * Deleta os backups dos dias anteriores */ fun deleteOldBackups() { val pasta = File(dataFolder, "/backup/") pasta.mkdirs() var lista = listOf(*pasta.listFiles()!!) lista.filter { it.lastModified() + TimeUnit.DAYS.toMillis(1) <= System.currentTimeMillis() } .forEach { Extra.deleteFolder(it) if (it.exists()) it.delete() } } /** * Gera backup dos arquivos config.yml, storage.yml e por ultimo database.db */ fun backup() { configs.set("backup-lasttime", Extra.getNow()) try { val pasta = File(dataFolder, "/backup/" + DATE_TIME_FORMATER.format(System.currentTimeMillis()) + "/") pasta.mkdirs() if (storage.existConfig() && storage.keys.isNotEmpty()) { Files.copy(storage.file.toPath(), Paths.get(pasta.path, storage.name)) } if (configs.existConfig() && storage.keys.isNotEmpty()) { Files.copy(configs.file.toPath(), Paths.get(pasta.path, configs.name)) } if (databaseFile.exists()) { Files.copy(databaseFile.toPath(), Paths.get(pasta.path, databaseFile.name)) } } catch (e: IOException) { e.printStackTrace() } } fun unregisterServices() { Bukkit.getServicesManager().unregisterAll(this) } fun unregisterListeners() { HandlerList.unregisterAll(this) } fun unregisterTasks() { Bukkit.getScheduler().cancelTasks(this) } fun unregisterStorableClasses() { StorageAPI.unregisterStorables(this) } fun unregisterMenus() { for (menu in Menu.registeredMenus.toList()) { if (this == menu.pluginInstance) { menu.unregisterListener() } } } fun unregisterCustomCommands() { CommandManager.commandsRegistred.values.forEach { cmd -> if (this == cmd.pluginInstance) { cmd.unregisterCommand() } } } fun disconnectDB() { db.closeConnection() } override fun onDisable() { disconnectDB() unregisterServices() unregisterListeners() unregisterTasks() unregisterStorableClasses() unregisterMenus() unregisterCustomCommands() log("Foi desativado na v" + description.version + " um plugin " + if (isFree) "§aGratuito" else "§bPago") } open fun save() { } open fun reload() {} open fun onActivation(){} open fun configDefault() { } fun getBoolean(path: String): Boolean { return configs.getBoolean(path) } fun getInt(path: String): Int { return configs.getInt(path)!! } fun getDouble(path: String): Double { return configs.getDouble(path)!! } fun message(path: String): String { return messages.message(path) } fun getMessages(path: String): List<String> { return messages.getMessages(path) } companion object { private val DATE_TIME_FORMATER = SimpleDateFormat("dd-MM-YYYY HH-mm-ss") } }
0
null
0
0
cea30c5464c2b45b5ffc003bc84aa189ebf7440b
9,036
EduardAPI
MIT License
src/test/java/de/tillhub/paymentengine/data/LavegoReceiptBuilderTest.kt
tillhub
578,173,252
false
{"Kotlin": 70997}
package de.tillhub.paymentengine.data import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe class LavegoReceiptBuilderTest : FunSpec({ test("LavegoReceiptBuilder by line merchant first") { val target = LavegoReceiptBuilder(true) target.addLine("merchantReceipt") target.addLine("") target.addLine("customerReceipt") target.customerReceipt shouldBe "customerReceipt\n" target.merchantReceipt shouldBe "merchantReceipt\n" } test("LavegoReceiptBuilder by line customer first") { val target = LavegoReceiptBuilder(false) target.addLine("customerReceipt") target.addLine("") target.addLine("merchantReceipt") target.customerReceipt shouldBe "customerReceipt\n" target.merchantReceipt shouldBe "merchantReceipt\n" } test("LavegoReceiptBuilder by block merchant first") { val target = LavegoReceiptBuilder(true) target.addBlock("merchantReceipt") target.addBlock("customerReceipt") target.customerReceipt shouldBe "customerReceipt" target.merchantReceipt shouldBe "merchantReceipt" } test("LavegoReceiptBuilder by block customer first") { val target = LavegoReceiptBuilder(false) target.addBlock("customerReceipt") target.addBlock("merchantReceipt") target.customerReceipt shouldBe "customerReceipt" target.merchantReceipt shouldBe "merchantReceipt" } })
0
Kotlin
0
0
b6010a13622b2649f3cca1105d0b93104fd3b4c3
1,492
payment-engine
MIT License
runtime/src/main/java/jp/co/soramitsu/runtime/multiNetwork/runtime/RuntimeFilesCache.kt
soramitsu
278,060,397
false
{"Kotlin": 5738291, "Java": 18796}
package jp.co.soramitsu.runtime.multiNetwork.runtime import jp.co.soramitsu.common.interfaces.FileProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext private const val METADATA_FILE_MASK = "metadata_%s" class RuntimeFilesCache( private val fileProvider: FileProvider ) { suspend fun getChainMetadata(chainId: String): String { return readCacheFile(METADATA_FILE_MASK.format(chainId)) } suspend fun saveChainMetadata(chainId: String, metadata: String) { val fileName = METADATA_FILE_MASK.format(chainId) writeToCacheFile(fileName, metadata) } private suspend fun writeToCacheFile(name: String, content: String) { return withContext(Dispatchers.IO) { val file = fileProvider.getFileInInternalCacheStorage(name) file.writeText(content) } } private suspend fun readCacheFile(name: String): String { return withContext(Dispatchers.IO) { val file = fileProvider.getFileInInternalCacheStorage(name) file.readText() } } }
15
Kotlin
30
89
812c6ed5465d19a0616865cbba3e946d046720a1
1,097
fearless-Android
Apache License 2.0
app/src/main/java/cn/rongcloud/voiceroomdemo/throwable/RoomNotExistException.kt
rongcloud
379,792,178
false
null
/* * Copyright © 2021 RongCloud. All rights reserved. */ package cn.rongcloud.voiceroomdemo.throwable /** * @author gusd * @Date 2021/06/23 */ class RoomNotExistException:Throwable("Room does not exist")
0
null
6
6
46ba4e512f2a5b24c9000a6b37ccc12a52857468
210
rongcloud-scene-android-demo
Apache License 2.0
presentation/src/main/java/com/anytypeio/anytype/presentation/relations/providers/ObjectRelationProvider.kt
anyproto
647,371,233
false
{"Kotlin": 11264576, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.presentation.relations.providers import com.anytypeio.anytype.core_models.Id import com.anytypeio.anytype.core_models.Key import com.anytypeio.anytype.core_models.ObjectWrapper import kotlinx.coroutines.flow.Flow interface ObjectRelationProvider { suspend fun get(relation: Key): ObjectWrapper.Relation suspend fun getById(relation: Id) : ObjectWrapper.Relation fun observe(relation: Key): Flow<ObjectWrapper.Relation> fun observeAll(): Flow<List<ObjectWrapper.Relation>> companion object { /** * Provider which should provide intrinsic relations of given object, be it a page, a collection or a set */ const val INTRINSIC_PROVIDER_TYPE = "object-intrinsic-relations-provider" /** * Provider which should provide relations for a data view from an object, a collection or a set. */ const val DATA_VIEW_PROVIDER_TYPE = "data-view-relations-provider" } }
40
Kotlin
40
480
c593cceeb82c6429173019cd7cbe4fcd90faeb5a
976
anytype-kotlin
RSA Message-Digest License
api/registry/src/test/kotlin/org/rsmod/api/registry/loc/LocRegistryAddTest.kt
rsmod
293,875,986
false
{"Kotlin": 1817705}
package org.rsmod.api.registry.loc import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Test import org.rsmod.api.testing.factory.collisionFactory import org.rsmod.api.testing.factory.locFactory import org.rsmod.api.testing.factory.locRegistryFactory import org.rsmod.api.testing.factory.locTypeListFactory import org.rsmod.api.testing.factory.mediumBlockWalk import org.rsmod.api.testing.factory.smallBlockRange import org.rsmod.api.testing.factory.smallBlockWalk import org.rsmod.game.loc.LocAngle import org.rsmod.game.loc.LocEntity import org.rsmod.game.loc.LocShape import org.rsmod.game.loc.LocZoneKey import org.rsmod.game.map.collision.get import org.rsmod.game.map.collision.set import org.rsmod.map.CoordGrid import org.rsmod.map.zone.ZoneGrid import org.rsmod.map.zone.ZoneKey import org.rsmod.pathfinder.flag.CollisionFlag class LocRegistryAddTest { @Test fun `add loc to empty coord grid`() { val types = locTypeListFactory.createDefault() val loc = locFactory.create(types.smallBlockWalk()) val collision = collisionFactory.create() val registry = locRegistryFactory.create(collision) check(registry.count() == 0) registry.add(loc) assertEquals(1, registry.count()) assertEquals(1, registry.spawnedLocs.locCount()) assertEquals(1, registry.findAll(ZoneKey.from(loc.coords)).count()) assertEquals(loc, registry.findAll(ZoneKey.from(loc.coords)).single()) assertNotEquals(0, collision[loc.coords] and CollisionFlag.LOC) } @Test fun `add locs to different coordinates in same zone`() { val types = locTypeListFactory.createDefault() val loc1 = locFactory.create(types.smallBlockWalk(), CoordGrid.ZERO) val loc2 = locFactory.create(types.smallBlockWalk(), CoordGrid.ZERO.translateX(1)) val collision = collisionFactory.create() val registry = locRegistryFactory.create(collision) check(registry.count() == 0) registry.add(loc1) registry.add(loc2) assertEquals(2, registry.count()) assertEquals(2, registry.spawnedLocs.locCount()) assertEquals(2, registry.findAll(ZoneKey.from(loc1.coords)).count()) assertEquals(setOf(loc1, loc2), registry.findAll(ZoneKey.from(loc1.coords)).toSet()) assertNotEquals(0, collision[loc1.coords] and CollisionFlag.LOC) assertNotEquals(0, collision[loc2.coords] and CollisionFlag.LOC) } @Test fun `add loc on top of same-layer spawned loc`() { val types = locTypeListFactory.createDefault() val loc1 = locFactory.create(types.smallBlockWalk()) val loc2 = locFactory.create(types.smallBlockRange()) val collision = collisionFactory.create() val registry = locRegistryFactory.create(collision) check(registry.count() == 0) registry.add(loc1) check(registry.count() == 1) registry.add(loc2) assertEquals(1, registry.count()) assertEquals(1, registry.spawnedLocs.locCount()) assertEquals(1, registry.findAll(ZoneKey.from(loc2.coords)).count()) assertEquals(loc2, registry.findAll(ZoneKey.from(loc2.coords)).single()) assertNotEquals(0, collision[loc2.coords] and CollisionFlag.LOC) } @Test fun `add loc on top of differing layer spawned loc`() { val types = locTypeListFactory.createDefault() val loc1 = locFactory.create(types.smallBlockWalk(), shape = LocShape.GroundDecor) val loc2 = locFactory.create(types.smallBlockRange(), shape = LocShape.CentrepieceStraight) val collision = collisionFactory.create() val registry = locRegistryFactory.create(collision) check(registry.count() == 0) registry.add(loc1) check(registry.count() == 1) registry.add(loc2) assertEquals(2, registry.count()) assertEquals(2, registry.spawnedLocs.locCount()) assertEquals(2, registry.findAll(ZoneKey.from(loc2.coords)).count()) assertEquals(setOf(loc1, loc2), registry.findAll(ZoneKey.from(loc1.coords)).toSet()) } @Test fun `add spawned loc on top of map loc with identical entity metadata`() { val types = locTypeListFactory.createDefault() val collision = collisionFactory.create() val registry = locRegistryFactory.create(collision) collision.allocateIfAbsent(0, 0, 0) val mapLoc = locFactory.create(types.mediumBlockWalk()) val spawnLoc = locFactory.create(types.mediumBlockWalk()) // Manually set the map loc. val zoneKey = ZoneKey.from(mapLoc.coords) val locZoneKey = LocZoneKey(ZoneGrid.from(mapLoc.coords), mapLoc.layer) registry.mapLocs[zoneKey, locZoneKey] = LocEntity(mapLoc.id, mapLoc.shape, mapLoc.angle) check(collision[mapLoc.coords] and CollisionFlag.LOC == 0) registry.add(spawnLoc) // As `spawnLoc` is the exact same (type, shape, and angle) as the already-existing map loc, // we don't want to add it to spawned locs. Though we will still perform other logic, such // as applying its collision data. assertEquals(0, registry.spawnedLocs.locCount()) assertNotEquals(0, collision[mapLoc.coords] and CollisionFlag.LOC) } @Test fun `add spawned loc on top of map loc with differing entity metadata`() { val types = locTypeListFactory.createDefault() val collision = collisionFactory.create() val registry = locRegistryFactory.create(collision) collision.allocateIfAbsent(0, 0, 0) val mapLoc = locFactory.create(types.mediumBlockWalk(), angle = LocAngle.West) val spawnLoc = locFactory.create(types.mediumBlockWalk(), angle = LocAngle.South) // Manually set the map loc. val zoneKey = ZoneKey.from(mapLoc.coords) val locZoneKey = LocZoneKey(ZoneGrid.from(mapLoc.coords), mapLoc.layer) registry.mapLocs[zoneKey, locZoneKey] = LocEntity(mapLoc.id, mapLoc.shape, mapLoc.angle) check(collision[mapLoc.coords] and CollisionFlag.LOC == 0) check(registry.spawnedLocs.locCount() == 0) check(registry.findAll(zoneKey).single() == mapLoc) registry.add(spawnLoc) assertEquals(1, registry.spawnedLocs.locCount()) assertNotEquals(0, collision[mapLoc.coords] and CollisionFlag.LOC) // Map loc should be masked by newly-spawned loc and be ignored during find lookups. assertEquals(setOf(spawnLoc), registry.findAll(zoneKey).toSet()) } }
0
Kotlin
64
95
3ba446ed70bcde0870ef431e1a8527efc6837d6c
6,641
rsmod
ISC License
src/main/kotlin/endertitan/echolib/resourcenetworks/value/IntValue.kt
ender-titan1
708,160,119
false
{"Kotlin": 61673}
package endertitan.echolib.resourcenetworks.value import net.minecraft.nbt.CompoundTag import javax.naming.OperationNotSupportedException class IntValue(var value: Int) : INetworkValue { override fun plus(other: INetworkValue): INetworkValue { if (other is IntValue) return IntValue(value + other.value) throw OperationNotSupportedException("Attempted to add two INetworkValues of different types") } override operator fun plusAssign(other: INetworkValue) { if (other is IntValue) value += other.value } override fun minus(other: INetworkValue): INetworkValue { if (other is IntValue) return IntValue(value - other.value) throw OperationNotSupportedException("Attempted to subtract two INetworkValues of different types") } override operator fun minusAssign(other: INetworkValue) { if (other is IntValue) value -= other.value } override operator fun div(amount: Int): INetworkValue { return IntValue(value / amount) } override operator fun compareTo(other: INetworkValue): Int { if (other !is IntValue) throw OperationNotSupportedException("Attempted to compare two INetworkValues of different types") return value.compareTo(other.value) } override fun toString(): String { return value.toString() } override fun saveNBT(prefix: String, nbt: CompoundTag): CompoundTag { nbt.putInt("$prefix-value", value); return nbt } override fun loadNBT(prefix: String, nbt: CompoundTag) { value = nbt.getInt("$prefix-value") } companion object { fun zero(): IntValue { return IntValue(0) } } }
4
Kotlin
0
1
68fffbd70ab43f250826af7d8cf64541b1faf8c6
1,766
echo-lib
MIT License
app/src/main/java/kunimitsova/valbee/datetimecalculator/ui/LayoutSetup.kt
kunimitsova
520,752,504
false
{"Kotlin": 126038, "HTML": 2824}
package kunimitsova.valbee.datetimecalculator.ui enum class LayoutSetup { ONE_COLUMN, ONE_ROW, TWO_COLUMNS, TWO_ROWS }
0
Kotlin
0
0
2b44e2e37202efb1189e7f0e5dae7c95949dba09
135
DateTimeCalculator
Apache License 2.0
flutter_training/assignment_03/android/app/src/main/kotlin/com/example/helloflutter/MainActivity.kt
Lennoard
503,149,805
false
{"Dart": 130642, "Kotlin": 2222, "Swift": 404, "Objective-C": 38}
package com.example.helloflutter import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
1346b0aa83f6ec8563c29372ac994306dc579f30
129
MobileDevelopmentSamples
The Unlicense
Pharmacy/app/src/main/java/com/example/myapplication/map.kt
dannysir
501,272,913
false
{"Kotlin": 19987}
package com.example.myapplication import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.net.Uri import android.os.Build import android.os.Bundle import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.drawerlayout.widget.DrawerLayout import com.gun0912.tedpermission.PermissionListener import com.gun0912.tedpermission.normal.TedPermission import net.daum.mf.map.api.MapView class map : AppCompatActivity() { @SuppressLint("MissingPermission") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.map) val menu_btn = findViewById<Button>(R.id.butMenu) val tomain_btn = findViewById<Button>(R.id.tomain) val tobook_btn = findViewById<Button>(R.id.tobook) val topharmacy_btn = findViewById<Button>(R.id.topharmacy) val intent_toexplain = Intent(this, explain::class.java) val intent_tomain = Intent(this, MainActivity::class.java) val intent_tobook = Intent(this, like_med::class.java) val intent_topharmacy = Intent(this, map::class.java) //메뉴 바 클릭시 펼쳐짐 menu_btn.setOnClickListener { val drawerLayout = findViewById<DrawerLayout>(R.id.drawerLayout) if (!drawerLayout.isDrawerOpen(Gravity.LEFT)) { drawerLayout.openDrawer(Gravity.LEFT) } else { drawerLayout.closeDrawer(Gravity.LEFT) } } // to main tomain_btn.setOnClickListener { startActivity(intent_tomain) } // to book tobook_btn.setOnClickListener { startActivity(intent_tobook) } // to pharmacy topharmacy_btn.setOnClickListener { startActivity(intent_topharmacy) } val permissionlistener: PermissionListener = object : PermissionListener { override fun onPermissionGranted() { // Toast.makeText(this@map, "Permission Granted", Toast.LENGTH_SHORT).show() val lm: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager; val gpsLocationListener: LocationListener = object : LocationListener { override fun onLocationChanged(location: Location) { val provider = location.provider val lon = location.longitude val lat = location.latitude val altitude = location.altitude val browserIntent = Intent( Intent.ACTION_VIEW, Uri.parse("kakaomap://search?q=약국&p=$lat,$lon") ) startActivity(browserIntent) } override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {} override fun onProviderEnabled(provider: String) {} override fun onProviderDisabled(provider: String) {} } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, 1f, gpsLocationListener ) lm.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 1000, 1f, gpsLocationListener ) } } override fun onPermissionDenied(deniedPermissions: List<String?>) { Toast.makeText( this@map, "Permission Denied\n$deniedPermissions", Toast.LENGTH_SHORT ).show() } } TedPermission.create() .setPermissionListener(permissionlistener) .setRationaleMessage("카카오맵을 사용하기 위해서는 위치 접근 권한이 필요해요") .setDeniedMessage("왜 거부하셨어요...\n하지만 [설정] > [권한] 에서 권한을 허용할 수 있어요.") .setPermissions( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ).check() val mapView = MapView(this) val mapViewContainer = findViewById<View>(R.id.map_view) as ViewGroup mapViewContainer.addView(mapView) } }
0
Kotlin
0
0
87708ce3a38d2a1b4a5142d5ac75d896100a7a35
4,868
pharmacy
Apache License 2.0
library_permiss/src/main/java/com/knight/kotlin/library_permiss/delegate/PermissionDelegateImplV34.kt
KnightAndroid
438,567,015
false
{"Kotlin": 1817006, "Java": 294277, "HTML": 46741, "C": 31605, "C++": 14920, "CMake": 5510}
package com.knight.kotlin.library_permiss.delegate import android.app.Activity import android.content.Context import androidx.annotation.RequiresApi import com.knight.kotlin.library_permiss.AndroidVersion import com.knight.kotlin.library_permiss.permissions.Permission import com.knight.kotlin.library_permiss.utils.PermissionUtils /** * Author:Knight * Time:2024/1/10 16:18 * Description:PermissionDelegateImplV34 */ @RequiresApi(api = AndroidVersion.ANDROID_14) open class PermissionDelegateImplV34 : PermissionDelegateImplV33(){ override fun isGrantedPermission( context: Context, permission: String ): Boolean { if (PermissionUtils.equalsPermission(permission, Permission.READ_MEDIA_VISUAL_USER_SELECTED)) { return PermissionUtils.checkSelfPermission(context, Permission.READ_MEDIA_VISUAL_USER_SELECTED); } // 如果用户授予了部分照片访问,那么 READ_MEDIA_VISUAL_USER_SELECTED 权限状态是授予的,而 READ_MEDIA_IMAGES 权限状态是拒绝的 if (PermissionUtils.equalsPermission(permission, Permission.READ_MEDIA_IMAGES) && !PermissionUtils.checkSelfPermission(context, Permission.READ_MEDIA_IMAGES)) { return PermissionUtils.checkSelfPermission(context, Permission.READ_MEDIA_VISUAL_USER_SELECTED); } // 如果用户授予了部分视频访问,那么 READ_MEDIA_VISUAL_USER_SELECTED 权限状态是授予的,而 READ_MEDIA_VIDEO 权限状态是拒绝的 if (PermissionUtils.equalsPermission(permission, Permission.READ_MEDIA_VIDEO) && !PermissionUtils.checkSelfPermission(context, Permission.READ_MEDIA_VIDEO)) { return PermissionUtils.checkSelfPermission(context, Permission.READ_MEDIA_VISUAL_USER_SELECTED); } return super.isGrantedPermission(context, permission); } override fun isDoNotAskAgainPermission( activity: Activity, permission: String ): Boolean { if (PermissionUtils.equalsPermission(permission, Permission.READ_MEDIA_VISUAL_USER_SELECTED)) { return !PermissionUtils.checkSelfPermission(activity, permission) && !PermissionUtils.shouldShowRequestPermissionRationale(activity, permission) } return super.isDoNotAskAgainPermission(activity, permission) } }
0
Kotlin
3
6
d423c9cf863afe8e290c183b250950bf155d1f84
2,221
wanandroidByKotlin
Apache License 2.0
trixnity-client/trixnity-client-media-okio/src/commonMain/kotlin/net/folivo/trixnity/client/media/okio/ByteFlowExtensions.kt
benkuly
330,904,570
false
{"Kotlin": 3995644, "JavaScript": 5163, "TypeScript": 2906, "CSS": 1454, "Dockerfile": 1243}
package net.folivo.trixnity.client.media.okio import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.withContext import net.folivo.trixnity.core.BYTE_ARRAY_FLOW_CHUNK_SIZE import net.folivo.trixnity.core.ByteArrayFlow import okio.* import kotlin.coroutines.CoroutineContext suspend fun ByteArrayFlow.writeToSink(sink: BufferedSink, coroutineContext: CoroutineContext = defaultContext): Unit = withContext(coroutineContext) { collect { sink.write(it) } } suspend fun BufferedSource.readByteFlow(coroutineContext: CoroutineContext = defaultContext): ByteArrayFlow = flow { while (exhausted().not()) { emit(readByteArray(BYTE_ARRAY_FLOW_CHUNK_SIZE.coerceAtMost(buffer.size))) } }.flowOn(coroutineContext) suspend fun FileSystem.writeByteFlow( path: Path, content: ByteArrayFlow, coroutineContext: CoroutineContext = defaultContext, ): Unit = withContext(coroutineContext) { sink(path).buffer().use { sink -> content.writeToSink(sink, coroutineContext) } } suspend fun FileSystem.readByteFlow( path: Path, coroutineContext: CoroutineContext = defaultContext, ): ByteArrayFlow? = if (exists(path)) flow { source(path).buffer().use { source -> emitAll(source.readByteFlow(coroutineContext)) } }.flowOn(coroutineContext) else null
0
Kotlin
3
27
f1c7c171e98a379abfd7baa079a36794aba652ca
1,484
trixnity
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/ses/S3ActionConfigDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.ses import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.ses.S3ActionConfig /** * S3Action configuration. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.ses.*; * S3ActionConfig s3ActionConfig = S3ActionConfig.builder() * .bucketName("bucketName") * // the properties below are optional * .kmsKeyArn("kmsKeyArn") * .objectKeyPrefix("objectKeyPrefix") * .topicArn("topicArn") * .build(); * ``` */ @CdkDslMarker public class S3ActionConfigDsl { private val cdkBuilder: S3ActionConfig.Builder = S3ActionConfig.builder() /** * @param bucketName The name of the Amazon S3 bucket that you want to send incoming mail to. */ public fun bucketName(bucketName: String) { cdkBuilder.bucketName(bucketName) } /** * @param kmsKeyArn The customer master key that Amazon SES should use to encrypt your emails * before saving them to the Amazon S3 bucket. */ public fun kmsKeyArn(kmsKeyArn: String) { cdkBuilder.kmsKeyArn(kmsKeyArn) } /** @param objectKeyPrefix The key prefix of the Amazon S3 bucket. */ public fun objectKeyPrefix(objectKeyPrefix: String) { cdkBuilder.objectKeyPrefix(objectKeyPrefix) } /** * @param topicArn The ARN of the Amazon SNS topic to notify when the message is saved to the * Amazon S3 bucket. */ public fun topicArn(topicArn: String) { cdkBuilder.topicArn(topicArn) } public fun build(): S3ActionConfig = cdkBuilder.build() }
3
null
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
1,937
awscdk-dsl-kotlin
Apache License 2.0
feature-account-impl/src/main/java/jp/co/soramitsu/feature_account_impl/presentation/account/create/CreateAccountFragment.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.feature_account_impl.presentation.account.create import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.dialog.MaterialAlertDialogBuilder import jp.co.soramitsu.common.base.BaseFragment import jp.co.soramitsu.common.di.FeatureUtils import jp.co.soramitsu.common.utils.hideSoftKeyboard import jp.co.soramitsu.common.utils.nameInputFilters import jp.co.soramitsu.common.utils.onTextChanged import jp.co.soramitsu.common.view.bottomSheet.list.dynamic.DynamicListBottomSheet import jp.co.soramitsu.core.model.Node import jp.co.soramitsu.feature_account_api.di.AccountFeatureApi import jp.co.soramitsu.feature_account_impl.R import jp.co.soramitsu.feature_account_impl.di.AccountFeatureComponent import jp.co.soramitsu.feature_account_impl.presentation.common.mixin.api.chooseNetworkClicked import jp.co.soramitsu.feature_account_impl.presentation.view.advanced.network.NetworkChooserBottomSheetDialog import jp.co.soramitsu.feature_account_impl.presentation.view.advanced.network.model.NetworkModel import kotlinx.android.synthetic.main.fragment_create_account.accountNameInput import kotlinx.android.synthetic.main.fragment_create_account.networkInput import kotlinx.android.synthetic.main.fragment_create_account.nextBtn import kotlinx.android.synthetic.main.fragment_create_account.toolbar class CreateAccountFragment : BaseFragment<CreateAccountViewModel>() { companion object { private const val KEY_FORCED_NETWORK_TYPE = "forced_network_type" fun getBundle(networkType: Node.NetworkType?): Bundle { return Bundle().apply { putSerializable(KEY_FORCED_NETWORK_TYPE, networkType) } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_create_account, container, false) } override fun initViews() { toolbar.setHomeButtonListener { viewModel.homeButtonClicked() } nextBtn.setOnClickListener { accountNameInput.hideSoftKeyboard() viewModel.nextClicked() } accountNameInput.content.onTextChanged { viewModel.accountNameChanged(it) } networkInput.setWholeClickListener { viewModel.chooseNetworkClicked() } accountNameInput.content.filters = nameInputFilters() } override fun inject() { val networkType = argument<Node.NetworkType?>(KEY_FORCED_NETWORK_TYPE) FeatureUtils.getFeature<AccountFeatureComponent>(context!!, AccountFeatureApi::class.java) .createAccountComponentFactory() .create(this, networkType) .inject(this) } override fun subscribe(viewModel: CreateAccountViewModel) { viewModel.nextButtonEnabledLiveData.observe { nextBtn.isEnabled = it } viewModel.showScreenshotsWarningEvent.observeEvent { showScreenshotWarningDialog() } viewModel.selectedNetworkLiveData.observe { networkInput.setTextIcon(it.networkTypeUI.icon) networkInput.setMessage(it.name) } networkInput.isEnabled = viewModel.isNetworkTypeChangeAvailable viewModel.networkChooserEvent.observeEvent(::showNetworkChooser) } private fun showNetworkChooser(payload: DynamicListBottomSheet.Payload<NetworkModel>) { NetworkChooserBottomSheetDialog( requireActivity(), payload, viewModel.selectedNetworkLiveData::setValue ).show() } private fun showScreenshotWarningDialog() { MaterialAlertDialogBuilder(context, R.style.AlertDialogTheme) .setTitle(R.string.common_no_screenshot_title) .setMessage(R.string.common_no_screenshot_message) .setPositiveButton(R.string.common_ok) { dialog, _ -> dialog?.dismiss() viewModel.screenshotWarningConfirmed(accountNameInput.content.text.toString()) } .show() } }
3
Kotlin
11
51
ce2d28cd14a57c20f4d1757a89e23d2709c63072
4,154
fearless-Android
Apache License 2.0
android-uitests/testData/CatchUp/app/src/main/kotlin/io/sweers/catchup/util/coroutines/LifecycleScoper.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) 2018 Zac Sweers * * 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.sweers.catchup.util.coroutines import android.os.Looper import androidx.lifecycle.GenericLifecycleObserver import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.launch /** * Scope suspending work to run when [LifecycleOwner] is at least at state [whenAtLeast]. * Runs [begin] each time [LifecycleOwner] reaches the target state and cancels the scope * whenever it falls beneath the target state again. Useful for connections and subscriptions. * * Adapted from https://gist.github.com/adamp/c6d213af7d931b0f00e9ca396d57dacd */ fun LifecycleOwner.liveCoroutineScope( whenAtLeast: Lifecycle.State = Lifecycle.State.STARTED, begin: suspend CoroutineScope.() -> Unit ) { val scoper = LifecycleScoper(whenAtLeast, begin) if (Looper.myLooper() == Looper.getMainLooper()) { lifecycle.addObserver(scoper) } else { GlobalScope.launch(Dispatchers.Main) { lifecycle.addObserver(scoper) } } } private class LifecycleScoper( whenAtLeast: Lifecycle.State, private val begin: suspend CoroutineScope.() -> Unit ) : GenericLifecycleObserver { private val upEvent = eventUpTo(whenAtLeast) private val downEvent = eventDownFrom(whenAtLeast) private var scope: CoroutineScope? = null override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { if (event == upEvent) { val scope = newScope() this.scope = scope scope.launch(start = CoroutineStart.UNDISPATCHED) { begin() } } else if (event == downEvent) { scope?.apply { coroutineContext.cancel() scope = null } } } private fun newScope() = CoroutineScope(Dispatchers.Main + SupervisorJob()) private fun eventUpTo(state: Lifecycle.State): Lifecycle.Event = when (state) { Lifecycle.State.CREATED -> Lifecycle.Event.ON_CREATE Lifecycle.State.STARTED -> Lifecycle.Event.ON_START Lifecycle.State.RESUMED -> Lifecycle.Event.ON_RESUME else -> throw IllegalArgumentException("no valid up event to reach $state") } private fun eventDownFrom(state: Lifecycle.State): Lifecycle.Event = when (state) { Lifecycle.State.CREATED -> Lifecycle.Event.ON_DESTROY Lifecycle.State.STARTED -> Lifecycle.Event.ON_STOP Lifecycle.State.RESUMED -> Lifecycle.Event.ON_PAUSE else -> throw IllegalArgumentException("no valid down event from $state") } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
3,243
android
Apache License 2.0
app/src/main/java/com/maliks/applocker/xtreme/di/module/ActivityBuilderModule.kt
gamerz1990
873,653,054
false
{"Kotlin": 357861, "Java": 1255}
package com.maliks.applocker.xtreme.di.module import com.maliks.applocker.xtreme.di.scope.ActivityScope import com.maliks.applocker.xtreme.ui.background.BackgroundsActivity import com.maliks.applocker.xtreme.ui.browser.BrowserActivity import com.maliks.applocker.xtreme.ui.callblocker.CallBlockerActivity import com.maliks.applocker.xtreme.ui.intruders.IntrudersPhotosActivity import com.maliks.applocker.xtreme.ui.main.MainActivity import com.maliks.applocker.xtreme.ui.newpattern.CreateNewPatternActivity import com.maliks.applocker.xtreme.ui.overlay.activity.OverlayValidationActivity import com.maliks.applocker.xtreme.ui.permissions.PermissionsActivity import com.maliks.applocker.xtreme.ui.vault.VaultActivity import dagger.Module import dagger.android.ContributesAndroidInjector /** * Created by mertsimsek on 12/11/2017. */ @Module abstract class ActivityBuilderModule { @ActivityScope @ContributesAndroidInjector(modules = [FragmentBuilderModule::class, DialogFragmentBuilderModule::class]) abstract fun mainActivity(): MainActivity @ActivityScope @ContributesAndroidInjector(modules = [FragmentBuilderModule::class, DialogFragmentBuilderModule::class]) abstract fun backgroundActivity(): BackgroundsActivity @ActivityScope @ContributesAndroidInjector(modules = [FragmentBuilderModule::class, DialogFragmentBuilderModule::class]) abstract fun browserActivity(): BrowserActivity @ActivityScope @ContributesAndroidInjector(modules = [FragmentBuilderModule::class, DialogFragmentBuilderModule::class]) abstract fun vaultActivity(): VaultActivity @ActivityScope @ContributesAndroidInjector(modules = [FragmentBuilderModule::class, DialogFragmentBuilderModule::class]) abstract fun callBlockerActivity(): CallBlockerActivity @ActivityScope @ContributesAndroidInjector(modules = [FragmentBuilderModule::class, DialogFragmentBuilderModule::class]) abstract fun intrudersPhotosActivity(): IntrudersPhotosActivity @ActivityScope @ContributesAndroidInjector abstract fun permissionsActivity(): PermissionsActivity @ActivityScope @ContributesAndroidInjector abstract fun createNewPatternActivity(): CreateNewPatternActivity @ActivityScope @ContributesAndroidInjector abstract fun fingerPrintOverlayActivity(): OverlayValidationActivity }
0
Kotlin
0
0
db1181e64ce277c498bc52472010da1efcf4c52e
2,356
applocker
Apache License 2.0
app/src/main/java/com/compose/wanandroid/ui/page/profile/coin/CoinPage.kt
MarkMjw
489,531,108
false
{"Kotlin": 333340}
package com.compose.wanandroid.ui.page.profile.coin import androidx.compose.foundation.layout.* import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.HelpOutline import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.compose.wanandroid.ui.widget.StatePage import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.itemsIndexed import com.compose.wanandroid.data.model.Coin import com.compose.wanandroid.data.model.Link import com.compose.wanandroid.logic.back import com.compose.wanandroid.logic.navigate import com.compose.wanandroid.ui.common.* import com.compose.wanandroid.ui.page.main.Page import com.compose.wanandroid.ui.theme.AppTheme import com.compose.wanandroid.ui.theme.textThird import com.compose.wanandroid.ui.widget.RefreshList fun NavGraphBuilder.coinGraph(controller: NavController) { composable( route = Page.Coin.route + "/{count}", arguments = listOf(navArgument("count") { type = NavType.IntType }) ) { val count = it.arguments?.getInt("count", 0) ?: 0 CoinPage(controller, count) } } @Composable fun CoinPage( controller: NavController, coinCount: Int, viewModel: CoinViewModel = viewModel() ) { val pagingItems = viewModel.pager.collectAsLazyPagingItems() AppScaffold( topBar = { AppTitleBar( text = "我的积分($coinCount)", onBack = { controller.back() }, trailingActions = { IconButton( onClick = { controller.navigate( Page.Web.route, Link(title = "本站积分规则", url = "https://www.wanandroid.com/blog/show/2653", addHistory = false) ) }, content = { Icon( imageVector = Icons.Outlined.HelpOutline, tint = AppTheme.colors.onPrimary, contentDescription = null ) } ) } ) } ) { StatePage( modifier = Modifier.fillMaxSize(), state = viewModel.getPageState(pagingItems), onRetry = { pagingItems.retry() } ) { RefreshList( lazyPagingItems = pagingItems, modifier = Modifier.fillMaxSize(), itemContent = { itemsIndexed(pagingItems) { _: Int, coin: Coin? -> if (coin != null) { CoinItem(coin) } } } ) } } } @Composable fun CoinItem(coin: Coin) { Row( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Column( modifier = Modifier .weight(1f) .align(Alignment.CenterVertically) ) { Text( text = coin.title, color = AppTheme.colors.textPrimary, fontSize = 15.sp, maxLines = 3, overflow = TextOverflow.Ellipsis ) Text( text = coin.time, fontSize = 12.sp, color = AppTheme.colors.textThird, overflow = TextOverflow.Ellipsis, maxLines = 2, modifier = Modifier.padding(top = 5.dp) ) } Text( text = coin.count, fontSize = 15.sp, color = AppTheme.colors.highlight, fontWeight = FontWeight.SemiBold, overflow = TextOverflow.Ellipsis, maxLines = 1, modifier = Modifier.align(Alignment.CenterVertically) ) } }
0
Kotlin
0
6
0e5e7033cab4b69120ddb7ad6e88eba465b46978
4,618
wanandroid-compose
Apache License 2.0
app/src/main/java/com/ik3130/betterdose/data/models/Report.kt
IvanKolanovic
624,046,561
false
null
package com.ik3130.betterdose.data.models import java.time.LocalDateTime data class Report( val id: String, val userId: String, val mood: String, val reportedAt: LocalDateTime )
0
Kotlin
0
0
db3efa648e55d25a12c799fe5f281fba45bfd6c1
196
BetterDose-android
Apache License 2.0
kotlin-electron/src/jsMain/generated/electron/core/ProcessMetricType.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package electron.core @seskar.js.JsVirtual sealed external interface ProcessMetricType { companion object { @seskar.js.JsValue("Browser") val Browser: ProcessMetricType @seskar.js.JsValue("Tab") val Tab: ProcessMetricType @seskar.js.JsValue("Utility") val Utility: ProcessMetricType @seskar.js.JsValue("Zygote") val Zygote: ProcessMetricType @seskar.js.JsValue("Sandbox helper") val SandboxHelper: ProcessMetricType @seskar.js.JsValue("GPU") val GPU: ProcessMetricType @seskar.js.JsValue("Pepper Plugin") val PepperPlugin: ProcessMetricType @seskar.js.JsValue("Pepper Plugin Broker") val PepperPluginBroker: ProcessMetricType @seskar.js.JsValue("Unknown") val Unknown: ProcessMetricType } }
40
Kotlin
165
1,347
997ed3902482883db4a9657585426f6ca167d556
907
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/fireblade/effectivecamera/graphics/common/IRenderEffect.kt
The-Shader
199,191,831
false
null
package com.fireblade.effectivecamera.graphics.common interface IRenderEffect { fun render(captureRequested: Boolean = false) }
1
Kotlin
0
0
ffdb0b5c542e4d0f624f9d1953b2681ac74b3c52
130
EffectiveCamera
MIT License
kotlin-grass-core/src/jvmTest/kotlin/io.blackmo18.kotlin.grass.core/TestCustomDataTypes.kt
blackmo18
271,912,019
false
null
package io.blackmo18.kotlin.grass.core import io.kotlintest.specs.WordSpec import kotlin.test.BeforeTest import kotlin.test.assertEquals import kotlin.test.assertNotEquals @ExperimentalStdlibApi class TestCustomDataTypes: WordSpec() { private val dataTypes = CustomDataTypeTest() @BeforeTest fun cleanUp() { CustomDataTypes.clearMapTypes() } init { "validate custom data types" should { "retrieve data" { CustomDataTypes.addDataTypes(dataTypes) assertNotEquals(0, dataTypes.mapTypes.size) } "clear data" { CustomDataTypes.addDataTypes(dataTypes) CustomDataTypes.clearMapTypes() assertEquals(0, CustomDataTypes.mapType.size) } } } }
0
Kotlin
7
38
e6378425e3d9832e7c073e90ff11ced288091c37
791
kotlin-grass
Apache License 2.0
core/model/src/main/java/com/msg/model/remote/model/auth/AuthTokenModel.kt
GSM-MSG
700,744,250
false
{"Kotlin": 552939, "CMake": 1834, "C++": 258}
package com.msg.model.remote.model.auth import com.msg.model.remote.enumdatatype.Authority data class AuthTokenModel( val accessToken: String, val refreshToken: String, val accessExpiredAt: String, val refreshExpiredAt: String, val authority: Authority )
10
Kotlin
0
16
0c78dc7edaedd568e8c47c8cd6a10fccb8f56242
278
Bitgoeul-Android
MIT License
data/src/test/java/com/android/template/data/repositories/preferences/PreferencesRepositoryImplTest.kt
huuphuoc1396
831,253,387
false
{"Kotlin": 72529}
package com.android.template.data.repositories.preferences import app.cash.turbine.test import com.android.template.data.storages.datastore.preferences.PreferencesDataStore import io.kotest.matchers.shouldBe import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import org.junit.Test internal class PreferencesRepositoryImplTest { private val preferencesDataStore = mockk<PreferencesDataStore>() private val repository = PreferencesRepositoryImpl(preferencesDataStore) @Test fun `isFirstRun returns true`() = runTest { // Given val expected = true every { preferencesDataStore.isFirstRun() } returns flowOf(expected) // When val result = repository.isFirstRun() // Then result.test { expectMostRecentItem() shouldBe expected } } @Test fun `isFirstRun returns false`() = runTest { // Given val expected = false every { preferencesDataStore.isFirstRun() } returns flowOf(expected) // When val result = repository.isFirstRun() // Then result.test { expectMostRecentItem() shouldBe expected } } @Test fun `setFirstRun is true`() = runTest { // Given val isFirstRun = true coEvery { preferencesDataStore.setFirstRun(isFirstRun) } returns Unit // When repository.setFirstRun(isFirstRun) // Then coVerify { preferencesDataStore.setFirstRun(isFirstRun) } } @Test fun `setFirstRun is false`() = runTest { // Given val isFirstRun = false coEvery { preferencesDataStore.setFirstRun(isFirstRun) } returns Unit // When repository.setFirstRun(isFirstRun) // Then coVerify { preferencesDataStore.setFirstRun(isFirstRun) } } }
0
Kotlin
0
11
a20cfd36e8630082948acb49daad4a8df4804282
1,961
android-template
MIT License
gradle-plugins/compose/src/main/kotlin/org/jetbrains/compose/resources/GenerateResClassTask.kt
JetBrains
293,498,508
false
{"Kotlin": 1921608, "Shell": 12615, "Dockerfile": 6720, "JavaScript": 5187, "Swift": 2823, "Ruby": 2627, "Java": 1964, "HTML": 1834, "PowerShell": 1708, "Groovy": 1415}
package org.jetbrains.compose.resources import org.gradle.api.file.DirectoryProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputDirectory import org.jetbrains.compose.internal.IdeaImportTask import java.io.File internal abstract class GenerateResClassTask : IdeaImportTask() { companion object { private const val RES_FILE_NAME = "Res" } @get:Input abstract val packageName: Property<String> @get:Input @get:Optional abstract val packagingDir: Property<File> @get:Input abstract val makeAccessorsPublic: Property<Boolean> @get:OutputDirectory abstract val codeDir: DirectoryProperty override fun safeAction() { val dir = codeDir.get().asFile dir.deleteRecursively() dir.mkdirs() logger.info("Generate $RES_FILE_NAME.kt") val pkgName = packageName.get() val moduleDirectory = packagingDir.getOrNull()?.let { it.invariantSeparatorsPath + "/" } ?: "" val isPublic = makeAccessorsPublic.get() getResFileSpec(pkgName, RES_FILE_NAME, moduleDirectory, isPublic).writeTo(dir) } }
64
Kotlin
1174
16,150
7e9832f6494edf3e7967082c11417e78cfd1d9d0
1,207
compose-multiplatform
Apache License 2.0
Sample/src/main/java/com/angcyo/dsladapter/dsl/DslDemoItem.kt
kingconan
223,879,716
false
null
package com.angcyo.dsladapter.dsl import com.angcyo.dsladapter.DslAdapterItem import com.angcyo.dsladapter.DslViewHolder import com.angcyo.dsladapter.demo.R /** * * Email:<EMAIL> * @author angcyo * @date 2019/10/16 * Copyright (c) 2019 ShenZhen O&M Cloud Co., Ltd. All rights reserved. */ class DslDemoItem : DslAdapterItem() { init { itemLayoutId = R.layout.item_demo_list } var itemText: CharSequence? = null override fun onItemBind( itemHolder: DslViewHolder, itemPosition: Int, adapterItem: DslAdapterItem ) { super.onItemBind(itemHolder, itemPosition, adapterItem) itemHolder.tv(R.id.text_view)?.text = itemText } }
0
null
0
1
e4a32119532b977bc8fc465703684ff59c3bbbf3
702
DslAdapter
MIT License
phoenix-android/src/main/kotlin/fr/acinq/phoenix/android/components/contact/ContactPhotoView.kt
ACINQ
192,964,514
false
{"C": 8424033, "Kotlin": 2796821, "Swift": 1884690, "Java": 39996, "HTML": 13403, "Dockerfile": 3585, "CMake": 2276, "CSS": 504}
/* * Copyright 2024 ACINQ SAS * * 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 fr.acinq.phoenix.android.components.contact import android.Manifest import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.net.Uri import android.provider.Settings import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.core.content.FileProvider import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import com.google.accompanist.permissions.shouldShowRationale import fr.acinq.lightning.utils.currentTimestampMillis import fr.acinq.phoenix.android.BuildConfig import fr.acinq.phoenix.android.R import fr.acinq.phoenix.android.isDarkTheme import fr.acinq.phoenix.android.utils.gray70 import fr.acinq.phoenix.android.utils.gray800 import org.slf4j.LoggerFactory import java.io.File import java.io.FileOutputStream @OptIn(ExperimentalPermissionsApi::class) @Composable fun ContactPhotoView( photoUri: String?, name: String?, onChange: ((String?) -> Unit)?, imageSize: Dp = 96.dp, borderSize: Dp = 1.dp, ) { val context = LocalContext.current var isProcessing by remember { mutableStateOf(false) } var tempPhotoUri by remember { mutableStateOf<Uri?>(null) } var fileName by remember(photoUri) { mutableStateOf(photoUri) } val bitmap: ImageBitmap? = remember(fileName) { fileName?.let { ContactPhotoHelper.getPhotoForFile(context, it) } } var cameraAccessDenied by remember { mutableStateOf(false) } val cameraPermissionState = rememberPermissionState(Manifest.permission.CAMERA) val cameraLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.TakePicture(), onResult = { val cacheUri = tempPhotoUri if (it && cacheUri != null) { val newFileName = ContactPhotoHelper.createPermaContactPicture(context, cacheUri) fileName = newFileName if (fileName != null) { onChange?.invoke(fileName) } } isProcessing = false } ) val color = if (isDarkTheme) gray800 else gray70 Box { Surface( shape = CircleShape, border = BorderStroke(width = borderSize, color = color), elevation = 0.dp, modifier = if (onChange != null) { Modifier.clickable( role = Role.Button, onClick = { Toast.makeText(context, "\uD83D\uDEA7 Coming soon!", Toast.LENGTH_SHORT).show() return@clickable if (isProcessing) return@clickable if (cameraPermissionState.status.isGranted) { isProcessing = true if (tempPhotoUri == null) { ContactPhotoHelper.createTempContactPictureUri(context)?.let { tempPhotoUri = it cameraLauncher.launch(tempPhotoUri) } } else { cameraLauncher.launch(tempPhotoUri) } } else { cameraAccessDenied = cameraPermissionState.status.shouldShowRationale if (cameraAccessDenied) { context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { data = Uri.fromParts("package", context.packageName, null) }) } else { cameraPermissionState.launchPermissionRequest() } } }, enabled = !isProcessing ) } else Modifier ) { if (bitmap == null) { Image( painter = painterResource(id = R.drawable.ic_contact_placeholder), colorFilter = ColorFilter.tint(color), contentDescription = name, modifier = Modifier.size(imageSize) ) if (cameraAccessDenied) { Text(text = stringResource(id = R.string.scan_request_camera_access_denied), style = MaterialTheme.typography.subtitle2) } } else { Image( bitmap = bitmap, contentDescription = name, modifier = Modifier.size(imageSize), contentScale = ContentScale.Crop, ) } } } } object ContactPhotoHelper { val log = LoggerFactory.getLogger(this::class.java) fun createTempContactPictureUri( context: Context, ): Uri? { val cacheContactsDir = File(context.cacheDir, "contacts") if (!cacheContactsDir.exists()) cacheContactsDir.mkdir() return try { val tempFile = File.createTempFile("contact_", ".png", cacheContactsDir) tempFile.deleteOnExit() FileProvider.getUriForFile(context, "${BuildConfig.APPLICATION_ID}.provider", tempFile) } catch (e: Exception) { log.error("failed to write temporary file for contact: {}", e.localizedMessage) null } } fun createPermaContactPicture( context: Context, tempFileUri: Uri, ): String? { val contactsDir = File(context.filesDir, "contacts") if (!contactsDir.exists()) contactsDir.mkdir() return try { val bitmap = context.contentResolver.openInputStream(tempFileUri)?.use { BitmapFactory.decodeStream(it) } ?: return null val scale = 480f / Math.max(bitmap.width, bitmap.height) val matrix = Matrix().apply { postScale(scale, scale) } val scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, false) val photoFile = File(contactsDir, "contact_${currentTimestampMillis()}.jpg") FileOutputStream(photoFile).use { scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, it) } photoFile.name } catch (e: Exception) { log.error("failed to write contact photo to disk: {}", e.localizedMessage) null } } fun getPhotoForFile( context: Context, fileName: String ): ImageBitmap? { val contactsDir = File(context.filesDir, "contacts") if (!contactsDir.exists() || !contactsDir.canRead()) return null return try { val photoFile = File(contactsDir, fileName) val content = photoFile.readBytes() BitmapFactory.decodeByteArray(content, 0, content.size).asImageBitmap() } catch (e: Exception) { log.info("could not read contact photo=$fileName: ", e.localizedMessage) null } } }
100
C
96
666
011c8b85f16ea9ad322cbbba2461439c5e2b0aed
9,042
phoenix
Apache License 2.0
app/src/main/java/com/arthurdw/threedots/ui/screens/Scan.kt
Arthurdw
636,324,418
false
null
package com.arthurdw.threedots.ui.screens import android.widget.Toast import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import com.arthurdw.threedots.R import com.arthurdw.threedots.ThreeDotsLayout import com.arthurdw.threedots.components.QRScanner import com.arthurdw.threedots.ui.Screens import com.arthurdw.threedots.utils.State @Composable @androidx.annotation.OptIn(androidx.camera.core.ExperimentalGetImage::class) fun ScanScreen() { val context = LocalContext.current val navController = State.LocalNavController.current val foundMessage = stringResource(R.string.qr_code_found) ThreeDotsLayout(stringResource(R.string.scan)) { QRScanner( onScan = { Toast.makeText(context, foundMessage, Toast.LENGTH_SHORT).show() navController.navigate(Screens.Overview.withArgs(it)) } ) } }
0
Kotlin
0
0
4a5be3f88b1e083e39aee51e1d8c6fcf46414f00
969
3dots
MIT License
src/main/kotlin/com/example/trackme/adapter/out/TrackedPersistenceAdapter.kt
MaciejPawlik
676,031,496
false
{"Kotlin": 9939}
package com.example.trackme.adapter.out import com.example.trackme.application.port.out.AddTrackedPort import com.example.trackme.domain.Tracked import org.springframework.stereotype.Component @Component class TrackedPersistenceAdapter(val mongoRepository: TrackedMongoRepository, val mapper: TrackedMapper) : AddTrackedPort { override fun addTracked(tracked: Tracked): String = mongoRepository.save(mapper.mapToTrackedEntity(tracked)).trackedId ?: "" }
0
Kotlin
0
0
63f2faed4d6043cceb503a4d648ea9b9b1a37fce
459
trackme
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/TheaterMasks.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.TheaterMasks: ImageVector get() { if (_theaterMasks != null) { return _theaterMasks!! } _theaterMasks = Builder(name = "TheaterMasks", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(21.153f, 1.403f) curveToRelative(-1.615f, -0.567f, -3.217f, -0.964f, -4.761f, -1.181f) curveTo(14.853f, 0.007f, 13.201f, -0.052f, 11.486f, 0.046f) curveToRelative(-1.997f, 0.116f, -3.653f, 1.619f, -3.937f, 3.573f) lineToRelative(-0.213f, 1.465f) curveToRelative(-1.478f, 0.222f, -3.008f, 0.608f, -4.552f, 1.149f) curveTo(0.893f, 6.897f, -0.273f, 8.803f, 0.012f, 10.764f) lineToRelative(0.954f, 6.557f) curveToRelative(0.473f, 3.249f, 4.306f, 5.295f, 7.438f, 6.44f) curveToRelative(0.44f, 0.161f, 0.897f, 0.24f, 1.349f, 0.24f) curveToRelative(0.801f, 0.0f, 1.59f, -0.249f, 2.25f, -0.73f) curveToRelative(1.482f, -1.082f, 3.475f, -2.782f, 4.568f, -4.745f) curveToRelative(2.886f, -1.198f, 5.979f, -3.14f, 6.401f, -6.037f) lineToRelative(0.954f, -6.556f) curveToRelative(0.285f, -1.962f, -0.881f, -3.867f, -2.772f, -4.53f) close() moveTo(10.235f, 20.846f) curveToRelative(-0.223f, 0.163f, -0.522f, 0.198f, -0.801f, 0.097f) curveToRelative(-3.198f, -1.169f, -5.305f, -2.723f, -5.499f, -4.055f) lineToRelative(-0.954f, -6.556f) curveToRelative(-0.081f, -0.554f, 0.247f, -1.075f, 0.796f, -1.268f) curveToRelative(1.035f, -0.363f, 2.091f, -0.653f, 3.105f, -0.856f) lineToRelative(-0.286f, 1.965f) curveToRelative(-0.022f, 0.15f, -0.036f, 0.299f, -0.043f, 0.448f) curveToRelative(-0.144f, -0.031f, -0.292f, -0.038f, -0.441f, -0.016f) curveToRelative(-0.689f, 0.1f, -1.187f, 0.765f, -1.373f, 1.638f) curveToRelative(-0.062f, 0.29f, 0.185f, 0.553f, 0.478f, 0.511f) lineToRelative(1.619f, -0.231f) curveToRelative(0.243f, 0.72f, 0.627f, 1.417f, 1.101f, 2.08f) curveToRelative(-1.025f, 0.528f, -1.757f, 1.514f, -2.086f, 2.678f) curveToRelative(-0.124f, 0.44f, 0.376f, 0.791f, 0.756f, 0.537f) curveToRelative(1.035f, -0.692f, 1.997f, -1.111f, 3.026f, -1.287f) curveToRelative(0.731f, 0.701f, 1.519f, 1.337f, 2.273f, 1.889f) curveToRelative(0.218f, 0.159f, 0.448f, 0.293f, 0.688f, 0.402f) curveToRelative(-0.822f, 0.851f, -1.743f, 1.574f, -2.361f, 2.026f) close() moveTo(20.957f, 5.501f) lineToRelative(-0.954f, 6.556f) curveToRelative(-0.194f, 1.332f, -2.301f, 2.886f, -5.499f, 4.055f) curveToRelative(-0.279f, 0.103f, -0.587f, 0.06f, -0.826f, -0.114f) curveToRelative(-2.73f, -1.999f, -4.307f, -4.064f, -4.114f, -5.391f) lineToRelative(0.954f, -6.556f) curveToRelative(0.08f, -0.551f, 0.561f, -0.976f, 1.142f, -1.01f) curveToRelative(0.479f, -0.028f, 0.953f, -0.042f, 1.417f, -0.042f) curveToRelative(1.007f, 0.0f, 1.978f, 0.065f, 2.898f, 0.194f) curveToRelative(1.329f, 0.187f, 2.776f, 0.546f, 4.185f, 1.041f) curveToRelative(0.549f, 0.192f, 0.877f, 0.713f, 0.796f, 1.267f) close() moveTo(18.206f, 11.351f) curveToRelative(-0.909f, 1.22f, -2.317f, 1.949f, -3.818f, 1.736f) curveToRelative(-1.501f, -0.212f, -2.645f, -1.306f, -3.177f, -2.729f) curveToRelative(-0.165f, -0.442f, 0.325f, -0.842f, 0.736f, -0.611f) curveToRelative(1.931f, 1.084f, 3.568f, 1.317f, 5.726f, 0.816f) curveToRelative(0.457f, -0.106f, 0.813f, 0.412f, 0.532f, 0.788f) close() moveTo(19.042f, 7.523f) curveToRelative(0.062f, 0.29f, -0.185f, 0.553f, -0.478f, 0.511f) lineToRelative(-2.356f, -0.337f) curveToRelative(-0.293f, -0.042f, -0.457f, -0.363f, -0.316f, -0.624f) curveToRelative(0.423f, -0.786f, 1.088f, -1.287f, 1.777f, -1.188f) curveToRelative(0.689f, 0.1f, 1.187f, 0.765f, 1.373f, 1.638f) close() moveTo(11.436f, 6.436f) curveToRelative(0.423f, -0.786f, 1.088f, -1.287f, 1.777f, -1.188f) curveToRelative(0.689f, 0.1f, 1.187f, 0.765f, 1.373f, 1.638f) curveToRelative(0.062f, 0.29f, -0.185f, 0.553f, -0.478f, 0.511f) lineToRelative(-2.356f, -0.337f) curveToRelative(-0.293f, -0.042f, -0.457f, -0.363f, -0.316f, -0.624f) close() } } .build() return _theaterMasks!! } private var _theaterMasks: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,946
icons
MIT License
platform/platform-impl/src/com/intellij/ide/troubleshooting/DisplayInfo.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.troubleshooting import com.intellij.openapi.util.SystemInfo import com.intellij.ui.ScreenUtil import com.intellij.ui.scale.JBUIScale import java.awt.GraphicsDevice import java.awt.GraphicsEnvironment import java.awt.Insets import java.awt.Rectangle import kotlin.math.roundToInt internal data class DisplayInfo( val screens: List<ScreenInfo>, ) { companion object { @JvmStatic fun get(): DisplayInfo = DisplayInfo( GraphicsEnvironment.getLocalGraphicsEnvironment().screenDevices.map { screenInfo(it) } ) } } private fun screenInfo(device: GraphicsDevice): ScreenInfo { val scale = JBUIScale.sysScale(device.defaultConfiguration) val displayMode = device.displayMode val resolutionScale = if (SystemInfo.isMac) { // On macOS, displayMode reports "fake" (scaled) resolution that matches user-space coordinates. // Scaling it will yield the correct resolution on a true retina display. // For "intermediate" displays, such as 27-32" 4K ones, it'll also be fake, // but at least it'll match, e.g., screenshot resolutions. // There seems to be no way to retrieve the actual resolution. // It isn't needed, though, as macOS performs raster scaling on its own. // Therefore, for all intents and purposes, a 32" 4K (3840x2160) monitor // set to 2560x1440 in the macOS settings is "actually" a 5K (5120x2880) monitor scaled at 200%, // as far as our code (both the platform and JBR) is concerned. scale } else { // On Windows, display modes are reliable and return the actual screen resolutions. No need to scale them. // On Linux, it's unpredictable and depends on the environment. In the best case, it works correctly, // otherwise it usually returns the scaled bounds, in the worst case without a way to unscale them // because it reports 200% scaling instead of the actual value. // So the best we can do here is to trust it and hope for the best. 1.0f } val resolution = Resolution(scale(displayMode.width, resolutionScale), scale(displayMode.height, resolutionScale)) val scaling = Scaling(scale) val bounds = device.defaultConfiguration.bounds val insets = ScreenUtil.getScreenInsets(device.defaultConfiguration) return ScreenInfo(resolution, scaling, bounds, insets) } fun scale(value: Int, scale: Float): Int = (value * scale).roundToInt() internal data class ScreenInfo( val resolution: Resolution, val scaling: Scaling, val bounds: Rectangle, val insets: Insets, ) internal data class Resolution(val width: Int, val height: Int) { override fun toString(): String = "${width}x${height}" } internal data class Scaling(val percentage: Int) { constructor(scale: Float) : this((scale * 100.0f).roundToInt()) override fun toString(): String = "$percentage%" }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
2,934
intellij-community
Apache License 2.0
app/src/main/java/com/kieronquinn/app/darq/ui/screens/bottomsheets/backuprestore/restore/BackupRestoreRestoreBottomSheetViewModel.kt
KieronQuinn
194,549,688
false
null
package com.kieronquinn.app.darq.ui.screens.bottomsheets.backuprestore.restore import android.content.Context import android.net.Uri import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.gson.Gson import com.kieronquinn.app.darq.BuildConfig import com.kieronquinn.app.darq.R import com.kieronquinn.app.darq.components.navigation.Navigation import com.kieronquinn.app.darq.components.settings.DarqSharedPreferences import com.kieronquinn.app.darq.model.settings.SettingsBackup import com.kieronquinn.app.darq.utils.extensions.ungzip import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import kotlinx.coroutines.withContext abstract class BackupRestoreRestoreViewModel: ViewModel() { abstract val state: Flow<State> abstract fun setOutputUri(uri: Uri) sealed class State { object Idle: State() data class Restore(val uri: Uri): State() data class Complete(val result: Result, val showLocationPrompt: Boolean = false): State() } enum class Result { SUCCESS, FAILED } } class BackupRestoreRestoreBottomSheetViewModelImpl(private val applicationContext: Context, private val settings: DarqSharedPreferences, private val navigation: Navigation): BackupRestoreRestoreViewModel() { companion object { //Minimum time to show for so we don't dismiss immediately private const val MINIMUM_SHOW_TIME = 2000L } private val _state = MutableStateFlow<State>(State.Idle).apply { viewModelScope.launch { collect { val result = handleState(it) if(result != null){ emit(result) } } } } override val state: Flow<State> = _state override fun setOutputUri(uri: Uri) { viewModelScope.launch { if(_state.value is State.Idle){ _state.emit(State.Restore(uri)) } } } private suspend fun handleState(state: State): State? { return when(state){ is State.Restore -> restoreBackup(state.uri) is State.Complete -> { navigation.navigateUpTo(R.id.settingsFragment) if(state.showLocationPrompt){ navigation.navigate(R.id.action_global_locationPermissionDialogFragment) } null } else -> null } } private suspend fun restoreBackup(inputUri: Uri): State { val startTime = System.currentTimeMillis() return withContext(Dispatchers.IO){ runCatching { val fileInput = applicationContext.contentResolver.openInputStream(inputUri) ?: return@withContext State.Complete(Result.FAILED) fileInput.use { val unGzipped = it.readBytes().ungzip() val settingsBackup = Gson().fromJson(unGzipped, SettingsBackup::class.java) val showLocationPrompt = settings.fromSettingsBackup(settingsBackup) val remainingTime = MINIMUM_SHOW_TIME - (System.currentTimeMillis() - startTime) if (remainingTime > 0L) { delay(remainingTime) } return@withContext State.Complete(Result.SUCCESS, showLocationPrompt) } }.onFailure { if(BuildConfig.DEBUG){ it.printStackTrace() } } State.Complete(Result.FAILED) } } }
8
null
39
915
e058b4230575288ac06f7c7fd2a6c4cc6daae108
3,777
DarQ
Apache License 2.0
app/src/main/java/com/kieronquinn/app/darq/ui/screens/bottomsheets/backuprestore/restore/BackupRestoreRestoreBottomSheetViewModel.kt
KieronQuinn
194,549,688
false
null
package com.kieronquinn.app.darq.ui.screens.bottomsheets.backuprestore.restore import android.content.Context import android.net.Uri import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.gson.Gson import com.kieronquinn.app.darq.BuildConfig import com.kieronquinn.app.darq.R import com.kieronquinn.app.darq.components.navigation.Navigation import com.kieronquinn.app.darq.components.settings.DarqSharedPreferences import com.kieronquinn.app.darq.model.settings.SettingsBackup import com.kieronquinn.app.darq.utils.extensions.ungzip import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import kotlinx.coroutines.withContext abstract class BackupRestoreRestoreViewModel: ViewModel() { abstract val state: Flow<State> abstract fun setOutputUri(uri: Uri) sealed class State { object Idle: State() data class Restore(val uri: Uri): State() data class Complete(val result: Result, val showLocationPrompt: Boolean = false): State() } enum class Result { SUCCESS, FAILED } } class BackupRestoreRestoreBottomSheetViewModelImpl(private val applicationContext: Context, private val settings: DarqSharedPreferences, private val navigation: Navigation): BackupRestoreRestoreViewModel() { companion object { //Minimum time to show for so we don't dismiss immediately private const val MINIMUM_SHOW_TIME = 2000L } private val _state = MutableStateFlow<State>(State.Idle).apply { viewModelScope.launch { collect { val result = handleState(it) if(result != null){ emit(result) } } } } override val state: Flow<State> = _state override fun setOutputUri(uri: Uri) { viewModelScope.launch { if(_state.value is State.Idle){ _state.emit(State.Restore(uri)) } } } private suspend fun handleState(state: State): State? { return when(state){ is State.Restore -> restoreBackup(state.uri) is State.Complete -> { navigation.navigateUpTo(R.id.settingsFragment) if(state.showLocationPrompt){ navigation.navigate(R.id.action_global_locationPermissionDialogFragment) } null } else -> null } } private suspend fun restoreBackup(inputUri: Uri): State { val startTime = System.currentTimeMillis() return withContext(Dispatchers.IO){ runCatching { val fileInput = applicationContext.contentResolver.openInputStream(inputUri) ?: return@withContext State.Complete(Result.FAILED) fileInput.use { val unGzipped = it.readBytes().ungzip() val settingsBackup = Gson().fromJson(unGzipped, SettingsBackup::class.java) val showLocationPrompt = settings.fromSettingsBackup(settingsBackup) val remainingTime = MINIMUM_SHOW_TIME - (System.currentTimeMillis() - startTime) if (remainingTime > 0L) { delay(remainingTime) } return@withContext State.Complete(Result.SUCCESS, showLocationPrompt) } }.onFailure { if(BuildConfig.DEBUG){ it.printStackTrace() } } State.Complete(Result.FAILED) } } }
8
null
39
915
e058b4230575288ac06f7c7fd2a6c4cc6daae108
3,777
DarQ
Apache License 2.0
shared/src/commonMain/kotlin/App.kt
fernandozanutto
679,913,369
false
{"Kotlin": 23884, "Ruby": 2310, "Swift": 782, "Shell": 228}
import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import cafe.adriel.voyager.navigator.Navigator import presentation.onboarding.OnboardingScreen @Composable fun App() { MaterialTheme { Navigator( OnboardingScreen() ) } }
6
Kotlin
0
1
f9710232df33417e0bfaac4f423a8845ac34bf91
304
water-reminder
Apache License 2.0
core/data/src/main/java/com/muhammetkudur/data/source/remote/TopRatedPagingDataSource.kt
mskdr
666,795,563
false
{"Kotlin": 78660}
package com.muhammetkudur.data.source.remote import androidx.paging.PagingSource import androidx.paging.PagingState import com.muhammetkudur.common.ONE_VALUE import com.muhammetkudur.data.api.MovieService import com.muhammetkudur.data.dto.Movie import kotlinx.coroutines.delay import retrofit2.HttpException import java.io.IOException import javax.inject.Inject /** * Created By <NAME> * 17.07.2023 */ class TopRatedMoviesPagingSource @Inject constructor( private val movieApi: MovieService ): PagingSource<Int, Movie>() { override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Movie> { return try { val pageNumber = params.key ?: STARTING_PAGE_INDEX if (pageNumber != STARTING_PAGE_INDEX) delay(LOAD_DELAY_MILLIS) val response = movieApi.fetchTopRatedMovies(language = "en-US", page = pageNumber) val prevKey = if (pageNumber == 1) null else pageNumber - 1 val nextKey = pageNumber + 1 LoadResult.Page( data = response.results, prevKey = prevKey, nextKey = nextKey ) }catch (e: IOException){ return LoadResult.Error(e) }catch (e: HttpException){ val message = e.response()?.errorBody()?.string() LoadResult.Error(Throwable(message ?: ERROR_MESSAGE)) } } override fun getRefreshKey(state: PagingState<Int, Movie>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(Int.ONE_VALUE) ?: anchorPage?.nextKey?.minus(Int.ONE_VALUE) } } companion object { private const val STARTING_PAGE_INDEX = 1 private const val LOAD_DELAY_MILLIS = 500L private const val ERROR_MESSAGE = "Http Exception, we couldn't handle your request." } }
0
Kotlin
0
4
73ae7473f96e297433aa6b85eaab7cc89e10134f
1,939
MovieApp
MIT License
app/src/main/java/io/github/xiaobaicz/rhythm/page/Action.kt
xiaobaicz
734,162,593
false
{"Kotlin": 11607}
package io.github.xiaobaicz.rhythm.page import android.media.MediaPlayer import android.os.Bundle import android.view.WindowManager import androidx.lifecycle.lifecycleScope import io.github.xiaobaicz.rhythm.R import io.github.xiaobaicz.rhythm.databinding.PageActionBinding import io.github.xiaobaicz.rhythm.entity.Beat import io.github.xiaobaicz.rhythm.store.Local import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import vip.oicp.xiaobaicz.lib.common.app.AppCompatActivity import vip.oicp.xiaobaicz.lib.store.store class Action : AppCompatActivity() { private val bind by lazy { PageActionBinding.inflate(layoutInflater) } private val local = store<Local>() private val player by lazy { MediaPlayer.create(this, R.raw.kn_part) } private var isHold = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(bind.root) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) player.setOnCompletionListener { if (isHold) player.start() } lifecycleScope.launch { val cycle = local.cycle ?: 1 val beat = local.beat ?: throw NullPointerException() start(beat, cycle) } lifecycleScope.launch { timer() } } private var count: Int = 0 private val s = 1L private val m = 60 * s private val h = 60 * m private suspend fun timer() { bind.time.text = String.format("%02d:%02d:%02d", count / h, count % h / m, count % m) count++ delay(1000L) timer() } private suspend fun start(beat: Beat, cycle: Int) { withContext(Dispatchers.IO) { repeat(cycle) { withContext(Dispatchers.Main) { val count = it + 1 bind.count.text = "$count" } relax(beat.relax * 1000L) hold(beat.hold * 1000L) } } finish() } private suspend fun relax(time: Long) { if (player.isPlaying) player.pause() isHold = false delay(time) } private suspend fun hold(time: Long) { if (!player.isPlaying) player.start() isHold = true delay(time) } override fun onDestroy() { player.release() super.onDestroy() } }
0
Kotlin
0
0
465387aa68492c07bfe8e2b6019dc259e1eb790d
2,528
rhythm
Apache License 2.0
app/src/main/java/com/androiddevchallenge/week3/americas/ui/screen/home/Home.kt
DavidMendozaMartinez
536,454,269
false
{"Kotlin": 26875}
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androiddevchallenge.week3.americas.ui.screen.home import android.content.res.Configuration import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.androiddevchallenge.week3.americas.ui.screen.login.LogIn import com.androiddevchallenge.week3.americas.ui.theme.WeTradeTheme @Composable fun Home() { } @Preview(name = "Dark Theme", widthDp = 360, heightDp = 640, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun LogInPreview() { WeTradeTheme { LogIn() } }
0
Kotlin
0
2
7066e722671123583a827e4eba49a8484799befd
1,158
AndroidDevChallenge-Jetpack-Compose-Week-3-Americas
Apache License 2.0
app/src/main/java/com/navigationdrawer/kotlinone/MainActivity.kt
PolamReddyNagarjunaReddy
94,178,021
false
null
package com.navigationdrawer.kotlinone import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Button import android.widget.TextView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //var --> variables defined with var are mutable(Read and Write) //val --> variables defined with val are immutable(Read only) /* Fetching Id's */ var textView: TextView = findViewById(R.id.textview) as TextView var buttonSecond: Button = findViewById(R.id.button_second) as Button var buttonThird: Button = findViewById(R.id.button_third) as Button var buttonBaseActivity: Button = findViewById(R.id.button_base) as Button /* Setting values to textviews and buttons */ textView.text = "Click ME" buttonSecond.text = "Second Activity" buttonThird.text = "Third Activity" /*Click listener and navigating to different screens*/ buttonSecond.setOnClickListener { var activityIntent = Intent(this, Main2Activity::class.java) startActivity(activityIntent) } buttonThird.setOnClickListener { var activityThree = Intent(this, Main3Activity::class.java) startActivity(activityThree) } buttonBaseActivity.setOnClickListener { var baseActivity = Intent(this, BaseActivity::class.java) startActivity(baseActivity) } /**/ var z: View = findViewById(R.id.my_view) if (z is TextView) { z.text = "I am Textview " } } }
0
Kotlin
0
1
cfe833eba9c063871f5b32968755a2217a5a90b4
1,794
KotlinOne
Apache License 2.0
app/src/main/java/codes/jean/telepathy/ConnectionInformation.kt
JMPetry
125,539,794
false
null
package codes.jean.telepathy /** * ConnectionInformation holds all information which are needed to send data to the server * Created by Jean on 04.03.2018. */ class ConnectionInformation{ companion object { var serverIP:String = "" var secNum:String = "" /** * Checks if the qr code string is correct, splits the connection info string from the QR code and sets ip and secure number for the connection * @return returns true if regex matches local ip + ; + secure number */ fun splitAndSetConnectionInfos(infos:String) : Boolean{ val regex = Regex(pattern = """^192\.168(\.(\d|\d{2}|(1[0-9][0-9]|2[0-4][0-9]|25[0-5]))){2}:([3-5][0-9][0-9][0-9][0-9]|6[0-5][0-4][0-9][0-9]);\d{4}$""") //regex matching 192.168.[0-255].[0-255]:[30000-65499];[1000-9999] if(regex.matches(infos)) { val splitted = infos.split(";") serverIP = splitted[0] secNum = splitted[1] return true } return false } } }
0
Kotlin
0
0
c89be268304fb9dc6e2a7b0bd4282da13e776673
1,082
Telepathy_Android_App
MIT License
TurboNotes/app/src/main/java/com/plotts/jonathan/turbonotes/ui/theme/Color.kt
plottsjp
759,252,464
false
{"Kotlin": 36674}
package com.plotts.jonathan.turbonotes.ui.theme import androidx.compose.ui.graphics.Color val primaryLight = Color(0xFF00696F) val onPrimaryLight = Color(0xFFFFFFFF) val primaryContainerLight = Color(0xFF9CF0F7) val onPrimaryContainerLight = Color(0xFF002022) val secondaryLight = Color(0xFF4A6365) val onSecondaryLight = Color(0xFFFFFFFF) val secondaryContainerLight = Color(0xFFCCE8E9) val onSecondaryContainerLight = Color(0xFF051F21) val tertiaryLight = Color(0xFF4E5F7D) val onTertiaryLight = Color(0xFFFFFFFF) val tertiaryContainerLight = Color(0xFFD6E3FF) val onTertiaryContainerLight = Color(0xFF091B36) val errorLight = Color(0xFFBA1A1A) val onErrorLight = Color(0xFFFFFFFF) val errorContainerLight = Color(0xFFFFDAD6) val onErrorContainerLight = Color(0xFF410002) val backgroundLight = Color(0xFFF4FAFB) val onBackgroundLight = Color(0xFF161D1D) val surfaceLight = Color(0xFFF4FAFB) val onSurfaceLight = Color(0xFF161D1D) val surfaceVariantLight = Color(0xFFDAE4E5) val onSurfaceVariantLight = Color(0xFF3F4849) val outlineLight = Color(0xFF6F7979) val outlineVariantLight = Color(0xFFBEC8C9) val scrimLight = Color(0xFF000000) val inverseSurfaceLight = Color(0xFF2B3232) val inverseOnSurfaceLight = Color(0xFFECF2F2) val inversePrimaryLight = Color(0xFF80D4DA) val surfaceDimLight = Color(0xFFD5DBDB) val surfaceBrightLight = Color(0xFFF4FAFB) val surfaceContainerLowestLight = Color(0xFFFFFFFF) val surfaceContainerLowLight = Color(0xFFEFF5F5) val surfaceContainerLight = Color(0xFFE9EFEF) val surfaceContainerHighLight = Color(0xFFE3E9E9) val surfaceContainerHighestLight = Color(0xFFDDE4E4) val primaryLightMediumContrast = Color(0xFF004B4F) val onPrimaryLightMediumContrast = Color(0xFFFFFFFF) val primaryContainerLightMediumContrast = Color(0xFF238086) val onPrimaryContainerLightMediumContrast = Color(0xFFFFFFFF) val secondaryLightMediumContrast = Color(0xFF2E4749) val onSecondaryLightMediumContrast = Color(0xFFFFFFFF) val secondaryContainerLightMediumContrast = Color(0xFF60797B) val onSecondaryContainerLightMediumContrast = Color(0xFFFFFFFF) val tertiaryLightMediumContrast = Color(0xFF334360) val onTertiaryLightMediumContrast = Color(0xFFFFFFFF) val tertiaryContainerLightMediumContrast = Color(0xFF657594) val onTertiaryContainerLightMediumContrast = Color(0xFFFFFFFF) val errorLightMediumContrast = Color(0xFF8C0009) val onErrorLightMediumContrast = Color(0xFFFFFFFF) val errorContainerLightMediumContrast = Color(0xFFDA342E) val onErrorContainerLightMediumContrast = Color(0xFFFFFFFF) val backgroundLightMediumContrast = Color(0xFFF4FAFB) val onBackgroundLightMediumContrast = Color(0xFF161D1D) val surfaceLightMediumContrast = Color(0xFFF4FAFB) val onSurfaceLightMediumContrast = Color(0xFF161D1D) val surfaceVariantLightMediumContrast = Color(0xFFDAE4E5) val onSurfaceVariantLightMediumContrast = Color(0xFF3B4545) val outlineLightMediumContrast = Color(0xFF576161) val outlineVariantLightMediumContrast = Color(0xFF737D7D) val scrimLightMediumContrast = Color(0xFF000000) val inverseSurfaceLightMediumContrast = Color(0xFF2B3232) val inverseOnSurfaceLightMediumContrast = Color(0xFFECF2F2) val inversePrimaryLightMediumContrast = Color(0xFF80D4DA) val surfaceDimLightMediumContrast = Color(0xFFD5DBDB) val surfaceBrightLightMediumContrast = Color(0xFFF4FAFB) val surfaceContainerLowestLightMediumContrast = Color(0xFFFFFFFF) val surfaceContainerLowLightMediumContrast = Color(0xFFEFF5F5) val surfaceContainerLightMediumContrast = Color(0xFFE9EFEF) val surfaceContainerHighLightMediumContrast = Color(0xFFE3E9E9) val surfaceContainerHighestLightMediumContrast = Color(0xFFDDE4E4) val primaryLightHighContrast = Color(0xFF002729) val onPrimaryLightHighContrast = Color(0xFFFFFFFF) val primaryContainerLightHighContrast = Color(0xFF004B4F) val onPrimaryContainerLightHighContrast = Color(0xFFFFFFFF) val secondaryLightHighContrast = Color(0xFF0C2628) val onSecondaryLightHighContrast = Color(0xFFFFFFFF) val secondaryContainerLightHighContrast = Color(0xFF2E4749) val onSecondaryContainerLightHighContrast = Color(0xFFFFFFFF) val tertiaryLightHighContrast = Color(0xFF11223D) val onTertiaryLightHighContrast = Color(0xFFFFFFFF) val tertiaryContainerLightHighContrast = Color(0xFF334360) val onTertiaryContainerLightHighContrast = Color(0xFFFFFFFF) val errorLightHighContrast = Color(0xFF4E0002) val onErrorLightHighContrast = Color(0xFFFFFFFF) val errorContainerLightHighContrast = Color(0xFF8C0009) val onErrorContainerLightHighContrast = Color(0xFFFFFFFF) val backgroundLightHighContrast = Color(0xFFF4FAFB) val onBackgroundLightHighContrast = Color(0xFF161D1D) val surfaceLightHighContrast = Color(0xFFF4FAFB) val onSurfaceLightHighContrast = Color(0xFF000000) val surfaceVariantLightHighContrast = Color(0xFFDAE4E5) val onSurfaceVariantLightHighContrast = Color(0xFF1C2626) val outlineLightHighContrast = Color(0xFF3B4545) val outlineVariantLightHighContrast = Color(0xFF3B4545) val scrimLightHighContrast = Color(0xFF000000) val inverseSurfaceLightHighContrast = Color(0xFF2B3232) val inverseOnSurfaceLightHighContrast = Color(0xFFFFFFFF) val inversePrimaryLightHighContrast = Color(0xFFABF9FF) val surfaceDimLightHighContrast = Color(0xFFD5DBDB) val surfaceBrightLightHighContrast = Color(0xFFF4FAFB) val surfaceContainerLowestLightHighContrast = Color(0xFFFFFFFF) val surfaceContainerLowLightHighContrast = Color(0xFFEFF5F5) val surfaceContainerLightHighContrast = Color(0xFFE9EFEF) val surfaceContainerHighLightHighContrast = Color(0xFFE3E9E9) val surfaceContainerHighestLightHighContrast = Color(0xFFDDE4E4) val primaryDark = Color(0xFF80D4DA) val onPrimaryDark = Color(0xFF00373A) val primaryContainerDark = Color(0xFF004F53) val onPrimaryContainerDark = Color(0xFF9CF0F7) val secondaryDark = Color(0xFFB1CCCD) val onSecondaryDark = Color(0xFF1B3436) val secondaryContainerDark = Color(0xFF324B4D) val onSecondaryContainerDark = Color(0xFFCCE8E9) val tertiaryDark = Color(0xFFB6C7EA) val onTertiaryDark = Color(0xFF20314C) val tertiaryContainerDark = Color(0xFF374764) val onTertiaryContainerDark = Color(0xFFD6E3FF) val errorDark = Color(0xFFFFB4AB) val onErrorDark = Color(0xFF690005) val errorContainerDark = Color(0xFF93000A) val onErrorContainerDark = Color(0xFFFFDAD6) val backgroundDark = Color(0xFF0E1415) val onBackgroundDark = Color(0xFFDDE4E4) val surfaceDark = Color(0xFF0E1415) val onSurfaceDark = Color(0xFFDDE4E4) val surfaceVariantDark = Color(0xFF3F4849) val onSurfaceVariantDark = Color(0xFFBEC8C9) val outlineDark = Color(0xFF899393) val outlineVariantDark = Color(0xFF3F4849) val scrimDark = Color(0xFF000000) val inverseSurfaceDark = Color(0xFFDDE4E4) val inverseOnSurfaceDark = Color(0xFF2B3232) val inversePrimaryDark = Color(0xFF00696F) val surfaceDimDark = Color(0xFF0E1415) val surfaceBrightDark = Color(0xFF343A3B) val surfaceContainerLowestDark = Color(0xFF090F10) val surfaceContainerLowDark = Color(0xFF161D1D) val surfaceContainerDark = Color(0xFF1A2121) val surfaceContainerHighDark = Color(0xFF252B2C) val surfaceContainerHighestDark = Color(0xFF303636) val primaryDarkMediumContrast = Color(0xFF84D8DE) val onPrimaryDarkMediumContrast = Color(0xFF001A1C) val primaryContainerDarkMediumContrast = Color(0xFF479DA3) val onPrimaryContainerDarkMediumContrast = Color(0xFF000000) val secondaryDarkMediumContrast = Color(0xFFB5D0D2) val onSecondaryDarkMediumContrast = Color(0xFF001A1C) val secondaryContainerDarkMediumContrast = Color(0xFF7B9597) val onSecondaryContainerDarkMediumContrast = Color(0xFF000000) val tertiaryDarkMediumContrast = Color(0xFFBACBEE) val onTertiaryDarkMediumContrast = Color(0xFF031630) val tertiaryContainerDarkMediumContrast = Color(0xFF8191B2) val onTertiaryContainerDarkMediumContrast = Color(0xFF000000) val errorDarkMediumContrast = Color(0xFFFFBAB1) val onErrorDarkMediumContrast = Color(0xFF370001) val errorContainerDarkMediumContrast = Color(0xFFFF5449) val onErrorContainerDarkMediumContrast = Color(0xFF000000) val backgroundDarkMediumContrast = Color(0xFF0E1415) val onBackgroundDarkMediumContrast = Color(0xFFDDE4E4) val surfaceDarkMediumContrast = Color(0xFF0E1415) val onSurfaceDarkMediumContrast = Color(0xFFF6FCFC) val surfaceVariantDarkMediumContrast = Color(0xFF3F4849) val onSurfaceVariantDarkMediumContrast = Color(0xFFC3CDCD) val outlineDarkMediumContrast = Color(0xFF9BA5A5) val outlineVariantDarkMediumContrast = Color(0xFF7B8586) val scrimDarkMediumContrast = Color(0xFF000000) val inverseSurfaceDarkMediumContrast = Color(0xFFDDE4E4) val inverseOnSurfaceDarkMediumContrast = Color(0xFF252B2C) val inversePrimaryDarkMediumContrast = Color(0xFF005055) val surfaceDimDarkMediumContrast = Color(0xFF0E1415) val surfaceBrightDarkMediumContrast = Color(0xFF343A3B) val surfaceContainerLowestDarkMediumContrast = Color(0xFF090F10) val surfaceContainerLowDarkMediumContrast = Color(0xFF161D1D) val surfaceContainerDarkMediumContrast = Color(0xFF1A2121) val surfaceContainerHighDarkMediumContrast = Color(0xFF252B2C) val surfaceContainerHighestDarkMediumContrast = Color(0xFF303636) val primaryDarkHighContrast = Color(0xFFEDFEFF) val onPrimaryDarkHighContrast = Color(0xFF000000) val primaryContainerDarkHighContrast = Color(0xFF84D8DE) val onPrimaryContainerDarkHighContrast = Color(0xFF000000) val secondaryDarkHighContrast = Color(0xFFEDFEFF) val onSecondaryDarkHighContrast = Color(0xFF000000) val secondaryContainerDarkHighContrast = Color(0xFFB5D0D2) val onSecondaryContainerDarkHighContrast = Color(0xFF000000) val tertiaryDarkHighContrast = Color(0xFFFBFAFF) val onTertiaryDarkHighContrast = Color(0xFF000000) val tertiaryContainerDarkHighContrast = Color(0xFFBACBEE) val onTertiaryContainerDarkHighContrast = Color(0xFF000000) val errorDarkHighContrast = Color(0xFFFFF9F9) val onErrorDarkHighContrast = Color(0xFF000000) val errorContainerDarkHighContrast = Color(0xFFFFBAB1) val onErrorContainerDarkHighContrast = Color(0xFF000000) val backgroundDarkHighContrast = Color(0xFF0E1415) val onBackgroundDarkHighContrast = Color(0xFFDDE4E4) val surfaceDarkHighContrast = Color(0xFF0E1415) val onSurfaceDarkHighContrast = Color(0xFFFFFFFF) val surfaceVariantDarkHighContrast = Color(0xFF3F4849) val onSurfaceVariantDarkHighContrast = Color(0xFFF3FDFD) val outlineDarkHighContrast = Color(0xFFC3CDCD) val outlineVariantDarkHighContrast = Color(0xFFC3CDCD) val scrimDarkHighContrast = Color(0xFF000000) val inverseSurfaceDarkHighContrast = Color(0xFFDDE4E4) val inverseOnSurfaceDarkHighContrast = Color(0xFF000000) val inversePrimaryDarkHighContrast = Color(0xFF003032) val surfaceDimDarkHighContrast = Color(0xFF0E1415) val surfaceBrightDarkHighContrast = Color(0xFF343A3B) val surfaceContainerLowestDarkHighContrast = Color(0xFF090F10) val surfaceContainerLowDarkHighContrast = Color(0xFF161D1D) val surfaceContainerDarkHighContrast = Color(0xFF1A2121) val surfaceContainerHighDarkHighContrast = Color(0xFF252B2C) val surfaceContainerHighestDarkHighContrast = Color(0xFF303636) val customColor1Light = Color(0xFF845415) val onCustomColor1Light = Color(0xFFFFFFFF) val customColor1ContainerLight = Color(0xFFFFDDBB) val onCustomColor1ContainerLight = Color(0xFF2B1700) val customColor1LightMediumContrast = Color(0xFF623A00) val onCustomColor1LightMediumContrast = Color(0xFFFFFFFF) val customColor1ContainerLightMediumContrast = Color(0xFF9D6A2A) val onCustomColor1ContainerLightMediumContrast = Color(0xFFFFFFFF) val customColor1LightHighContrast = Color(0xFF351D00) val onCustomColor1LightHighContrast = Color(0xFFFFFFFF) val customColor1ContainerLightHighContrast = Color(0xFF623A00) val onCustomColor1ContainerLightHighContrast = Color(0xFFFFFFFF) val customColor1Dark = Color(0xFFFABA73) val onCustomColor1Dark = Color(0xFF482900) val customColor1ContainerDark = Color(0xFF673D00) val onCustomColor1ContainerDark = Color(0xFFFFDDBB) val customColor1DarkMediumContrast = Color(0xFFFFBE76) val onCustomColor1DarkMediumContrast = Color(0xFF241200) val customColor1ContainerDarkMediumContrast = Color(0xFFBE8543) val onCustomColor1ContainerDarkMediumContrast = Color(0xFF000000) val customColor1DarkHighContrast = Color(0xFFFFFAF8) val onCustomColor1DarkHighContrast = Color(0xFF000000) val customColor1ContainerDarkHighContrast = Color(0xFFFFBE76) val onCustomColor1ContainerDarkHighContrast = Color(0xFF000000)
0
Kotlin
0
0
d14985650092a51fb4e181a422ee7e5da635b289
12,244
Raven-s-Memory
MIT License
alice-ktx/src/main/kotlin/com/github/alice/ktx/handlers/Handler.kt
danbeldev
833,612,985
false
{"Kotlin": 68779}
package com.github.alice.ktx.handlers import com.github.alice.ktx.models.request.MessageRequest import com.github.alice.ktx.models.response.MessageResponse /** * Интерфейс `Handler` предназначен для обработки событий, связанных с запросами сообщений. * Реализация этого интерфейса позволяет задать логику для определения, когда обработчик должен сработать, * и для обработки самого запроса. */ interface Handler { /** * Определяет, сработает ли обработчик для данного сообщения. * * @param message Сообщение, которое проверяется на соответствие условиям обработчика. * @return `true`, если обработчик должен сработать для данного сообщения; `false` в противном случае. */ suspend fun event(message: MessageRequest): Boolean /** * Выполняет обработку запроса сообщения и возвращает ответ. * * @param request Запрос сообщения, который будет обработан. * @return Ответ на запрос в виде `MessageResponse`. */ suspend fun handle(request: MessageRequest): MessageResponse }
0
Kotlin
0
3
2e2cb34b3bc4de208917e007d1bea2c827fcfbf4
1,041
alice-ktx
MIT License
dispatcher/src/test/kotlin/com/robotpajamas/dispatcher/RetryTest.kt
RobotPajamas
135,966,970
false
{"Kotlin": 25199}
package com.robotpajamas.dispatcher import android.os.Handler import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class RetryTest { private val dispatcher = SerialDispatcher() private lateinit var dispatchOne: Dispatch<String> private lateinit var dispatchTwo: Dispatch<String> private lateinit var dispatchThree: Dispatch<String> private val actual = mutableListOf<String>() private val expected = mutableListOf<String>() private val handler = Handler() @Before fun setUp() { actual.clear() expected.clear() handler.removeCallbacksAndMessages(null) } @Test fun `Given 2 items with RETRY and NONE retry policies, When 2 items are scheduled and RETRY one fails, Then its execution is retried maximum attempts before executing the second item`() { dispatchOne = Dispatch(id = "id", retryPolicy = RetryPolicy.RETRY, execution = { cb -> actual.add(dispatchOne.id) println("Execution failed") cb(Result.Failure(Exception("Mocked failure"))) }, completion = { println("Completion block invoked") }) dispatchTwo = Dispatch(id = "id2", retryPolicy = RetryPolicy.NONE, execution = { cb -> actual.add(dispatchTwo.id) println("Execution failed") cb(Result.Failure(Exception("Mocked failure"))) }, completion = { println("Completion block invoked") }) expected.addAll(listOf(dispatchOne.id, dispatchOne.id, dispatchOne.id, dispatchTwo.id)) handler.post { dispatcher.enqueue(dispatchOne) dispatcher.enqueue(dispatchTwo) } println(actual) assertThat(actual).containsExactlyElementsOf(expected) } @Test fun `Given 2 items with RESCHEDULE and NONE retry policies, When 2 items are scheduled and RESCHEDULE one fails, Then it gets re-added to the tail of the queue, And the order of execution matches expected order`() { dispatchOne = Dispatch(id = "id", retryPolicy = RetryPolicy.RESCHEDULE, execution = { cb -> actual.add(dispatchOne.id) println("Execution failed") cb(Result.Failure(Exception("Mocked failure"))) }, completion = { println("Completion block invoked") }) dispatchTwo = Dispatch(id = "id2", retryPolicy = RetryPolicy.NONE, execution = { cb -> actual.add(dispatchTwo.id) println("Execution failed") cb(Result.Failure(Exception("Mocked failure"))) }, completion = { println("Completion block invoked") }) expected.addAll(listOf(dispatchOne.id, dispatchTwo.id, dispatchOne.id, dispatchOne.id)) handler.post { dispatcher.enqueue(dispatchOne) dispatcher.enqueue(dispatchTwo) } println(actual) assertThat(actual).containsExactlyElementsOf(expected) } @Test fun `Given 3 items with different retry policies, When execution fails, Then the order of retries matches expected order`() { dispatchOne = Dispatch(id = "id", retryPolicy = RetryPolicy.RESCHEDULE, execution = { cb -> actual.add(dispatchOne.id) println("Execution failed") cb(Result.Failure(Exception("Mocked failure"))) }, completion = { println("Completion block invoked") }) dispatchTwo = Dispatch(id = "id2", retryPolicy = RetryPolicy.RETRY, execution = { cb -> actual.add(dispatchTwo.id) println("Execution failed") cb(Result.Failure(Exception("Mocked failure"))) }, completion = { println("Completion block invoked") }) dispatchThree = Dispatch(id = "id3", retryPolicy = RetryPolicy.NONE, execution = { cb -> actual.add(dispatchThree.id) println("Execution failed") cb(Result.Failure(Exception("Mocked failure"))) }, completion = { println("Completion block invoked") }) expected.addAll(listOf(dispatchOne.id, dispatchTwo.id, dispatchTwo.id, dispatchTwo.id, dispatchThree.id, dispatchOne.id, dispatchOne.id)) handler.post { dispatcher.enqueue(dispatchOne) dispatcher.enqueue(dispatchTwo) dispatcher.enqueue(dispatchThree) } println(actual) assertThat(actual).containsExactlyElementsOf(expected) } }
1
Kotlin
1
0
90f42c47a5f213e7dc1aee685cb950438a720928
5,074
Dispatcher
Apache License 2.0
analysis/analysis-api/testData/sessions/sessionInvalidation/codeFragmentWithContextModuleDependent.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// MODULE: context // MODULE_KIND: Source // FILE: context.kt fun foo() { <caret_context>val x = 0 } // MODULE: dependent(context) // MODULE_KIND: Source // WILDCARD_MODIFICATION_EVENT // FILE: dependent.kt fun dependent() { val y = 1 } // MODULE: fragment1.kt // MODULE_KIND: CodeFragment // CONTEXT_MODULE: context // FILE: fragment1.kt // CODE_FRAGMENT_KIND: BLOCK <caret>foo()
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
392
kotlin
Apache License 2.0
src/r3/atomic-swap/corda/evm-interop-workflows/src/main/kotlin/com/r3/corda/evminterop/services/BridgeIdentity.kt
hyperledger-labs
648,500,313
false
{"Java": 736584, "JavaScript": 620424, "Solidity": 416150, "Kotlin": 336027, "Makefile": 2770, "Dockerfile": 2180, "Smarty": 1842, "Shell": 1365, "HTML": 411}
package com.r3.corda.evminterop.services import com.r3.corda.evminterop.services.internal.RemoteEVMIdentityImpl import org.web3j.crypto.* import java.net.URI data class BridgeIdentity ( /** * [privateKey] defines the signing key and derived account address */ val privateKey: String, /** * [rpcEndpoint] defines the EVM node endpoint to connect to */ override val rpcEndpoint: URI, /** * [chainId] of the selected EVM network */ override val chainId: Long = -1, /** * [protocolAddress] defines the protocol contract deployment address on the given network */ override val protocolAddress: String, /** * [deployerAddress] defines the protocol contract deployment address on the given network */ override val deployerAddress: String ) : RemoteEVMIdentityImpl(rpcEndpoint, chainId, protocolAddress, deployerAddress) { private val credentials = Credentials.create(privateKey) override fun signMessage(rawTransaction: RawTransaction, chainId: Long) : ByteArray { return if (chainId > -1) { TransactionEncoder.signMessage(rawTransaction, chainId, credentials) } else { TransactionEncoder.signMessage(rawTransaction, credentials) } } override fun getAddress() : String = credentials.address override fun signData(data: ByteArray) : ByteArray { val ecKeyPair = credentials.ecKeyPair val signatureData = Sign.signMessage(data, ecKeyPair) val signatureBytes = ByteArray(65) System.arraycopy(signatureData.r, 0, signatureBytes, 0, 32) System.arraycopy(signatureData.s, 0, signatureBytes, 32, 32) System.arraycopy(signatureData.v, 0, signatureBytes, 64, 1) val publicKey = Sign.signedMessageToKey(data, signatureData) val addressString = Keys.getAddress(publicKey) val address = org.web3j.abi.datatypes.Address(addressString) return signatureBytes } override fun dispose() { } }
6
Java
15
23
12f3f0182d6c0ccc6f4f9e8b1629e2e9111e6de2
2,033
harmonia
Apache License 2.0
src/com/ivaneye/ktjvm/model/attr/SourceDebugExtension.kt
ivaneye
90,348,769
false
{"XML": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Java": 1, "Kotlin": 65}
package com.ivaneye.ktjvm.model.attr import com.ivaneye.ktjvm.type.U1 import com.ivaneye.ktjvm.type.U2 import com.ivaneye.ktjvm.type.U4 /** * Created by wangyifan on 2017/5/22. */ class SourceDebugExtension : Attribute{ lateinit var attributeNameIndex: U2 lateinit var attributeLength: U4 lateinit var debugExtension: Array<U1> }
1
null
1
1
0c153fa416cd6380ffcbaa771fcca46968f32974
346
kt-jvm
Apache License 2.0
u-android/app/src/main/java/com/study/u/ui/fragment/AssetFragment.kt
liuhuiAndroid
274,625,628
false
{"Markdown": 7, "Text": 3, "Batchfile": 2, "Shell": 2, "Maven POM": 1, "Ignore List": 5, "INI": 1, "Java": 45, "YAML": 3, "Dockerfile": 1, "Dotenv": 3, "JSON": 2, "JavaScript": 39, "JSON with Comments": 1, "EditorConfig": 1, "HTML": 1, "Vue": 26, "SVG": 11, "SCSS": 6, "Gradle": 3, "Java Properties": 2, "Proguard": 1, "Kotlin": 46, "XML": 37, "PureBasic": 1}
package com.study.u.ui.fragment import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.study.u.R import com.study.u.ui.WithdrawActivity import com.study.u.viewmodel.AssetViewModel import kotlinx.android.synthetic.main.fragment_asset.* import timber.log.Timber class AssetFragment : Fragment() { private lateinit var assetViewModel: AssetViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { assetViewModel = ViewModelProvider(this)[AssetViewModel::class.java] return inflater.inflate(R.layout.fragment_asset, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) assetViewModel.subscribeAsset()?.observe(viewLifecycleOwner, Observer { Timber.i("asset: $it") it?.let { mTvAsset.text = "投资资产:${it.invest}U \n推广资产:${it.extend}U \n总资产:${it.allUsdt}U " } }) withdrawButton.setOnClickListener { startActivity(Intent(activity, WithdrawActivity::class.java)) } } }
0
Kotlin
0
0
730775e1a263d4849483c686b413737ba051bb3d
1,403
u-app
MIT License
app/src/main/java/com/sk/autotp/ui/Margin.kt
swapnilkadlag
715,625,548
false
{"Kotlin": 63221}
package com.sk.autotp.ui import androidx.compose.ui.unit.dp object Margin { val VerySmall = 4.dp val Small = 8.dp val Medium = 16.dp val Large = 24.dp val VeryLarge = 32.dp val FabHeight = 96.dp }
0
Kotlin
0
0
53cfcb772e8ee3cb57f747b36ad8abc93e918776
222
AutOTP
Apache License 2.0
compiler/test-infrastructure/tests/org/jetbrains/kotlin/test/WrappedException.kt
gonexwind
383,707,681
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.test sealed class WrappedException( cause: Throwable, val priority: Int, val additionalPriority: Int ) : Exception(cause), Comparable<WrappedException> { sealed class FromFacade(cause: Throwable, additionalPriority: Int) : WrappedException(cause, 0, additionalPriority) { class Frontend(cause: Throwable) : FromFacade(cause, 1) class Converter(cause: Throwable) : FromFacade(cause, 2) class Backend(cause: Throwable) : FromFacade(cause, 3) override val message: String get() = "Exception was thrown" } class FromMetaInfoHandler(cause: Throwable) : WrappedException(cause, 1, 1) class FromFrontendHandler(cause: Throwable) : WrappedException(cause, 1, 1) class FromBackendHandler(cause: Throwable) : WrappedException(cause, 1, 2) class FromBinaryHandler(cause: Throwable) : WrappedException(cause, 1, 3) class FromUnknownHandler(cause: Throwable) : WrappedException(cause, 1, 4) class FromAfterAnalysisChecker(cause: Throwable) : WrappedException(cause, 2, 1) class FromModuleStructureTransformer(cause: Throwable) : WrappedException(cause, 2, 1) override val cause: Throwable get() = super.cause!! override fun compareTo(other: WrappedException): Int { if (priority == other.priority) { return additionalPriority - other.additionalPriority } return priority - other.priority } }
1
null
1
2
30d0fea003a9d96116250d7ad82b94f3bb332a77
1,674
kotlin
Apache License 2.0
helper-core/src/main/java/archtree/helper/binding/ImageViewAdapter.kt
Mordag
129,695,558
false
{"Kotlin": 93302}
package archtree.helper.binding import android.content.res.Resources import android.graphics.PorterDuff import android.widget.ImageView import androidx.core.content.ContextCompat import androidx.databinding.BindingAdapter @BindingAdapter("archtree_drawableRes") fun ImageView.setDrawableRes(icon: Int?) { icon?.run { val drawable = try { ContextCompat.getDrawable(context, icon) } catch (e: Resources.NotFoundException) { null } setImageDrawable(drawable) } ?: setImageBitmap(null) } @BindingAdapter("archtree_imageTintColor") fun ImageView.setTintColor(value: Int?) { value?.run { setColorFilter(ContextCompat.getColor(context, value), PorterDuff.Mode.MULTIPLY) } }
0
Kotlin
1
2
8daf284b9ae3d908c545b82bc42abdc86baec1c4
749
archtree
Apache License 2.0
app/src/main/java/com/charlag/promind/core/action/ActionHandlerImpl.kt
charlag
83,122,828
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 72, "XML": 27, "Java": 1}
package com.charlag.promind.core.action import android.content.Context import com.charlag.promind.core.data.models.Action import com.charlag.promind.util.makeIntent /** * Created by charlag on 17/04/2017. */ class ActionHandlerImpl(private val context: Context) : ActionHandler { override fun handle(action: Action) = context.startActivity(action.makeIntent(context)) }
0
Kotlin
0
1
4b8ca32de1d83fadf0bc37d7390915ec7a2d67dd
378
Promind
MIT License
feature/settings/src/main/java/soup/movie/settings/SettingsScreen.kt
Moop-App
113,048,795
false
null
/* * Copyright 2021 SOUP * * 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 soup.movie.settings import android.content.Context import android.content.Intent import android.net.Uri import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.AlertDialog import androidx.compose.material.ButtonDefaults import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.BugReport import androidx.compose.material.icons.rounded.Edit import androidx.compose.material.icons.rounded.NewReleases import androidx.compose.material.icons.rounded.Palette import androidx.compose.material.icons.rounded.Shop import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.google.accompanist.flowlayout.FlowRow import soup.metronome.material.UnelevatedButton import soup.movie.ext.startActivitySafely import soup.movie.model.Theater import soup.movie.theater.TheaterChip import soup.movie.theme.stringResIdOf import soup.movie.ui.divider import soup.movie.util.Cgv import soup.movie.util.LotteCinema import soup.movie.util.Megabox import soup.movie.util.Moop import soup.movie.util.debounce @Composable internal fun SettingsScreen( viewModel: SettingsViewModel, onThemeEditClick: () -> Unit, onTheaterEditClick: () -> Unit, onVersionClick: (VersionSettingUiModel) -> Unit, onMarketIconClick: () -> Unit, ) { Scaffold( topBar = { TopAppBar( title = { Text(text = stringResource(R.string.menu_settings)) } ) } ) { paddingValues -> val context = LocalContext.current val theme by viewModel.themeUiModel.observeAsState() val theater by viewModel.theaterUiModel.observeAsState() val version by viewModel.versionUiModel.observeAsState() Column( modifier = Modifier .padding(paddingValues) .padding(horizontal = 16.dp) .verticalScroll(rememberScrollState()) ) { SettingsThemeItem(theme, onClick = onThemeEditClick) SettingsDivider() SettingsTheaterItem( theater?.theaterList.orEmpty(), onItemClick = { theater -> context.executeWeb(theater) }, onEditClick = onTheaterEditClick ) SettingsDivider() SettingsVersionItem( version = version, onClick = onVersionClick, onActionClick = onMarketIconClick ) SettingsDivider() SettingsFeedbackItem(onClick = { context.goToEmail() }) } } if (viewModel.showVersionUpdateDialog) { val context = LocalContext.current AlertDialog( onDismissRequest = { viewModel.showVersionUpdateDialog = false }, title = { Row(verticalAlignment = Alignment.CenterVertically) { Icon( Icons.Rounded.NewReleases, contentDescription = null, tint = MaterialTheme.colors.error ) Spacer(modifier = Modifier.width(8.dp)) Text(text = stringResource(R.string.settings_version_update_title)) } }, text = { Text(text = stringResource(R.string.settings_version_update_message)) }, confirmButton = { TextButton( onClick = { Moop.executePlayStore(context) }, colors = ButtonDefaults.textButtonColors( contentColor = MaterialTheme.colors.secondary ), ) { Text(text = stringResource(R.string.settings_version_update_button_positive)) } }, dismissButton = { TextButton( onClick = { viewModel.showVersionUpdateDialog = false }, colors = ButtonDefaults.textButtonColors( contentColor = MaterialTheme.colors.secondary ), ) { Text(text = stringResource(R.string.settings_version_update_button_negative)) } }, ) } } @Composable private fun SettingsThemeItem( theme: ThemeSettingUiModel?, onClick: () -> Unit, ) { val text = if (theme != null) { stringResource(stringResIdOf(theme.themeOption)) } else { "" } Column( modifier = Modifier.padding(top = 12.dp, bottom = 24.dp) ) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { SettingsCategory( text = stringResource(R.string.settings_category_theme), modifier = Modifier.weight(1f) ) IconButton( onClick = { debounce(onClick) }, modifier = Modifier.size(48.dp) ) { Icon( Icons.Rounded.Palette, contentDescription = null, tint = MaterialTheme.colors.onBackground, ) } } Spacer(modifier = Modifier.height(12.dp)) Box(modifier = Modifier.requiredHeight(48.dp)) { UnelevatedButton( onClick = { debounce(onClick) }, modifier = Modifier.fillMaxSize(), colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.surface ) ) { Text( text = text, modifier = Modifier.fillMaxWidth(), fontSize = 17.sp, style = MaterialTheme.typography.body2 ) } } } } @Composable private fun SettingsTheaterItem( theaterList: List<Theater>, onItemClick: (Theater) -> Unit, onEditClick: () -> Unit, ) { Column( modifier = Modifier.padding(top = 12.dp, bottom = 24.dp) ) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { SettingsCategory( text = stringResource(R.string.settings_category_theater), modifier = Modifier.weight(1f) ) IconButton( onClick = { debounce(onEditClick) }, modifier = Modifier.size(48.dp) ) { Icon( Icons.Rounded.Edit, contentDescription = null, tint = MaterialTheme.colors.onBackground, ) } } Spacer(modifier = Modifier.height(12.dp)) Box { if (theaterList.isEmpty()) { Text( text = stringResource(R.string.settings_theater_empty_description), textAlign = TextAlign.Center, style = MaterialTheme.typography.body2 ) } else { FlowRow(mainAxisSpacing = 8.dp) { theaterList.forEach { theater -> TheaterChip(theater, onItemClick) } } } } } } @Composable private fun SettingsVersionItem( version: VersionSettingUiModel?, onClick: (VersionSettingUiModel) -> Unit, onActionClick: () -> Unit = {} ) { Column( modifier = Modifier.padding(vertical = 24.dp) ) { SettingsCategory(text = stringResource(R.string.settings_category_version)) Spacer(modifier = Modifier.height(12.dp)) Box(modifier = Modifier.requiredHeight(48.dp)) { SettingsButton( onClick = { debounce { version?.run(onClick) } }, modifier = Modifier.fillMaxSize() ) { Text( text = version?.let { version -> if (version.isLatest) { stringResource(R.string.settings_version_latest, version.versionName) } else { stringResource(R.string.settings_version_current, version.versionName) } }.orEmpty(), textAlign = TextAlign.Center, style = MaterialTheme.typography.body2 ) } IconButton( onClick = { debounce(onActionClick) }, modifier = Modifier .width(48.dp) .padding(end = 4.dp) .align(Alignment.CenterEnd) ) { if (version?.isLatest == true) { Icon( Icons.Rounded.Shop, contentDescription = null, tint = MaterialTheme.colors.onSurface, ) } else { Icon( Icons.Rounded.NewReleases, contentDescription = null, tint = MaterialTheme.colors.onError, ) } } } } } @Composable private fun SettingsFeedbackItem( onClick: () -> Unit ) { Column( modifier = Modifier.padding(vertical = 24.dp) ) { SettingsCategory(text = stringResource(R.string.settings_category_feedback)) Spacer(modifier = Modifier.height(12.dp)) Box(modifier = Modifier.requiredHeight(48.dp)) { SettingsButton( onClick = onClick, modifier = Modifier.fillMaxSize() ) { Text( text = "개발자에게 버그 신고하기", textAlign = TextAlign.Center, style = MaterialTheme.typography.body2 ) } Icon( Icons.Rounded.BugReport, contentDescription = null, tint = MaterialTheme.colors.onSurface, modifier = Modifier .padding(end = 16.dp) .align(Alignment.CenterEnd) ) } } } @Composable private fun SettingsCategory( text: String, modifier: Modifier = Modifier ) { Text( text = text, modifier = modifier.fillMaxWidth(), color = MaterialTheme.colors.onBackground, fontSize = 17.sp, fontWeight = FontWeight.Bold ) } @Composable private fun SettingsDivider() { Divider(color = MaterialTheme.colors.divider) } @Composable private fun SettingsButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, content: @Composable RowScope.() -> Unit ) { UnelevatedButton( onClick = onClick, modifier = modifier, enabled = enabled, colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.onSurface.copy(alpha = 0.1f), disabledBackgroundColor = MaterialTheme.colors.onSurface.copy(alpha = 0.05f) ), content = content ) } private fun Context.executeWeb(theater: Theater) { return when (theater.type) { Theater.TYPE_CGV -> Cgv.executeWeb(this, theater) Theater.TYPE_LOTTE -> LotteCinema.executeWeb(this, theater) Theater.TYPE_MEGABOX -> Megabox.executeWeb(this, theater) else -> throw IllegalArgumentException("${theater.type} is not valid type.") } } private fun Context.goToEmail() { val intent = Intent(Intent.ACTION_SENDTO) intent.data = Uri.parse("mailto:") intent.putExtra(Intent.EXTRA_EMAIL, arrayOf("<EMAIL>")) intent.putExtra( Intent.EXTRA_SUBJECT, "뭅 v${BuildConfig.VERSION_NAME} 버그리포트" ) startActivitySafely(intent) }
8
Kotlin
15
130
be2b359530f5207073175e2e950f41a717bc5ca3
13,852
Moop-Android
Apache License 2.0
app/src/main/java/org/citruscircuits/viewer/fragments/ranking/RankingListAdapter.kt
frc1678
804,234,032
false
{"Kotlin": 418437}
package org.citruscircuits.viewer.fragments.ranking import android.app.Activity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import org.citruscircuits.viewer.R import org.citruscircuits.viewer.data.getTeamObjectByKey import java.util.regex.Pattern /** * Custom list adapter class with aq object handling to display the custom cell for the match schedule. */ class RankingListAdapter(activity: Activity, private val listContents: List<String>) : BaseAdapter() { private val inflater = LayoutInflater.from(activity) /** * @return The size of the match schedule. */ override fun getCount() = listContents.size /** * @return The match object given the match number. */ override fun getItem(position: Int) = listContents[position] /** * @return The position of the cell. */ override fun getItemId(position: Int) = position.toLong() /** * Populates the elements of the custom cell. */ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val viewHolder: ViewHolder val rowView: View? if (convertView == null) { rowView = inflater.inflate(R.layout.seeding_cell, parent, false) viewHolder = ViewHolder(rowView) rowView.tag = viewHolder } else { rowView = convertView viewHolder = rowView.tag as ViewHolder } viewHolder.tvTeamNumber.text = listContents[position] val regex: Pattern = Pattern.compile("[0-9]+" + Regex.escape(".") + "[0-9]+") viewHolder.tvDatapointOne.text = getTeamObject("current_rank", position) val currentAvgRps = getTeamObject( "current_avg_rps", position ) viewHolder.tvDatapointTwo.text = if (currentAvgRps?.let { regex.matcher(it).matches() } == true) { "%.2f".format(currentAvgRps.toFloat()) } else { currentAvgRps } viewHolder.tvDatapointThree.text = getTeamObject("current_rps", position) val predictedRps = getTeamObject("predicted_rps", position) viewHolder.tvDatapointFour.text = if (predictedRps?.let { regex.matcher(it).matches() } == true) { "%.1f".format(predictedRps.toFloat()) } else { predictedRps } viewHolder.tvDatapointFive.text = getTeamObject("predicted_rank", position) return rowView!! } private fun getTeamObject(field: String, position: Int) = getTeamObjectByKey(listContents[position], field) } /** * View holder class to handle the elements used in the custom cells. */ private class ViewHolder(view: View?) { val tvTeamNumber: TextView = view?.findViewById(R.id.tv_team_number)!! val tvDatapointOne: TextView = view?.findViewById(R.id.tv_datapoint_one)!! val tvDatapointTwo: TextView = view?.findViewById(R.id.tv_datapoint_two)!! val tvDatapointThree: TextView = view?.findViewById(R.id.tv_datapoint_three)!! val tvDatapointFour: TextView = view?.findViewById(R.id.tv_datapoint_four)!! val tvDatapointFive: TextView = view?.findViewById(R.id.tv_datapoint_five)!! }
0
Kotlin
0
0
f38e2f99c1b16f6f5a89342b4619c19082346b09
3,245
viewer-2024-public
MIT License
MyPayTemplate/app/src/main/java/br/uea/transirie/mypay/mypaytemplate2/ui/home/Ajustes/EstabelecimentoUsuarioViewModel.kt
gldnjmat17
438,400,051
false
{"Kotlin": 501915}
package br.uea.transirie.mypay.mypaytemplate2.ui.home.Ajustes import android.util.Log import br.uea.transirie.mypay.mypaytemplate2.model.Estabelecimento import br.uea.transirie.mypay.mypaytemplate2.model.Usuario import br.uea.transirie.mypay.mypaytemplate2.repository.room.AppDatabase import br.uea.transirie.mypay.mypaytemplate2.repository.room.EstabelecimentoRepository import br.uea.transirie.mypay.mypaytemplate2.repository.room.UsuarioRepository class EstabelecimentoUsuarioViewModel(appDatabase: AppDatabase) { private var estabelecimentoRepository = EstabelecimentoRepository(appDatabase) private val usuarioRepository = UsuarioRepository(appDatabase) private val usuarios = getUsuarios() fun getUsuarios(): List<Usuario>{ // CoroutineScope(Dispatchers.IO).launch { // val usuarios = usuarioRepository.getAllUsuario() // _usuarios.postValue(usuarios) // } return usuarioRepository.getAllUsuario() } fun estabelecimentoByCPFGerente(cpfGerente: String): Estabelecimento? = estabelecimentoRepository.estabelecimentoByCPFGerente(cpfGerente) fun usuarioByPin(pin: Int): Usuario { val usuario = usuarioRepository.usuarioByPin(pin) if (usuario == null) Log.i("LOGIN_VIEW_MODEL", "Pin não cadastrado no banco de dados") return usuario } fun usuarioByEmail(email: String): Usuario = usuarioRepository.usuarioByEmail(email) fun deleteUsuario(usuario: Usuario) = usuarioRepository.delete(usuario) fun getNumGerentes(): Int = usuarios.filter { it.isGerente }.size fun deleteEstabelecimento(estab: Estabelecimento) = estabelecimentoRepository.delete(estab) fun deleteAllUsuarios() { usuarios.forEach { deleteUsuario(it) } } }
0
Kotlin
0
0
bef2b21101aee9c8f985498532385eee18cb0e05
1,802
MyPets---Aplicativo
MIT License
app/src/main/java/zzzguide/ui/common/BangbooListAdapter.kt
nikunj3011
847,834,199
false
{"Kotlin": 100085}
package zzzguide.ui.common import android.content.Context import android.graphics.Color import android.text.SpannableStringBuilder import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.core.text.bold import androidx.core.text.color import androidx.core.text.italic import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import zzzguide.R import zzzguide.models.api.bangboo.BangBoosResponseItem class BangbooListAdapter( private val contextEcho: Context, private var fruitsList:List<BangBoosResponseItem>, private val clickListener:(BangBoosResponseItem)->Unit ) : RecyclerView.Adapter<MyViewHolder>(){ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val listItem = layoutInflater.inflate(R.layout.layout_bangboo_list,parent,false) return MyViewHolder(listItem) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val fruit = fruitsList[position] holder.bind(contextEcho, fruit, clickListener) } fun setFilteredList(mList: List<BangBoosResponseItem>){ this.fruitsList = mList notifyDataSetChanged() } override fun getItemCount(): Int { return fruitsList.size } } class MyViewHolder(val view: View):RecyclerView.ViewHolder(view){ fun bind(contextEcho: Context, bangboo: BangBoosResponseItem, clickListener:(BangBoosResponseItem)->Unit) { val echoTextView = view.findViewById<TextView>(R.id.bangbooName) echoTextView.text = bangboo?.nick_name val textBangbooDes = view.findViewById<TextView>(R.id.textBangbooDes) textBangbooDes.text = bangboo?.bio val imageViewBangboo = view.findViewById<ImageView>(R.id.imageViewBangboo) Glide.with(view) .load("https://cdn.jsdelivr.net/gh/boringcdn/zzz/bangboos/${bangboo.name}.webp") .diskCacheStrategy(DiskCacheStrategy.RESOURCE) .into(imageViewBangboo) var bangbooSkill1 = SpannableStringBuilder() if(bangboo.skills.isNotEmpty()){ for (skill in bangboo.skills){ bangbooSkill1 = bangbooSkill1.append() .color(Color.WHITE, { append(skill?.name) }) .append(" : ") .bold{ append(skill?.desc) .append("\n")} } } val textViewBangbooSkill1 = view.findViewById<TextView>(R.id.textViewBangbooSkill1) textViewBangbooSkill1.text = bangbooSkill1 var bangbooStats = "Stats- HP: ${bangboo.stats.HP} ATK: ${bangboo.stats.ATK} DEF: ${bangboo.stats.DEF} Impact: ${bangboo.stats.Impact}" val textBangbooStats = view.findViewById<TextView>(R.id.textBangbooStats) textBangbooStats.text = bangbooStats val imageViewBangbooRank = view.findViewById<ImageView>(R.id.imageViewBangbooRank) val viewBangbooRank = view.findViewById<View>(R.id.viewBangbooRank) if (bangboo?.categories?.elementAt(0) != null) { when (bangboo.categories.elementAt(0).name) { "a-rank" -> { Glide.with(view) .load(R.drawable.arank) .into(imageViewBangbooRank) viewBangbooRank.setBackgroundColor(Color.parseColor("#AB3A4E")) } "s-rank" -> { Glide.with(view) .load(R.drawable.srank) .into(imageViewBangbooRank) viewBangbooRank.setBackgroundColor(Color.parseColor("#F9A700")) } else -> { Glide.with(view) .load(R.drawable.srank) .into(imageViewBangbooRank) viewBangbooRank.setBackgroundColor(Color.parseColor("#F9A700")) } } } } }
0
Kotlin
0
0
affa7bdb62afd13d023df60665cd685cc17ff4bc
4,154
ZZZ-Guide-Android
MIT License
src/test/kotlin/ee/studiofrancium/common/i18n/CountryCodeTest.kt
kristo-aun
425,076,491
true
{"Kotlin": 492852}
/* * Copyright (C) 2014-2015 Neo Visionaries Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ee.studiofrancium.common.i18n import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import java.util.* internal class CountryCodeTest { @Test fun test1() { val list: List<CountryCode> = CountryCode.findByName(".*United.*") assertEquals(6, list.size) // AE: United Arab Emirates assertTrue(list.contains(CountryCode.AE)) // GB: United Kingdom assertTrue(list.contains(CountryCode.GB)) // TZ: Tanzania, United Republic of assertTrue(list.contains(CountryCode.TZ)) // UK: United Kingdom assertTrue(list.contains(CountryCode.UK)) // UM: United States Minor Outlying Islands assertTrue(list.contains(CountryCode.UM)) // US: United States assertTrue(list.contains(CountryCode.US)) } @Test fun test2() { assertSame(Locale.CANADA, CountryCode.CA.toLocale()) } @Test fun test3() { assertSame(Locale.CHINA, CountryCode.CN.toLocale()) } @Test fun test4() { assertSame(Locale.GERMANY, CountryCode.DE.toLocale()) } @Test fun test5() { assertSame(Locale.FRANCE, CountryCode.FR.toLocale()) } @Test fun test6() { assertSame(Locale.UK, CountryCode.GB.toLocale()) } @Test fun test7() { assertSame(Locale.ITALY, CountryCode.IT.toLocale()) } @Test fun test8() { assertSame(Locale.JAPAN, CountryCode.JP.toLocale()) } @Test fun test9() { assertSame(Locale.KOREA, CountryCode.KR.toLocale()) } @Test fun test10() { assertSame(Locale.TAIWAN, CountryCode.TW.toLocale()) } @Test fun test11() { assertSame(Locale.US, CountryCode.US.toLocale()) } @Test fun test12() { val undefinedLocale = CountryCode.UNDEFINED.toLocale() try { val root = Locale::class.java.getDeclaredField("ROOT")[null] as Locale assertSame(root, undefinedLocale) } catch (e: Exception) { assertEquals("", undefinedLocale!!.language) assertEquals("", undefinedLocale.country) } } @Test fun test13() { assertSame(CountryCode.UNDEFINED, CountryCode.getByCode("UNDEFINED")) } @Test fun test14() { assertNull(CountryCode.getByCode("undefined")) } @Test fun test15() { assertSame(CountryCode.UNDEFINED, CountryCode.getByCodeIgnoreCase("undefined")) } @Test fun test16() { assertSame(CountryCode.UNDEFINED, CountryCode.getByLocale(Locale("", ""))) } @Test fun test17() { assertNull(CountryCode.getByCode(null)) } @Test fun test18() { assertNull(CountryCode.getByCode("")) } @Test fun test19() { assertSame(CountryCode.AN, CountryCode.getByCode("ANT")) } @Test fun test20() { assertSame(CountryCode.AN, CountryCode.getByCode("ANHH")) } @Test fun test21() { assertSame(CountryCode.BU, CountryCode.getByCode("BUR")) } @Test fun test22() { assertSame(CountryCode.BU, CountryCode.getByCode("BUMM")) } @Test fun test23() { assertSame(CountryCode.CS, CountryCode.getByCode("SCG")) } @Test fun test24() { assertSame(CountryCode.CS, CountryCode.getByCode("CSXX")) } @Test fun test25() { assertSame(CountryCode.NT, CountryCode.getByCode("NTZ")) } @Test fun test26() { assertSame(CountryCode.NT, CountryCode.getByCode("NTHH")) } @Test fun test27() { assertSame(CountryCode.TP, CountryCode.getByCode("TMP")) } @Test fun test28() { assertSame(CountryCode.TP, CountryCode.getByCode("TPTL")) } @Test fun test29() { assertSame(CountryCode.YU, CountryCode.getByCode("YUG")) } @Test fun test30() { assertSame(CountryCode.YU, CountryCode.getByCode("YUCS")) } @Test fun test31() { assertSame(CountryCode.ZR, CountryCode.getByCode("ZAR")) } @Test fun test32() { assertSame(CountryCode.ZR, CountryCode.getByCode("ZRCD")) } @Test fun test33() { for (cc in CountryCode.values()) { val alpha3 = cc.alpha3 ?: continue assertEquals(3, alpha3.length) } } @Test fun test34() { // FI and SF have the same alpha-3 code "FIN". // FI should be returned for "FIN". assertSame(CountryCode.FI, CountryCode.getByCode("FIN")) } @Test fun test35() { // BU and MM have the same numeric code 104. MM should be used. assertSame(CountryCode.MM, CountryCode.getByCode(104)) assertSame(CountryCode.MM, CountryCode.getByCode(CountryCode.BU.numeric)) assertSame(CountryCode.MM, CountryCode.getByCode(CountryCode.MM.numeric)) } @Test fun test36() { // CD and ZR have the same numeric code 180. CD should be used. assertSame(CountryCode.CD, CountryCode.getByCode(180)) assertSame(CountryCode.CD, CountryCode.getByCode(CountryCode.CD.numeric)) assertSame(CountryCode.CD, CountryCode.getByCode(CountryCode.ZR.numeric)) } @Test fun test37() { // FI and SF have the same numeric code 246. FI should be used. assertSame(CountryCode.FI, CountryCode.getByCode(246)) assertSame(CountryCode.FI, CountryCode.getByCode(CountryCode.FI.numeric)) assertSame(CountryCode.FI, CountryCode.getByCode(CountryCode.SF.numeric)) } @Test fun test38() { // GB and UK have the same numeric code 826. GB should be used. assertSame(CountryCode.GB, CountryCode.getByCode(826)) assertSame(CountryCode.GB, CountryCode.getByCode(CountryCode.GB.numeric)) assertSame(CountryCode.GB, CountryCode.getByCode(CountryCode.UK.numeric)) } @Test fun test39() { // TL and TP have the same numeric code 626. GB should be used. assertSame(CountryCode.TL, CountryCode.getByCode(626)) assertSame(CountryCode.TL, CountryCode.getByCode(CountryCode.TL.numeric)) assertSame(CountryCode.TL, CountryCode.getByCode(CountryCode.TP.numeric)) } @Test fun test40() { assertSame(CountryCode.JP, CountryCode.getByCode(392)) } @Test fun test41() { // Checks changed made in version 1.17. assertEquals(249, CountryCode.FX.numeric) assertEquals(810, CountryCode.SU.numeric) assertEquals(626, CountryCode.TP.numeric) assertEquals(826, CountryCode.UK.numeric) assertEquals(180, CountryCode.ZR.numeric) } @Test fun test42() { // Country code 280 should map to 278, due to legacy applications in payment industry. assertEquals(CountryCode.DE, CountryCode.getByCode(280)) } }
0
Kotlin
0
1
7dffa9596b068cb6b710ab244531f1263bf2aab3
7,515
common-i18n
Apache License 2.0