path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/de/jensklingenberg/jetpackcomposeplayground/mysamples/github/material/floatingactionbutton/FabDemo.kt
|
Foso
| 187,719,625
| false
|
{"Kotlin": 106029, "Shell": 5712}
|
package de.jensklingenberg.jetpackcomposeplayground.mysamples.github.material.floatingactionbutton
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
@Composable
fun FloatingActionButtonDemo() {
FloatingActionButton(onClick = { /*do something*/}) {
Text("FloatingActionButton")
}
}
@Composable
fun ExtendedFloatingActionButtonDemo() {
ExtendedFloatingActionButton(
icon = { Icon(Icons.Filled.Favorite,"") },
text = { Text("FloatingActionButton") },
onClick = { /*do something*/ },
elevation = FloatingActionButtonDefaults.elevation(8.dp)
)
}
| 13
|
Kotlin
|
287
| 3,404
|
53b5945345cbc4dcddfd965eb73085096cb8791a
| 764
|
Jetpack-Compose-Playground
|
MIT License
|
acornui-core/src/commonMain/kotlin/com/acornui/filter/ColorTransformationFilter.kt
|
fuzzyweapon
| 130,889,917
| true
|
{"Kotlin": 2963922, "JavaScript": 15366, "HTML": 5956, "Java": 4507}
|
/*
* Copyright 2018 <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.filter
import com.acornui.component.UiComponentRo
import com.acornui.core.di.inject
import com.acornui.gl.core.GlState
import com.acornui.math.ColorTransformation
import com.acornui.math.ColorTransformationRo
import com.acornui.math.MinMaxRo
class ColorTransformationFilter(
target: UiComponentRo,
/**
* The mutable color transformation to be applied.
*/
val colorTransformation: ColorTransformation
) : RenderFilterBase(target) {
private val glState = inject(GlState)
private val combined = ColorTransformation()
private var previous: ColorTransformationRo? = null
override fun beforeRender(clip: MinMaxRo) {
previous = glState.colorTransformation
val previous = previous
if (previous == null) {
glState.colorTransformation = colorTransformation
} else {
combined.set(previous).mul(colorTransformation)
glState.colorTransformation = combined
}
}
override fun afterRender(clip: MinMaxRo) {
glState.colorTransformation = previous
}
}
fun UiComponentRo.colorTransformationFilter(colorTransformation: ColorTransformation = ColorTransformation()): ColorTransformationFilter {
return ColorTransformationFilter(this, colorTransformation)
}
| 0
|
Kotlin
|
1
| 0
|
a57100f894721ee342d23fe8cacb3fcbcedbe6dc
| 1,792
|
acornui
|
Apache License 2.0
|
src/main/kotlin/com/mpaulse/mobitra/DataUsageMonitor.kt
|
mpaulse
| 219,060,709
| false
| null |
/*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mpaulse.mobitra
import com.mpaulse.mobitra.data.MobileDataProduct
import com.mpaulse.mobitra.data.MobileDataProductDB
import com.mpaulse.mobitra.data.MobileDataProductType
import com.mpaulse.mobitra.data.MobileDataProductType.ANYTIME
import com.mpaulse.mobitra.data.MobileDataProductType.NIGHT_SURFER
import com.mpaulse.mobitra.data.MobileDataProductType.OFF_PEAK
import com.mpaulse.mobitra.data.MobileDataProductType.UNSPECIFIED
import com.mpaulse.mobitra.data.MobileDataUsage
import com.mpaulse.mobitra.net.HuaweiMonitoringInfo
import com.mpaulse.mobitra.net.LTE_ONCE_OFF_10MBPS_OFF_PEAK_DATA_RESOURCE_TYPE
import com.mpaulse.mobitra.net.LTE_ONCE_OFF_4MBPS_OFF_PEAK_DATA_RESOURCE_TYPE
import com.mpaulse.mobitra.net.LTE_ONCE_OFF_ANYTIME_DATA_RESOURCE_TYPE
import com.mpaulse.mobitra.net.LTE_ONCE_OFF_NIGHT_SURFER_DATA_RESOURCE_TYPE
import com.mpaulse.mobitra.net.MonitoringAPIClient
import com.mpaulse.mobitra.net.TelkomFreeResource
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.yield
import org.slf4j.LoggerFactory
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit.HOURS
import java.time.temporal.ChronoUnit.MILLIS
import java.util.Collections
import java.util.Locale
import java.util.UUID
class DataUsageMonitor(
routerIPAddress: String?,
private val productDB: MobileDataProductDB,
private val listener: DataUsageMonitorListener
): CoroutineScope by MainScope() {
private var monitoringAPIClient: MonitoringAPIClient? = null
private var monitoringJob: Job? = null
private val activeProductsMap = mutableMapOf<UUID, MobileDataProduct>()
private var activeProductInUse: MobileDataProduct? = null
private var downloadAmountUnrecorded = 0L
private var uploadAmountUnrecorded = 0L
private var updateProducts = true
private val logger = LoggerFactory.getLogger(DataUsageMonitor::class.java)
var routerIPAddress: String? = null
set(value) {
if (value != null) {
if (monitoringAPIClient == null) {
monitoringAPIClient = MonitoringAPIClient(value)
} else {
monitoringAPIClient?.huaweiHost = value
}
} else {
monitoringAPIClient = null
}
}
val activeProducts: Map<UUID, MobileDataProduct>
get() = Collections.unmodifiableMap(activeProductsMap)
val currentProduct: MobileDataProduct?
get() = activeProductInUse
init {
for (product in productDB.getActiveProducts()) {
activeProductsMap[product.id] = product
}
this.routerIPAddress = routerIPAddress
}
fun start() {
monitoringJob = launch(Dispatchers.Default) {
updateProductInfo()
}
}
fun stop() {
monitoringJob?.cancel()
val product = activeProductInUse
if (product != null) {
val dataUsage = MobileDataUsage(downloadAmount = downloadAmountUnrecorded, uploadAmount = uploadAmountUnrecorded)
if (dataUsage.totalAmount > 0) {
if (!product.isUnlimited) {
product.availableAmount -= dataUsage.totalAmount
}
product.usedAmount += dataUsage.totalAmount
if (logger.isDebugEnabled) {
logger.debug("Store product: $product")
}
productDB.storeProduct(product)
if (logger.isDebugEnabled) {
logger.debug("Add data usage:\n\tproduct: $product\n\tusage: $dataUsage")
}
productDB.addDataUsage(product, dataUsage)
}
}
}
private suspend fun updateProductInfo() {
pollDataUsage().collect { dataUsage ->
if (logger.isDebugEnabled) {
logger.debug("Data usage event: $dataUsage")
}
try {
yield()
val telkomFreeResources = monitoringAPIClient?.getTelkomFreeResources()
if (telkomFreeResources != null) {
var msisdn: String? = null
for (resource in telkomFreeResources) {
val product = resourceToProduct(resource) ?: continue
if (msisdn == null) {
msisdn = product.msisdn
}
val prevProductInfo = productDB.getProduct(product.id)
val prevUsedAmount = prevProductInfo?.usedAmount ?: 0
// Correct zero usage amount reported by Telkom.
if (product.usedAmount == 0L) {
product.usedAmount = prevUsedAmount
if (prevProductInfo != null && product.availableAmount < prevProductInfo.availableAmount) {
product.usedAmount += prevProductInfo.availableAmount - product.availableAmount
}
}
if (logger.isDebugEnabled) {
logger.debug("Store product: $product")
}
productDB.storeProduct(product)
activeProductsMap[product.id] = product
if (product.usedAmount != prevUsedAmount) {
val uncategorisedAmount = product.usedAmount - prevUsedAmount
var dataUsageToAdd =
if (activeProductInUse?.id == product.id) {
dataUsage.copy(uncategorisedAmount = uncategorisedAmount - (dataUsage.downloadAmount + dataUsage.uploadAmount))
} else {
MobileDataUsage(uncategorisedAmount = uncategorisedAmount)
}
if (!product.isUnlimited && dataUsageToAdd.totalAmount > product.availableAmount) {
val overExhaustedAmount = dataUsageToAdd.totalAmount - product.availableAmount
if (logger.isDebugEnabled) {
logger.debug("Forcing zero available amount for over-exhausted product: $product")
logger.debug("Over-exhausted amount: $overExhaustedAmount")
}
dataUsageToAdd = dataUsageToAdd.copy(uncategorisedAmount = dataUsageToAdd.uncategorisedAmount - overExhaustedAmount)
product.availableAmount = 0
productDB.storeProduct(product)
}
if (dataUsageToAdd.totalAmount != 0L) {
if (logger.isDebugEnabled) {
logger.debug("Add data usage:\n\tproduct: $product\n\tusage: $dataUsageToAdd")
}
productDB.addDataUsage(product, dataUsageToAdd)
}
}
}
val expiredProductIds = mutableListOf<UUID>()
for (product in activeProductsMap.values) {
if (product.isExpired) {
expiredProductIds += product.id
}
}
for (productId in expiredProductIds) {
activeProductsMap.remove(productId)
}
activeProductInUse = if (msisdn != null) getActiveProductInUse(msisdn) else null
if (logger.isDebugEnabled) {
logger.debug("Active product: $activeProductInUse")
}
listener.onActiveProductsUpdate()
}
updateProducts = false
} catch (e: Exception) {
if (e is CancellationException) {
throw e
}
updateProducts = true
listener.onDataUsageMonitoringException(
DataUsageMonitoringException("Error retrieving usage information from Telkom", e))
}
}
}
private fun pollDataUsage() = flow {
var lastMonitoringInfo: HuaweiMonitoringInfo? = null
var downloadAmountPolled: Long
var downloadAmountTotal = 0L
var uploadAmountPolled: Long
var uploadAmountTotal = 0L
val pollDelay = 5000L
while (true) {
try {
yield()
val monitoringInfo = monitoringAPIClient?.getHuaweiMonitoringInfo()
if (monitoringInfo != null) {
downloadAmountPolled = -1L
uploadAmountPolled = -1L
if (lastMonitoringInfo != null
&& monitoringInfo.deviceInfo.deviceName == lastMonitoringInfo.deviceInfo.deviceName
&& monitoringInfo.wirelessLANSettings.ssid == lastMonitoringInfo.wirelessLANSettings.ssid) {
downloadAmountPolled = monitoringInfo.trafficStats.currentDownloadAmount - lastMonitoringInfo.trafficStats.currentDownloadAmount
uploadAmountPolled = monitoringInfo.trafficStats.currentUploadAmount - lastMonitoringInfo.trafficStats.currentUploadAmount
}
if (downloadAmountPolled >= 0 && uploadAmountPolled >= 0) {
downloadAmountUnrecorded += downloadAmountPolled
downloadAmountTotal += downloadAmountPolled
uploadAmountUnrecorded += uploadAmountPolled
uploadAmountTotal += uploadAmountPolled
listener.onDataTrafficUpdate(
MobileDataUsage(downloadAmount = downloadAmountPolled, uploadAmount = uploadAmountPolled),
MobileDataUsage(downloadAmount = downloadAmountTotal, uploadAmount = uploadAmountTotal))
}
if (logger.isDebugEnabled) {
logger.debug("Unrecorded traffic: download = $downloadAmountUnrecorded B, upload = $uploadAmountUnrecorded B")
}
// Emit event if:
// - the data usage needs to be recorded and products from Telkom refreshed
// - there is a router restart or a switch a different router (d < 0 or u < 0)
// - the product remaining amount gets consumed
if (updateProducts
|| (downloadAmountPolled < 0 || uploadAmountPolled < 0)
|| (activeProductInUse != null
&& !activeProductInUse!!.isUnlimited
&& (downloadAmountUnrecorded + uploadAmountUnrecorded) >= activeProductInUse!!.availableAmount)) {
emit(MobileDataUsage(
downloadAmount = downloadAmountUnrecorded,
uploadAmount = uploadAmountUnrecorded))
if (!updateProducts) {
downloadAmountUnrecorded = 0
uploadAmountUnrecorded = 0
}
}
lastMonitoringInfo = monitoringInfo
}
// Delay until just the next hour mark when we emit an event,
// or within 5 seconds, whichever comes first.
val now = LocalDateTime.now()
var t = now.until(now.truncatedTo(HOURS).plusHours(1), MILLIS)
if (t > pollDelay) {
t = pollDelay
} else {
updateProducts = true
}
if (logger.isDebugEnabled) {
logger.debug("Poll in ${t}ms")
}
delay(t)
} catch (e: Exception) {
if (e is CancellationException) {
throw e
}
updateProducts = true
lastMonitoringInfo = null
listener.onDataUsageMonitoringException(
DataUsageMonitoringException("Error retrieving data traffic information from router", e))
delay(pollDelay)
}
}
}
private fun resourceToProduct(resource: TelkomFreeResource): MobileDataProduct? {
val activationDate = resource.activationDate ?: return null
var type = when (resource.type) {
LTE_ONCE_OFF_ANYTIME_DATA_RESOURCE_TYPE -> ANYTIME
LTE_ONCE_OFF_NIGHT_SURFER_DATA_RESOURCE_TYPE -> NIGHT_SURFER
LTE_ONCE_OFF_4MBPS_OFF_PEAK_DATA_RESOURCE_TYPE,
LTE_ONCE_OFF_10MBPS_OFF_PEAK_DATA_RESOURCE_TYPE -> OFF_PEAK
else -> UNSPECIFIED
}
if (type == UNSPECIFIED) {
if ("off peak" in resource.name.lowercase(Locale.getDefault())) {
type = OFF_PEAK // Unlimited
} else {
return null
}
}
return MobileDataProduct(
resource.id,
resource.msisdn,
resource.name,
type,
resource.availableAmount,
resource.usedAmount,
activationDate,
resource.expiryDate)
}
private fun getActiveProductInUse(msisdn: String): MobileDataProduct? {
var productInUse: MobileDataProduct? = null
val now = LocalDateTime.now()
if (now.hour in 0..6) {
productInUse = getProductInUseOfType(msisdn, NIGHT_SURFER)
}
if (productInUse == null && now.hour in 0..18) {
productInUse = getProductInUseOfType(msisdn, OFF_PEAK)
}
if (productInUse == null) {
productInUse = getProductInUseOfType(msisdn, ANYTIME)
}
return productInUse
}
private fun getProductInUseOfType(msisdn: String, type: MobileDataProductType): MobileDataProduct? {
val candidateProducts = mutableListOf<MobileDataProduct>()
for (product in activeProductsMap.values) {
if (product.msisdn == msisdn
&& product.type == type
&& (product.isUnlimited || (!product.isUnlimited && product.availableAmount > 0))) {
if (candidateProducts.isEmpty()) {
candidateProducts += product
} else {
val p = candidateProducts[0]
if (product.activationDate < p.activationDate) {
candidateProducts.clear()
}
if (product.activationDate <= p.activationDate) {
candidateProducts += product
}
}
}
}
candidateProducts.sortBy {
it.initialAvailableAmount
}
return if (candidateProducts.isEmpty()) null
else candidateProducts[candidateProducts.size - 1]
}
}
class DataUsageMonitoringException(
message: String, cause: Throwable? = null
): Exception(message, cause)
| 0
|
Kotlin
|
0
| 0
|
613e58a0558fcb771ac409c0ff92cdcdb36a81ca
| 16,706
|
mobitra
|
MIT License
|
src/main/kotlin/com/mpaulse/mobitra/DataUsageMonitor.kt
|
mpaulse
| 219,060,709
| false
| null |
/*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mpaulse.mobitra
import com.mpaulse.mobitra.data.MobileDataProduct
import com.mpaulse.mobitra.data.MobileDataProductDB
import com.mpaulse.mobitra.data.MobileDataProductType
import com.mpaulse.mobitra.data.MobileDataProductType.ANYTIME
import com.mpaulse.mobitra.data.MobileDataProductType.NIGHT_SURFER
import com.mpaulse.mobitra.data.MobileDataProductType.OFF_PEAK
import com.mpaulse.mobitra.data.MobileDataProductType.UNSPECIFIED
import com.mpaulse.mobitra.data.MobileDataUsage
import com.mpaulse.mobitra.net.HuaweiMonitoringInfo
import com.mpaulse.mobitra.net.LTE_ONCE_OFF_10MBPS_OFF_PEAK_DATA_RESOURCE_TYPE
import com.mpaulse.mobitra.net.LTE_ONCE_OFF_4MBPS_OFF_PEAK_DATA_RESOURCE_TYPE
import com.mpaulse.mobitra.net.LTE_ONCE_OFF_ANYTIME_DATA_RESOURCE_TYPE
import com.mpaulse.mobitra.net.LTE_ONCE_OFF_NIGHT_SURFER_DATA_RESOURCE_TYPE
import com.mpaulse.mobitra.net.MonitoringAPIClient
import com.mpaulse.mobitra.net.TelkomFreeResource
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.yield
import org.slf4j.LoggerFactory
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit.HOURS
import java.time.temporal.ChronoUnit.MILLIS
import java.util.Collections
import java.util.Locale
import java.util.UUID
class DataUsageMonitor(
routerIPAddress: String?,
private val productDB: MobileDataProductDB,
private val listener: DataUsageMonitorListener
): CoroutineScope by MainScope() {
private var monitoringAPIClient: MonitoringAPIClient? = null
private var monitoringJob: Job? = null
private val activeProductsMap = mutableMapOf<UUID, MobileDataProduct>()
private var activeProductInUse: MobileDataProduct? = null
private var downloadAmountUnrecorded = 0L
private var uploadAmountUnrecorded = 0L
private var updateProducts = true
private val logger = LoggerFactory.getLogger(DataUsageMonitor::class.java)
var routerIPAddress: String? = null
set(value) {
if (value != null) {
if (monitoringAPIClient == null) {
monitoringAPIClient = MonitoringAPIClient(value)
} else {
monitoringAPIClient?.huaweiHost = value
}
} else {
monitoringAPIClient = null
}
}
val activeProducts: Map<UUID, MobileDataProduct>
get() = Collections.unmodifiableMap(activeProductsMap)
val currentProduct: MobileDataProduct?
get() = activeProductInUse
init {
for (product in productDB.getActiveProducts()) {
activeProductsMap[product.id] = product
}
this.routerIPAddress = routerIPAddress
}
fun start() {
monitoringJob = launch(Dispatchers.Default) {
updateProductInfo()
}
}
fun stop() {
monitoringJob?.cancel()
val product = activeProductInUse
if (product != null) {
val dataUsage = MobileDataUsage(downloadAmount = downloadAmountUnrecorded, uploadAmount = uploadAmountUnrecorded)
if (dataUsage.totalAmount > 0) {
if (!product.isUnlimited) {
product.availableAmount -= dataUsage.totalAmount
}
product.usedAmount += dataUsage.totalAmount
if (logger.isDebugEnabled) {
logger.debug("Store product: $product")
}
productDB.storeProduct(product)
if (logger.isDebugEnabled) {
logger.debug("Add data usage:\n\tproduct: $product\n\tusage: $dataUsage")
}
productDB.addDataUsage(product, dataUsage)
}
}
}
private suspend fun updateProductInfo() {
pollDataUsage().collect { dataUsage ->
if (logger.isDebugEnabled) {
logger.debug("Data usage event: $dataUsage")
}
try {
yield()
val telkomFreeResources = monitoringAPIClient?.getTelkomFreeResources()
if (telkomFreeResources != null) {
var msisdn: String? = null
for (resource in telkomFreeResources) {
val product = resourceToProduct(resource) ?: continue
if (msisdn == null) {
msisdn = product.msisdn
}
val prevProductInfo = productDB.getProduct(product.id)
val prevUsedAmount = prevProductInfo?.usedAmount ?: 0
// Correct zero usage amount reported by Telkom.
if (product.usedAmount == 0L) {
product.usedAmount = prevUsedAmount
if (prevProductInfo != null && product.availableAmount < prevProductInfo.availableAmount) {
product.usedAmount += prevProductInfo.availableAmount - product.availableAmount
}
}
if (logger.isDebugEnabled) {
logger.debug("Store product: $product")
}
productDB.storeProduct(product)
activeProductsMap[product.id] = product
if (product.usedAmount != prevUsedAmount) {
val uncategorisedAmount = product.usedAmount - prevUsedAmount
var dataUsageToAdd =
if (activeProductInUse?.id == product.id) {
dataUsage.copy(uncategorisedAmount = uncategorisedAmount - (dataUsage.downloadAmount + dataUsage.uploadAmount))
} else {
MobileDataUsage(uncategorisedAmount = uncategorisedAmount)
}
if (!product.isUnlimited && dataUsageToAdd.totalAmount > product.availableAmount) {
val overExhaustedAmount = dataUsageToAdd.totalAmount - product.availableAmount
if (logger.isDebugEnabled) {
logger.debug("Forcing zero available amount for over-exhausted product: $product")
logger.debug("Over-exhausted amount: $overExhaustedAmount")
}
dataUsageToAdd = dataUsageToAdd.copy(uncategorisedAmount = dataUsageToAdd.uncategorisedAmount - overExhaustedAmount)
product.availableAmount = 0
productDB.storeProduct(product)
}
if (dataUsageToAdd.totalAmount != 0L) {
if (logger.isDebugEnabled) {
logger.debug("Add data usage:\n\tproduct: $product\n\tusage: $dataUsageToAdd")
}
productDB.addDataUsage(product, dataUsageToAdd)
}
}
}
val expiredProductIds = mutableListOf<UUID>()
for (product in activeProductsMap.values) {
if (product.isExpired) {
expiredProductIds += product.id
}
}
for (productId in expiredProductIds) {
activeProductsMap.remove(productId)
}
activeProductInUse = if (msisdn != null) getActiveProductInUse(msisdn) else null
if (logger.isDebugEnabled) {
logger.debug("Active product: $activeProductInUse")
}
listener.onActiveProductsUpdate()
}
updateProducts = false
} catch (e: Exception) {
if (e is CancellationException) {
throw e
}
updateProducts = true
listener.onDataUsageMonitoringException(
DataUsageMonitoringException("Error retrieving usage information from Telkom", e))
}
}
}
private fun pollDataUsage() = flow {
var lastMonitoringInfo: HuaweiMonitoringInfo? = null
var downloadAmountPolled: Long
var downloadAmountTotal = 0L
var uploadAmountPolled: Long
var uploadAmountTotal = 0L
val pollDelay = 5000L
while (true) {
try {
yield()
val monitoringInfo = monitoringAPIClient?.getHuaweiMonitoringInfo()
if (monitoringInfo != null) {
downloadAmountPolled = -1L
uploadAmountPolled = -1L
if (lastMonitoringInfo != null
&& monitoringInfo.deviceInfo.deviceName == lastMonitoringInfo.deviceInfo.deviceName
&& monitoringInfo.wirelessLANSettings.ssid == lastMonitoringInfo.wirelessLANSettings.ssid) {
downloadAmountPolled = monitoringInfo.trafficStats.currentDownloadAmount - lastMonitoringInfo.trafficStats.currentDownloadAmount
uploadAmountPolled = monitoringInfo.trafficStats.currentUploadAmount - lastMonitoringInfo.trafficStats.currentUploadAmount
}
if (downloadAmountPolled >= 0 && uploadAmountPolled >= 0) {
downloadAmountUnrecorded += downloadAmountPolled
downloadAmountTotal += downloadAmountPolled
uploadAmountUnrecorded += uploadAmountPolled
uploadAmountTotal += uploadAmountPolled
listener.onDataTrafficUpdate(
MobileDataUsage(downloadAmount = downloadAmountPolled, uploadAmount = uploadAmountPolled),
MobileDataUsage(downloadAmount = downloadAmountTotal, uploadAmount = uploadAmountTotal))
}
if (logger.isDebugEnabled) {
logger.debug("Unrecorded traffic: download = $downloadAmountUnrecorded B, upload = $uploadAmountUnrecorded B")
}
// Emit event if:
// - the data usage needs to be recorded and products from Telkom refreshed
// - there is a router restart or a switch a different router (d < 0 or u < 0)
// - the product remaining amount gets consumed
if (updateProducts
|| (downloadAmountPolled < 0 || uploadAmountPolled < 0)
|| (activeProductInUse != null
&& !activeProductInUse!!.isUnlimited
&& (downloadAmountUnrecorded + uploadAmountUnrecorded) >= activeProductInUse!!.availableAmount)) {
emit(MobileDataUsage(
downloadAmount = downloadAmountUnrecorded,
uploadAmount = uploadAmountUnrecorded))
if (!updateProducts) {
downloadAmountUnrecorded = 0
uploadAmountUnrecorded = 0
}
}
lastMonitoringInfo = monitoringInfo
}
// Delay until just the next hour mark when we emit an event,
// or within 5 seconds, whichever comes first.
val now = LocalDateTime.now()
var t = now.until(now.truncatedTo(HOURS).plusHours(1), MILLIS)
if (t > pollDelay) {
t = pollDelay
} else {
updateProducts = true
}
if (logger.isDebugEnabled) {
logger.debug("Poll in ${t}ms")
}
delay(t)
} catch (e: Exception) {
if (e is CancellationException) {
throw e
}
updateProducts = true
lastMonitoringInfo = null
listener.onDataUsageMonitoringException(
DataUsageMonitoringException("Error retrieving data traffic information from router", e))
delay(pollDelay)
}
}
}
private fun resourceToProduct(resource: TelkomFreeResource): MobileDataProduct? {
val activationDate = resource.activationDate ?: return null
var type = when (resource.type) {
LTE_ONCE_OFF_ANYTIME_DATA_RESOURCE_TYPE -> ANYTIME
LTE_ONCE_OFF_NIGHT_SURFER_DATA_RESOURCE_TYPE -> NIGHT_SURFER
LTE_ONCE_OFF_4MBPS_OFF_PEAK_DATA_RESOURCE_TYPE,
LTE_ONCE_OFF_10MBPS_OFF_PEAK_DATA_RESOURCE_TYPE -> OFF_PEAK
else -> UNSPECIFIED
}
if (type == UNSPECIFIED) {
if ("off peak" in resource.name.lowercase(Locale.getDefault())) {
type = OFF_PEAK // Unlimited
} else {
return null
}
}
return MobileDataProduct(
resource.id,
resource.msisdn,
resource.name,
type,
resource.availableAmount,
resource.usedAmount,
activationDate,
resource.expiryDate)
}
private fun getActiveProductInUse(msisdn: String): MobileDataProduct? {
var productInUse: MobileDataProduct? = null
val now = LocalDateTime.now()
if (now.hour in 0..6) {
productInUse = getProductInUseOfType(msisdn, NIGHT_SURFER)
}
if (productInUse == null && now.hour in 0..18) {
productInUse = getProductInUseOfType(msisdn, OFF_PEAK)
}
if (productInUse == null) {
productInUse = getProductInUseOfType(msisdn, ANYTIME)
}
return productInUse
}
private fun getProductInUseOfType(msisdn: String, type: MobileDataProductType): MobileDataProduct? {
val candidateProducts = mutableListOf<MobileDataProduct>()
for (product in activeProductsMap.values) {
if (product.msisdn == msisdn
&& product.type == type
&& (product.isUnlimited || (!product.isUnlimited && product.availableAmount > 0))) {
if (candidateProducts.isEmpty()) {
candidateProducts += product
} else {
val p = candidateProducts[0]
if (product.activationDate < p.activationDate) {
candidateProducts.clear()
}
if (product.activationDate <= p.activationDate) {
candidateProducts += product
}
}
}
}
candidateProducts.sortBy {
it.initialAvailableAmount
}
return if (candidateProducts.isEmpty()) null
else candidateProducts[candidateProducts.size - 1]
}
}
class DataUsageMonitoringException(
message: String, cause: Throwable? = null
): Exception(message, cause)
| 0
|
Kotlin
|
0
| 0
|
613e58a0558fcb771ac409c0ff92cdcdb36a81ca
| 16,706
|
mobitra
|
MIT License
|
kotlin-electron/src/jsMain/generated/electron/main/NotificationAction.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11400167, "JavaScript": 146545}
|
package electron.main
typealias NotificationAction = electron.core.NotificationAction
| 28
|
Kotlin
|
173
| 1,250
|
d1f8f5d805ffa18431dfefb7a1aa2f67f48915f6
| 88
|
kotlin-wrappers
|
Apache License 2.0
|
kotlin-electron/src/jsMain/generated/electron/main/NotificationAction.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11400167, "JavaScript": 146545}
|
package electron.main
typealias NotificationAction = electron.core.NotificationAction
| 28
|
Kotlin
|
173
| 1,250
|
d1f8f5d805ffa18431dfefb7a1aa2f67f48915f6
| 88
|
kotlin-wrappers
|
Apache License 2.0
|
library/src/main/java/com/shevelev/page_turning_lib/page_curling/ResizingState.kt
|
AlShevelev
| 398,846,673
| false
| null |
/*
* Copyright (c) 2021 <NAME>
*
* Licensed under the MIT License;
* ---------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.shevelev.page_turning_lib.page_curling
class ResizingState(margins: Margins, scaleFactor: Float) {
// Margins of OGL-view - for smooth image
var margins: Margins? = null
private set
// Zoom of OGL-camera - for fast resizing (1: in-screen image; 2: zoom value1 2)
private var currentScaleFactor = MIN_SCALE
var isResized = false
private set
var scaleFactor: Float
get() = currentScaleFactor
set(scaleFactor) {
currentScaleFactor = rangeValue(scaleFactor, MIN_SCALE, MAX_SCALE)
if (currentScaleFactor <= MIN_SCALE + (MAX_SCALE - MIN_SCALE) * 0.05f) {
currentScaleFactor = MIN_SCALE
}
isResized = currentScaleFactor != MIN_SCALE
}
init {
initMargins(margins)
this.scaleFactor = scaleFactor
}
fun recalculateMarginsByScaleFactor() {
val oneMargin = MIN_MARGIN * ((currentScaleFactor - MIN_SCALE) / (MAX_SCALE - MIN_SCALE))
margins = Margins(oneMargin, oneMargin, oneMargin, oneMargin)
}
private fun rangeValue(value: Float, minValue: Float, maxValue: Float): Float =
when {
value < minValue -> minValue
value > maxValue -> maxValue
else -> value
}
fun updateScaleFactor(value: Float) {
scaleFactor = currentScaleFactor + value
}
private fun initMargins(margins: Margins) {
this.margins = Margins(rangeValue(margins.left, MIN_MARGIN, MAX_MARGIN),
rangeValue(margins.top, MIN_MARGIN, MAX_MARGIN),
rangeValue(margins.right, MIN_MARGIN, MAX_MARGIN),
rangeValue(margins.bottom, MIN_MARGIN, MAX_MARGIN))
}
companion object {
const val MAX_MARGIN = 0f
const val MIN_MARGIN = -0.5f
const val MIN_SCALE = 1f
const val MAX_SCALE = 2f
}
}
| 3
|
Kotlin
|
0
| 6
|
11cef6855d3808fd22579d6eb96b6d0eea103e21
| 3,075
|
PageTurningLib
|
MIT License
|
componentlibrary/src/main/java/com/vallem/componentlibrary/ui/appbar/SylphBottomBar.kt
|
leonardovallem
| 613,461,263
| false
|
{"Kotlin": 308660}
|
package com.vallem.componentlibrary.ui.appbar
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Add
import androidx.compose.material.icons.rounded.LocationSearching
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.vallem.componentlibrary.ui.model.SylphShortcut
import com.vallem.componentlibrary.ui.theme.TransFlagColors
@Composable
fun <T : SylphShortcut> SylphBottomBar(
shortcuts: Set<T>,
onShortcutClick: (T) -> Unit,
modifier: Modifier = Modifier,
floatingActionButton: @Composable () -> Unit = {}
) {
BottomAppBar(
actions = {
shortcuts.forEach {
IconButton(onClick = { onShortcutClick(it) }) {
Icon(
imageVector = it.icon,
contentDescription = it.label,
)
}
}
},
floatingActionButton = floatingActionButton,
containerColor = TransFlagColors.Blue,
contentColor = TransFlagColors.OnBlue,
modifier = modifier
)
}
@Preview
@Composable
private fun SylphBottomBarPreview() {
SylphBottomBar(
shortcuts = setOf(
object : SylphShortcut {
override val label = "Adicionar evento"
override val icon = Icons.Rounded.Add
}
),
onShortcutClick = {},
modifier = Modifier.fillMaxWidth()
) {
FloatingActionButton(
onClick = {},
containerColor = TransFlagColors.Pink,
modifier = Modifier.shadow(
elevation = 6.dp,
shape = RoundedCornerShape(16.dp),
ambientColor = Color(0xFF3F3F3F)
)
) {
Icon(imageVector = Icons.Rounded.LocationSearching, null)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
27615ff4672845892d2150ed7069702b521115ef
| 2,340
|
sylph
|
MIT License
|
measurer/src/commonMain/kotlin/com/github/soushin/measurer/httpclient/HttpClient.kt
|
soushin
| 171,784,688
| false
| null |
package com.github.soushin.measurer.httpclient
abstract class HttpClient {
abstract class Request {
abstract val method: String
abstract val path: String
abstract val userAgent: String
open val body: String? = null
open val headers = emptyMap<String, String>()
open val queries = emptyMap<String, String>()
}
abstract val baseUrl: String
abstract val client: Client
suspend fun request(request: Request) = client.call(baseUrl, request) {
this.error(it)
}
abstract fun error(statusCode: Int)
}
| 0
|
Kotlin
|
0
| 8
|
203da2e72e8ee11d32673b59801e4c3db6e5f3c3
| 582
|
measurer
|
Apache License 2.0
|
app/src/main/kotlin/android/emu6502/instructions/impl/ADC.kt
|
felipecsl
| 37,146,897
| false
| null |
package android.emu6502.instructions.impl
import android.emu6502.CPU
import android.emu6502.instructions.BaseInstruction
import android.emu6502.instructions.Instruction
/** ADd with Carry */
class ADC(private val cpu: CPU) : BaseInstruction(Instruction.ADC, cpu) {
override fun immediate() {
testADC(cpu.popByte())
}
private fun testADC(value: Int) {
var tmp: Int
if (cpu.A.xor(value).and(0x80) != 0) {
cpu.CLV()
} else {
cpu.setOverflow()
}
if (cpu.decimalMode()) {
tmp = cpu.A.and(0xf) + value.and(0xf) + cpu.P.and(1)
if (tmp >= 10) {
tmp = 0x10.or((tmp + 6).and(0xf))
}
tmp += cpu.A.and(0xf0) + value.and(0xf0)
if (tmp >= 160) {
cpu.SEC()
if (cpu.overflow() && tmp >= 0x180) {
cpu.CLV()
}
tmp += 0x60
} else {
cpu.CLC()
if (cpu.overflow() && tmp < 0x80) {
cpu.CLV()
}
}
} else {
tmp = cpu.A + value + cpu.P.and(1)
if (tmp >= 0x100) {
cpu.SEC()
if (cpu.overflow() && tmp >= 0x180) {
cpu.CLV()
}
} else {
cpu.CLC()
if (cpu.overflow() && tmp < 0x80) {
cpu.CLV()
}
}
}
cpu.A = tmp.and(0xff)
cpu.setSZFlagsForRegA()
}
}
| 0
|
Kotlin
|
3
| 13
|
b928d84c4911db28cdd2973fd87d3d6ba4d18ea5
| 1,299
|
6502Android
|
Apache License 2.0
|
TripKitAndroid/src/main/java/com/skedgo/tripkit/notification/Notification.kt
|
skedgo
| 38,415,407
| false
|
{"Java": 815763, "Kotlin": 434506}
|
package com.skedgo.tripkit.notification
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
fun Context.createNotification(
channelId: String,
smallIcon: Int? = null,
largeIcon: Bitmap? = null,
contentTitle: String? = null,
contentText: String? = null,
groupAlertBehavior: Int? = null,
groupKey: String? = null,
groupSummary: Boolean = false,
sound: Uri? = null,
autoCancel: Boolean = true,
bigText: String? = null,
intent: Intent? = null,
priority: Int = NotificationCompat.PRIORITY_DEFAULT
): Notification {
val builder = NotificationCompat.Builder(this, channelId)
smallIcon?.let { builder.setSmallIcon(it) }
largeIcon?.let { builder.setLargeIcon(it) }
contentTitle?.let { builder.setContentTitle(it) }
contentText?.let { builder.setContentText(it) }
groupAlertBehavior?.let { builder.setGroupAlertBehavior(it) }
groupKey?.let { builder.setGroup(it) }
sound?.let { builder.setSound(it, AudioManager.STREAM_SYSTEM) }
bigText?.let { builder.setStyle(NotificationCompat.BigTextStyle().bigText(it)) }
builder.setGroupSummary(groupSummary)
builder.setAutoCancel(autoCancel)
builder.priority = priority
intent?.let {
builder.setContentIntent(
PendingIntent.getActivity(
this, 0, it, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
}
return builder.build()
}
@RequiresApi(Build.VERSION_CODES.O)
fun Context.createNotificationChannels(channels: List<NotificationChannel>) {
val notificationManager = this.getSystemService(NotificationManager::class.java)
notificationManager?.createNotificationChannels(channels)
}
@RequiresApi(Build.VERSION_CODES.O)
fun createChannel(id: String, name: String): NotificationChannel {
return NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH)
}
fun Notification.fire(context: Context, id: Int? = null) {
NotificationManagerCompat.from(context).notify(id ?: this.hashCode(), this)
}
fun Context.cancelChannelNotifications(id: Int) {
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(id)
}
| 2
|
Java
|
3
| 4
|
55fd2ddc7692ccf183499c387bdab32476732bdc
| 2,706
|
tripkit-android
|
Apache License 2.0
|
packages/cli/src/main/kotlin/elide/tool/cli/GuestLanguage.kt
|
elide-dev
| 506,113,888
| false
| null |
package elide.tool.cli
/** Specifies languages supported for REPL access. */
internal enum class GuestLanguage constructor (
internal val id: String,
internal val formalName: String,
internal val experimental: Boolean = false,
internal val extensions: List<String> = emptyList(),
internal val mimeTypes: List<String> = emptyList(),
) : elide.runtime.gvm.GuestLanguage {
/** Interactive JavaScript VM. */
JS (
id = "js",
formalName = "JavaScript",
experimental = true,
extensions = listOf("js", "cjs", "mjs"),
mimeTypes = listOf("application/javascript", "application/ecmascript"),
);
companion object {
/** @return Language based on the provided ID, or `null`. */
internal fun resolveFromId(id: String): GuestLanguage? = when (id) {
JS.id -> JS
else -> null
}
}
/** @inheritDoc */
override val symbol: String get() = id
/** @inheritDoc */
override val label: String get() = formalName
}
| 36
|
Kotlin
|
4
| 33
|
91800dbbf291e65a91d451ed50c9673d82efd174
| 963
|
elide
|
MIT License
|
feature/about/src/main/java/io/github/droidkaigi/confsched2020/about/ui/item/AboutTextItem.kt
|
DroidKaigi
| 202,978,106
| false
| null |
package io.github.droidkaigi.confsched2020.about.ui.item
import com.squareup.inject.assisted.Assisted
import com.squareup.inject.assisted.AssistedInject
import com.xwray.groupie.databinding.BindableItem
import io.github.droidkaigi.confsched2020.about.R
import io.github.droidkaigi.confsched2020.about.databinding.ItemAboutTextBinding
class AboutTextItem @AssistedInject constructor(
@Assisted private val name: String,
@Assisted private val content: String
) : BindableItem<ItemAboutTextBinding>() {
override fun getLayout(): Int = R.layout.item_about_text
override fun bind(viewBinding: ItemAboutTextBinding, position: Int) {
viewBinding.title.text = name
viewBinding.content.text = content
}
@AssistedInject.Factory
interface Factory {
fun create(
name: String,
content: String
): AboutTextItem
}
}
| 46
|
Kotlin
|
331
| 785
|
4c5533e4611d4bf6007284dd1f61db2fc92eb0ae
| 893
|
conference-app-2020
|
Apache License 2.0
|
app/src/main/java/home/smart/fly/animations/webview/NestedWebViewActivity.kt
|
REBOOTERS
| 65,188,539
| false
| null |
package home.smart.fly.animations.webview
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ScrollView
import androidx.appcompat.app.AppCompatActivity
import home.smart.fly.animations.R
class NestedWebViewActivity : AppCompatActivity() {
private val TAG = "NestedWebViewActivity"
private val BASE_URL = "https://www.baidu.com"
private lateinit var webView: CustomWebView
private lateinit var scrollView: ScrollView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nested_web_view)
webView = findViewById(R.id.webView)
scrollView = findViewById(R.id.scrollView)
webView.loadUrl(BASE_URL)
val settings = webView.settings
settings.javaScriptEnabled = true
settings.useWideViewPort = true
webView.webViewClient = (object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
return false
}
})
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
webView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
Log.e(TAG, "webView---------scrollY=" + scrollY)
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
scrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
Log.e(TAG, "ScrollView-scrollY=" + scrollY)
}
}
}
}
| 4
| null |
352
| 1,880
|
278998c8da1da2b47778dba3dbd3f2de1e12f2ed
| 1,723
|
AndroidAnimationExercise
|
Apache License 2.0
|
app/src/main/java/com/livin/square/module/repo/MainRepository.kt
|
Livinlawrence
| 380,013,816
| false
| null |
package com.livin.square.module.repo
import android.app.Application
import com.livin.square.module.model.Repo
import com.livin.square.module.repo.RepoNetworkDataAssembler.generateDataModel
import com.livin.square.network.ApiHelper
import com.livin.square.util.isNetworkAvailable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class MainRepository @Inject constructor(
private val application: Application,
private val apiHelper: ApiHelper
) {
suspend fun getRepos(): MutableList<Repo> {
return withContext(Dispatchers.IO) {
val dataModel: MutableList<Repo> = mutableListOf()
if (application.isNetworkAvailable()) {
try {
val response = apiHelper.getRepos()
if (response.isSuccessful){
response.body()?.let {
generateDataModel(it,dataModel)
}?:kotlin.run {
throw Exception("Please try again later")
}
}else{
throw Exception("Please try again later")
}
}catch (exception:Exception){
exception.printStackTrace()
throw Exception("Please try again later")
}
} else {
throw Exception("Please check your internet connection")
}
dataModel
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d93f1c315070d6643668783831e08bc9951d8255
| 1,522
|
Square_Repo_Listing
|
Apache License 2.0
|
app/src/main/java/com/zerowater/environment/data/source/RemoteDataSource.kt
|
byzerowater
| 264,695,996
| false
|
{"Gradle": 3, "Java Properties": 3, "Markdown": 2, "Shell": 2, "Text": 1, "Ignore List": 2, "Batchfile": 2, "YAML": 1, "Proguard": 1, "XML": 29, "Kotlin": 54, "Java": 1}
|
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zerowater.environment.data.source
import com.zerowater.environment.data.*
/**
* Main entry point for accessing tasks data.
*/
interface RemoteDataSource {
suspend fun getVersion(): Result<Version>
suspend fun login(auth: Auth): Result<Token>
suspend fun refreshToken(token: Token): Result<Token>
suspend fun getSchedule(): Result<Schedule>
}
| 0
|
Kotlin
|
0
| 0
|
3139da828c309cee13c0eaf3b8ce9a24ce151c5c
| 994
|
Environment3
|
Apache License 2.0
|
core/droidkaigiui/src/iosMain/kotlin/io/github/droidkaigi/confsched/droidkaigiui/IosComposeAdapter.kt
|
DroidKaigi
| 776,354,672
| false
|
{"Kotlin": 1119401, "Swift": 211686, "Shell": 2954, "Makefile": 1314, "Ruby": 386}
|
package io.github.droidkaigi.confsched.droidkaigiui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.interop.LocalUIViewController
import androidx.compose.ui.window.ComposeUIViewController
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import app.cash.molecule.RecompositionMode
import app.cash.molecule.moleculeFlow
import co.touchlab.kermit.Logger
import io.github.droidkaigi.confsched.compose.compositionLocalProviderWithReturnValue
import io.github.droidkaigi.confsched.data.Repositories
import io.github.droidkaigi.confsched.designsystem.theme.KaigiTheme
import io.github.droidkaigi.confsched.model.compositionlocal.LocalRepositories
import kotlinx.coroutines.flow.Flow
import platform.UIKit.UIViewController
import kotlin.reflect.KClass
@Suppress("unused")
fun <EVENT, UISTATE> presenterStateFlow(
repositories: Map<KClass<*>, Any>,
events: Flow<EVENT>,
presenter: @Composable (events: Flow<EVENT>) -> UISTATE,
): Flow<UISTATE> {
return moleculeFlow(RecompositionMode.Immediate) {
val nestedRegistry = remember {
object : ViewModelStoreOwner {
override val viewModelStore: ViewModelStore = ViewModelStore()
}
}
val lifecycleRegistry = remember {
object : LifecycleOwner {
override val lifecycle: Lifecycle = LifecycleRegistry(this)
}
}
compositionLocalProviderWithReturnValue(LocalViewModelStoreOwner provides nestedRegistry) {
compositionLocalProviderWithReturnValue(LocalLifecycleOwner provides lifecycleRegistry) {
compositionLocalProviderWithReturnValue(LocalRepositories provides repositories) {
presenter(events)
}
}
}
}
}
@Suppress("UNUSED")
fun composeViewController(
repositories: Repositories,
content: @Composable () -> Unit,
): UIViewController = ComposeUIViewController {
NavHost(rememberNavController(), startDestination = "root") {
composable("root") {
CompositionLocalProvider(
LocalRepositories provides repositories.map,
) {
Logger.d { "contributorViewController" }
val uiViewController = LocalUIViewController.current
LaunchedEffect(uiViewController) {
// uiViewController
// TODO: How to know the destroy event of the ViewController?
// viewModel.viewModelScope.cancel()
}
KaigiTheme {
content()
}
}
}
}
}
| 49
|
Kotlin
|
201
| 438
|
57c38a76beb5b75edc9220833162e1257f40ac06
| 3,190
|
conference-app-2024
|
Apache License 2.0
|
lib-test/src/main/java/io/sellmair/kompass/app/MainActivity.kt
|
nairobi222
| 181,482,076
| false
| null |
package io.sellmair.kompass.app
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import io.sellmair.kompass.extension.sail
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onStart() {
super.onStart()
Holder.main.setSail(sail(R.id.container)).releasedBy(this)
}
override fun onBackPressed() {
if (!Holder.kompass.backImmediate()) {
finish()
}
}
}
| 1
| null |
1
| 1
|
855e3905f5367a41c00c7a45e5eaf35905c8f893
| 595
|
kompass
|
Apache License 2.0
|
app/src/main/java/com/dolearnn/cg/ui/primitives/Point.kt
|
Jaseemakhtar
| 487,589,439
| false
|
{"Kotlin": 74987}
|
package com.dolearnn.cg.ui.primitives
import androidx.compose.ui.geometry.Offset
data class Point(
val x: Float,
val y: Float,
val z: Float = 0f
) {
fun toOffset() = Offset(x, y)
fun toMatrix() = listOf(listOf(x), listOf(y), listOf(z))
fun scaleToOffset(factor: Float) = Offset(x * factor, y * factor)
fun scaleToPoint(factor: Float) = Point(x * factor, y * factor)
// fun offset(dx: Float, dy: Float) {
// x += dx
// y += dy
// }
}
| 0
|
Kotlin
|
8
| 164
|
d3dc8c47a714132851cd7d619991bbb7703f5176
| 490
|
ComposeCG
|
MIT License
|
app/src/main/java/com/mindorks/framework/mvvm/ui/about/AboutFragment.kt
|
halimbimantara
| 510,920,973
| false
|
{"Kotlin": 361926, "Java": 109358}
|
/*
* Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED
*
* 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://mindorks.com/license/apache-v2
*
* 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.mindorks.framework.mvvm.ui.about
import android.os.Bundle
import com.mindorks.framework.mvvm.BR
import com.mindorks.framework.mvvm.R
import com.mindorks.framework.mvvm.databinding.FragmentAboutBinding
import com.mindorks.framework.mvvm.di.component.FragmentComponent
import com.mindorks.framework.mvvm.ui.base.BaseFragment
/**
* Created by amitshekhar on 09/07/17.
*/
class AboutFragment : BaseFragment<FragmentAboutBinding, AboutViewModel>(), AboutNavigator {
override fun goBack() {
baseActivity?.onFragmentDetached(TAG)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mViewModel?.navigator = this
}
override fun performDependencyInjection(buildComponent: FragmentComponent) {
buildComponent.inject(this)
}
companion object {
const val TAG = "AboutFragment"
fun newInstance(): AboutFragment {
val args = Bundle()
val fragment = AboutFragment()
fragment.arguments = args
return fragment
}
}
override fun getBindingVariable(): Int {
return BR.viewModel
}
override fun getLayoutId(): Int {
return R.layout.fragment_about
}
}
| 0
|
Kotlin
|
0
| 0
|
6e0d1073428e064a5abf4aaebedc44fea5abe847
| 1,877
|
blitar-membina
|
MIT License
|
app/src/main/java/com/mindorks/framework/mvvm/ui/about/AboutFragment.kt
|
halimbimantara
| 510,920,973
| false
|
{"Kotlin": 361926, "Java": 109358}
|
/*
* Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED
*
* 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://mindorks.com/license/apache-v2
*
* 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.mindorks.framework.mvvm.ui.about
import android.os.Bundle
import com.mindorks.framework.mvvm.BR
import com.mindorks.framework.mvvm.R
import com.mindorks.framework.mvvm.databinding.FragmentAboutBinding
import com.mindorks.framework.mvvm.di.component.FragmentComponent
import com.mindorks.framework.mvvm.ui.base.BaseFragment
/**
* Created by amitshekhar on 09/07/17.
*/
class AboutFragment : BaseFragment<FragmentAboutBinding, AboutViewModel>(), AboutNavigator {
override fun goBack() {
baseActivity?.onFragmentDetached(TAG)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mViewModel?.navigator = this
}
override fun performDependencyInjection(buildComponent: FragmentComponent) {
buildComponent.inject(this)
}
companion object {
const val TAG = "AboutFragment"
fun newInstance(): AboutFragment {
val args = Bundle()
val fragment = AboutFragment()
fragment.arguments = args
return fragment
}
}
override fun getBindingVariable(): Int {
return BR.viewModel
}
override fun getLayoutId(): Int {
return R.layout.fragment_about
}
}
| 0
|
Kotlin
|
0
| 0
|
6e0d1073428e064a5abf4aaebedc44fea5abe847
| 1,877
|
blitar-membina
|
MIT License
|
app/src/main/java/com/example/localplayer/MainActivity.kt
|
yana9i
| 343,807,929
| false
|
{"Kotlin": 36793}
|
package com.example.localplayer
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.ImageDecoder
import android.os.*
import android.provider.MediaStore
import android.util.Size
import android.view.Menu
import android.view.MenuItem
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.annotation.RequiresApi
import androidx.core.view.GravityCompat
import com.example.localplayer.activities.AlbumActivity
import com.example.localplayer.utils.MusicItem
import com.example.localplayer.utils.MusicItemAdapter
import com.example.localplayer.services.MusicService
import com.example.localplayer.activities.AllMusicActivity
import com.example.localplayer.activities.PlaylistActivity
import com.example.localplayer.activities.SettingsActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
private var musicList = mutableListOf<MusicItem>()
private lateinit var musicServiceBinder: MusicService.MusicServiceBinder
private val stateChangeListener = object :
MusicService.OnStateChangeListener {
override fun onPause(musicItem: MusicItem) {
play_btn.setBackgroundResource(R.drawable.ic_baseline_play_arrow_24)
}
override fun onPlay(musicItem: MusicItem) {
play_btn.setBackgroundResource(R.drawable.ic_baseline_pause_24)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun onPlayProgressChange(musicItem: MusicItem, currentPosition: Int) {
updatePlayingInfo(musicItem,currentPosition)
}
}
private val serviceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName?) {
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
musicServiceBinder = service as MusicService.MusicServiceBinder
musicList = musicServiceBinder.getPlayList()
musicServiceBinder.registerOnChangeListener(stateChangeListener)
}
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
supportActionBar?.let {
it.setDisplayHomeAsUpEnabled(true)
it.setHomeAsUpIndicator(R.drawable.ic_baseline_menu_24)
}
nav_view.setNavigationItemSelectedListener {
drawer_layout.closeDrawers()
when(it.itemId){
R.id.nav_to_allMusic ->{
val intent = Intent(this,
AllMusicActivity::class.java)
startActivity(intent)
}
R.id.nav_to_playlist ->{
val intent = Intent(this,PlaylistActivity::class.java)
startActivity(intent)
}
R.id.nav_to_settings ->{
val intent = Intent(this,SettingsActivity::class.java)
startActivity(intent)
}
R.id.nav_to_albumList ->{
val intent = Intent(this,AlbumActivity::class.java)
startActivity(intent)
}
}
true
}
val intent = Intent(this, MusicService::class.java)
startService(intent)
bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE)
play_btn.setOnClickListener{
if (musicServiceBinder.isPlaying()){
musicServiceBinder.pause()
} else{
musicServiceBinder.play()
}
}
next_btn.setOnClickListener{
musicServiceBinder.playNext()
}
pre_btn.setOnClickListener{
musicServiceBinder.playPre()
}
seek_music.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
seekBar?.let { musicServiceBinder.seekTo(it.progress) }
}
})
}
override fun onResume() {
super.onResume()
nav_view.setCheckedItem(R.id.nav_to_nowPlaying)
}
override fun onDestroy() {
super.onDestroy()
unbindService(serviceConnection)
musicServiceBinder.unregisterOnStateChangeListener(stateChangeListener)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.toolbar_menu,menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
android.R.id.home -> drawer_layout.openDrawer(GravityCompat.START)
}
return true
}
@SuppressLint("SimpleDateFormat")
@RequiresApi(Build.VERSION_CODES.Q)
private fun updatePlayingInfo(musicItem: MusicItem, currentPosition:Int){
val durationTime = musicItem.duration
val mSDF = SimpleDateFormat("mm:ss")
val durationDate = Date(durationTime)
duration_time.text = mSDF.format(durationDate)
val currentPositionDate = Date(currentPosition.toLong())
current_position.text = mSDF.format(currentPositionDate)
if(musicServiceBinder.isPlaying())
play_btn.setBackgroundResource(R.drawable.ic_baseline_pause_24)
else
play_btn.setBackgroundResource(R.drawable.ic_baseline_play_arrow_24)
seek_music.max = musicItem.duration.toInt()
seek_music.progress = currentPosition
now_playing_music_title.text = musicItem.title
try {
now_playing_album.setImageBitmap(contentResolver.loadThumbnail(musicItem.albumUri, Size(800,800),null))
} catch (e:Exception) {
e.printStackTrace()
now_playing_album.setImageBitmap(musicItem.albumThumb)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d63877dfb5547c71f537ee5b90d56f67680c68e8
| 6,314
|
LocalMusicPlayer
|
MIT License
|
androidApp/src/test/java/com/mehmedmert/minesweeperkmmshowcase/android/game/GameViewStatusMapperTest.kt
|
mmert1988
| 718,163,465
| false
|
{"Kotlin": 34593, "Swift": 342}
|
package com.mehmedmert.minesweeperkmmshowcase.android.game
import com.mehmedmert.minesweeperkmmshowcase.domain.model.GameStatus
import kotlinx.datetime.Instant
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class GameViewStatusMapperTest {
@Test
fun `test map running game`() {
val tested = GameViewStatusMapper()
val result = tested.map(
GameStatus.Running(
rows = 3,
columns = 3,
openedCells = mapOf(
Pair(0, 0) to 1
),
flags = setOf(Pair(1, 1)),
startTime = Instant.DISTANT_PAST,
remainingMines = 1
)
)
assertEquals(3, result.rows)
assertEquals(3, result.columns)
assertEquals(
listOf(
Cell.Open(1),
Cell.Closed,
Cell.Closed,
Cell.Closed,
Cell.Flagged,
Cell.Closed,
Cell.Closed,
Cell.Closed,
Cell.Closed
),
result.cells
)
assertEquals(Status.Running, result.status)
assertEquals(1, result.remainingMines)
}
@Test
fun `test map lost game`() {
val tested = GameViewStatusMapper()
val result = tested.map(
GameStatus.Lost(
rows = 3,
columns = 3,
openedCells = mapOf(
Pair(0, 0) to 1
),
flags = setOf(Pair(1, 1)),
mines = setOf(Pair(1, 1), Pair(2, 2))
)
)
assertEquals(3, result.rows)
assertEquals(3, result.columns)
assertEquals(
listOf(
Cell.Open(1),
Cell.Closed,
Cell.Closed,
Cell.Closed,
Cell.Flagged,
Cell.Closed,
Cell.Closed,
Cell.Closed,
Cell.Mined
),
result.cells
)
assertEquals(Status.Lost, result.status)
assertNull(result.remainingMines)
}
@Test
fun `test map won game`() {
val tested = GameViewStatusMapper()
val result = tested.map(
GameStatus.Won(
rows = 3,
columns = 3,
openedCells = mapOf(
Pair(0, 0) to 1
),
flags = setOf(Pair(1, 1)),
)
)
assertEquals(3, result.rows)
assertEquals(3, result.columns)
assertEquals(
listOf(
Cell.Open(1),
Cell.Closed,
Cell.Closed,
Cell.Closed,
Cell.Flagged,
Cell.Closed,
Cell.Closed,
Cell.Closed,
Cell.Closed
),
result.cells
)
assertEquals(Status.Won, result.status)
assertNull(result.remainingMines)
}
}
| 0
|
Kotlin
|
0
| 0
|
f5e8d20a869cccad966aba6d1e7c581125373626
| 3,111
|
minesweeper-kmm-showcase
|
Apache License 2.0
|
shared/src/commonMain/kotlin/domain/usecases/debts/GetAllDebtsUseCase.kt
|
SergStas
| 697,631,567
| false
|
{"Kotlin": 55889, "Swift": 592, "Shell": 228}
|
package domain.usecases.debts
import di.AppDiAware
import domain.models.Currency
import domain.models.User
import domain.repo.IDebtRepo
import org.kodein.di.instance
class GetAllDebtsUseCase: AppDiAware {
private val debtRepo by instance<IDebtRepo>()
suspend operator fun invoke(owner: User, args: FilterArgs? = null) =
debtRepo.getAll(owner, args)
data class FilterArgs(
val users: List<User>? = null,
val types: List<DebtTag>? = null,
val currencies: List<Currency>? = null,
) {
enum class DebtTag {
Active, Accepted, ToPay, ToReceive, PendingConfirm, Declined;
}
}
}
| 0
|
Kotlin
|
0
| 0
|
955b263d2669fdfda8b57b8a584c99dc6a905c40
| 653
|
DebtsTrackerCompose
|
Apache License 2.0
|
app/src/main/java/com/babylon/wallet/android/presentation/settings/linkedconnectors/relink/RelinkConnectorsScreen.kt
|
radixdlt
| 513,047,280
| false
| null |
package com.babylon.wallet.android.presentation.settings.linkedconnectors.relink
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import androidx.hilt.navigation.compose.hiltViewModel
import com.babylon.wallet.android.R
import com.babylon.wallet.android.designsystem.theme.RadixTheme
import com.babylon.wallet.android.designsystem.theme.RadixWalletTheme
import com.babylon.wallet.android.presentation.ui.composables.BackIconType
import com.babylon.wallet.android.presentation.ui.composables.RadixCenteredTopAppBar
import com.babylon.wallet.android.presentation.ui.composables.linkedconnector.LinkedConnectorMessageScreen
@Composable
fun RelinkConnectorsScreen(
onContinueClick: () -> Unit,
onDismiss: () -> Unit,
viewModel: RelinkConnectorsViewModel = hiltViewModel()
) {
RelinkConnectorsContent(
state = viewModel.state.collectAsState().value,
onContinueClick = {
viewModel.acknowledgeMessage()
onContinueClick()
},
onDismiss = {
viewModel.acknowledgeMessage()
onDismiss()
}
)
}
@Composable
private fun RelinkConnectorsContent(
state: RelinkConnectorsViewModel.UiState,
onContinueClick: () -> Unit,
onDismiss: () -> Unit
) {
Scaffold(
topBar = {
RadixCenteredTopAppBar(
title = stringResource(id = R.string.empty),
onBackClick = onDismiss,
backIconType = BackIconType.Close,
windowInsets = WindowInsets.statusBars
)
},
containerColor = RadixTheme.colors.defaultBackground,
) { padding ->
Box(
modifier = Modifier.padding(padding)
) {
when (state) {
RelinkConnectorsViewModel.UiState.AppUpdate -> LinkedConnectorMessageScreen(
title = stringResource(id = R.string.linkedConnectors_relinkConnectors_title),
message = stringResource(id = R.string.linkedConnectors_relinkConnectors_afterUpdateMessage),
onPositiveClick = onContinueClick,
onNegativeClick = onDismiss,
negativeButton = stringResource(id = R.string.linkedConnectors_relinkConnectors_laterButton)
)
RelinkConnectorsViewModel.UiState.ProfileRestore -> LinkedConnectorMessageScreen(
title = stringResource(id = R.string.linkedConnectors_relinkConnectors_title),
message = stringResource(id = R.string.linkedConnectors_relinkConnectors_afterProfileRestoreMessage),
onPositiveClick = onContinueClick,
onNegativeClick = onDismiss,
negativeButton = stringResource(id = R.string.linkedConnectors_relinkConnectors_laterButton)
)
RelinkConnectorsViewModel.UiState.Idle -> {}
}
}
}
}
@Composable
@Preview
private fun RelinkConnectorsPreview(
@PreviewParameter(RelinkConnectorsPreviewProvider::class) state: RelinkConnectorsViewModel.UiState
) {
RadixWalletTheme {
RelinkConnectorsContent(
state = state,
onContinueClick = {},
onDismiss = {}
)
}
}
class RelinkConnectorsPreviewProvider : PreviewParameterProvider<RelinkConnectorsViewModel.UiState> {
override val values: Sequence<RelinkConnectorsViewModel.UiState>
get() = sequenceOf(
RelinkConnectorsViewModel.UiState.AppUpdate,
RelinkConnectorsViewModel.UiState.ProfileRestore
)
}
| 6
| null |
6
| 9
|
a973af97556c2c3c5c800dac937d0007a13a3a1c
| 4,129
|
babylon-wallet-android
|
Apache License 2.0
|
identity/data/src/main/java/com/timecat/identity/data/model.kt
|
LinXueyuanStdio
| 324,718,951
| false
|
{"Java": 208407, "Kotlin": 165348}
|
package com.timecat.identity.data
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.timecat.identity.data.block.Good
import com.timecat.identity.data.block.Reward
import com.timecat.identity.data.block.TaskRule
import com.timecat.identity.data.block.UpdateInfo
/**
* @author 林学渊
* @email linxy59@mail2.sysu.edu.cn
* @date 2019-09-08
* @description null
* @usage null
*/
fun JSONObject.getUpdateInfoList(key: String): MutableList<UpdateInfo> {
return getJSONArray(key)?.toUpdateInfoList() ?: mutableListOf()
}
fun JSONObject.getStringList(key: String): MutableList<String> {
return getJSONArray(key)?.toListString() ?: mutableListOf()
}
fun JSONObject.getGoodList(key: String): MutableList<Good> {
return getJSONArray(key)?.toGoodList() ?: mutableListOf()
}
fun JSONObject.getTaskRuleList(key: String): MutableList<TaskRule> {
return getJSONArray(key)?.toTaskRuleList() ?: mutableListOf()
}
fun JSONObject.getRewardList(key: String): MutableList<Reward> {
return getJSONArray(key)?.toRewardList() ?: mutableListOf()
}
fun JSONArray.toUpdateInfoList(): MutableList<UpdateInfo> {
val list: MutableList<UpdateInfo> = mutableListOf()
for (i in this) {
list.add(UpdateInfo.fromJson(i as JSONObject))
}
return list
}
fun JSONArray.toListString(): MutableList<String> {
val list: MutableList<String> = mutableListOf()
for (i in this) {
list.add((i as JSONObject).toString())
}
return list
}
fun JSONArray.toGoodList(): MutableList<Good> {
val list: MutableList<Good> = mutableListOf()
for (i in this) {
list.add(Good.fromJson(i as JSONObject))
}
return list
}
fun JSONArray.toTaskRuleList(): MutableList<TaskRule> {
val list: MutableList<TaskRule> = mutableListOf()
for (i in this) {
list.add(TaskRule.fromJson(i as JSONObject))
}
return list
}
fun JSONArray.toRewardList(): MutableList<Reward> {
val list: MutableList<Reward> = mutableListOf()
for (i in this) {
list.add(Reward.fromJson(i as JSONObject))
}
return list
}
| 1
| null |
1
| 1
|
3258d40c4b2cba45a5e380556bf460f7fd52f823
| 2,103
|
TimeCatIdentity
|
Apache License 2.0
|
falling-evaders-chaos/core/src/gparap/games/falling/screens/Screen.kt
|
gparap
| 388,079,965
| false
|
{"Text": 1, "Ignore List": 10, "Markdown": 6, "Gradle": 34, "INI": 12, "Shell": 7, "Batchfile": 7, "Java": 98, "Kotlin": 41, "Proguard": 7, "XML": 67, "Java Properties": 8, "CMake": 1, "JSON": 1, "C++": 27, "C": 1, "OpenStep Property List": 4, "Makefile": 1, "HTML": 1, "CSS": 1}
|
/*******************************
* Katocheánian Gaming Studios *
* Falling Evaders Chaos *
* created by gparap *
*******************************/
package gparap.games.falling.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Preferences
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter
import com.badlogic.gdx.utils.ScreenUtils
import com.badlogic.gdx.utils.viewport.ScreenViewport
import gparap.games.falling.utils.GameConstants
/**
* Base class for all screens of the game.
*/
open class Screen(protected val spriteBatch: SpriteBatch) : Screen {
private lateinit var background: Texture
private lateinit var camera: OrthographicCamera
protected lateinit var viewport: ScreenViewport
protected lateinit var font: BitmapFont
protected lateinit var preferences: Preferences
override fun show() {
//set up how the game world coordinates are mapped to and from the screen
camera = OrthographicCamera(Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat())
camera.setToOrtho(false)
viewport = ScreenViewport(camera)
//create background
background = Texture(GameConstants.BACKGROUND)
//get the preferences of this game
preferences = Gdx.app.getPreferences(GameConstants.PREFERENCES)
}
override fun render(delta: Float) {
//clear the screen before drawing
ScreenUtils.clear(0F, 0F, 0F, 1F)
//draw background
spriteBatch.projectionMatrix = camera.combined
spriteBatch.begin()
spriteBatch.draw(background, 0F, 0F, viewport.screenWidth.toFloat(), viewport.screenHeight.toFloat())
spriteBatch.end()
}
override fun resize(width: Int, height: Int) {
viewport.update(width, height, true)
}
override fun pause() {}
override fun resume() {}
override fun hide() {}
override fun dispose() {
background.dispose()
}
/** Creates the default font that will be used throughout the screens */
protected open fun createFont(fontSize: Int = GameConstants.DEFAULT_FONT_SIZE) {
font = BitmapFont(Gdx.files.internal(GameConstants.DEFAULT_FONT))
val generator = FreeTypeFontGenerator(Gdx.files.internal(GameConstants.OPEN_TYPE_FONT))
val parameter = FreeTypeFontParameter()
parameter.size = fontSize
font = generator.generateFont(parameter)
generator.dispose()
}
}
| 0
|
Java
|
0
| 4
|
0d8fe879a7ed4440ab97f68711d278715f9830b0
| 2,775
|
kgs
|
Apache License 2.0
|
sample/src/main/java/dev/gerlot/securewebview/sample/demos/FileAccessFragment.kt
|
balazsgerlei
| 786,827,564
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 19, "XML": 38, "HTML": 2, "INI": 1, "Java": 4}
|
package dev.gerlot.securewebview.sample.demos
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import dev.gerlot.securewebview.sample.R
import dev.gerlot.securewebview.sample.SecurableWebViewFragment
import dev.gerlot.securewebview.sample.WebViewSecureState
import dev.gerlot.securewebview.sample.databinding.FileAccessFragmentBinding
import dev.gerlot.securewebview.sample.util.hideKeyboard
import dev.gerlot.securewebview.sample.util.makeClearableEditText
import dev.gerlot.securewebview.sample.util.setOnDoneActionListener
class FileAccessFragment : Fragment(), SecurableWebViewFragment {
private var _binding: FileAccessFragmentBinding? = null
private val binding get() = _binding!!
private var webViewSecureState = WebViewSecureState.INSECURE
private var currentUrl: String? = null
private val requestPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
loadUrl(INITIAL_URI)
} else {
// Explain to the user that the feature is unavailable because the
// feature requires a permission that the user has denied.
// Won't implement this for a sample app
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
view ?: return
if (webViewSecureState == WebViewSecureState.INSECURE) {
binding.insecureWebView.goBack()
} else {
binding.secureWebView.goBack()
}
}
})
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FileAccessFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// For demonstrative purposes we explicitly enable file access on versions
// where it is disabled by default, otherwise (on Android 9 and below)
// we rely on the default false value
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
binding.insecureWebView.settings.allowFileAccess = true
}
binding.insecureWebView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
return false
}
override fun onPageFinished(view: WebView?, url: String?) {
currentUrl = url
view ?: return
_binding ?: return
binding.urlInput.setText(url)
super.onPageFinished(view, url)
}
}
binding.secureWebView.setWebViewClient(object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
currentUrl = url
view ?: return
_binding ?: return
binding.urlInput.setText(url)
super.onPageFinished(view, url)
}
})
binding.urlInput.setImeActionLabel(resources.getString(R.string.load_url), KeyEvent.KEYCODE_ENTER)
binding.urlInput.setOnDoneActionListener {
loadUrl(binding.urlInput.text.toString())
binding.urlInput.clearFocus()
false
}
binding.urlInput.makeClearableEditText()
if (webViewSecureState == WebViewSecureState.INSECURE) {
binding.viewFlipper.displayedChild = 0
} else {
binding.viewFlipper.displayedChild = 1
}
if (savedInstanceState == null) {
val permissionToUse = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) Manifest.permission.READ_MEDIA_IMAGES else Manifest.permission.READ_EXTERNAL_STORAGE
if (ContextCompat.checkSelfPermission(requireContext(), permissionToUse) == PackageManager.PERMISSION_GRANTED) {
loadUrl(INITIAL_URI)
} else if (shouldShowRequestPermissionRationale(permissionToUse)) {
// In an educational UI, explain to the user why your app requires this
// permission for a specific feature to behave as expected, and what
// features are disabled if it's declined.
// Won't implement this for a sample app
} else {
requestPermissionLauncher.launch(permissionToUse)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
activity?.hideKeyboard()
_binding = null
}
private fun loadUrl(url: String) {
currentUrl = url
if (url != binding.urlInput.text.toString()) {
binding.urlInput.setText(url)
}
if (webViewSecureState == WebViewSecureState.INSECURE) {
binding.insecureWebView.loadUrl(url)
} else {
binding.secureWebView.loadUrl(url)
}
}
override fun secureWebView() {
webViewSecureState = WebViewSecureState.SECURE
if (view != null) {
binding.viewFlipper.displayedChild = 1
currentUrl?.let {
loadUrl(it)
}
}
}
override fun unSecureWebView() {
webViewSecureState = WebViewSecureState.INSECURE
if (view != null) {
binding.viewFlipper.displayedChild = 0
currentUrl?.let {
loadUrl(it)
}
}
}
companion object {
private const val INITIAL_URI = "file:///storage/emulated/0/Download/android_robot.png"
val TAG: String = FileAccessFragment::class.java.canonicalName ?: FileAccessFragment::class.java.name
fun newInstance() = FileAccessFragment()
}
}
| 1
|
Java
|
2
| 3
|
bf29f205b0e3c509bf7e402686d34220a02273a2
| 6,693
|
SecureWebView
|
Creative Commons Zero v1.0 Universal
|
urbanairship-debug/src/main/java/com/urbanairship/debug/event/persistence/EventDao.kt
|
tmckeown-rsc
| 193,259,287
| false
|
{"INI": 1, "Markdown": 12, "Shell": 3, "Batchfile": 1, "Proguard": 6, "Java": 621, "Kotlin": 49, "Python": 1, "Java Properties": 3, "C#": 2, "CSS": 1}
|
/* Copyright Airship and Contributors */
package com.urbanairship.debug.event.persistence
import android.arch.lifecycle.LiveData
import android.arch.paging.DataSource
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Insert
import android.arch.persistence.room.Query
import android.support.annotation.RestrictTo
/**
* Data Access Object for the event table.
* @hide
*/
@Dao
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
interface EventDao {
@Insert
fun insertEvent(event: EventEntity)
@Query("SELECT * FROM events ORDER BY id DESC")
fun getEvents(): DataSource.Factory<Int, EventEntity>
@Query("SELECT * FROM events WHERE type IN(:types) ORDER BY id DESC")
fun getEvents(types: List<String>): DataSource.Factory<Int, EventEntity>
@Query("select * from events where eventId = :eventId")
fun getEvent(eventId: String): LiveData<EventEntity?>
@Query("DELETE FROM events where eventId NOT IN (SELECT eventId from events ORDER BY time LIMIT :count)")
fun trimEvents(count: Long)
}
| 1
| null |
1
| 1
|
5f672d6669f2191c73f5dde5071e1a7bab09579c
| 1,053
|
android-library
|
Apache License 2.0
|
app/src/main/java/caatsoft/studio/com/gamecatalog/viewmodel/GamesViewModel.kt
|
Lhmsouza
| 375,726,918
| true
|
{"Kotlin": 44697}
|
package caatsoft.studio.com.gamecatalog.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import caatsoft.studio.com.gamecatalog.network.model.Game
import caatsoft.studio.com.gamecatalog.repository.Repository
import kotlinx.coroutines.launch
class GamesViewModel (private val repository: Repository) : ViewModel() {
private val gameListLiveData = MutableLiveData<List<Game>>()
val games = gameListLiveData as LiveData<List<Game>>
fun getFilteredGames() {
viewModelScope.launch {
val filteredGamesResponse = repository.getFilteredGames(FORMAT, FIELD_LIST)
if (filteredGamesResponse.isSuccessful){
filteredGamesResponse.body()?.let { gameResponse ->
gameListLiveData.value = gameResponse.results
}
}
}
}
companion object {
private const val FORMAT = "json"
private const val FIELD_LIST = "name,deck,platforms,original_release_date,image"
}
}
| 0
| null |
0
| 0
|
d05f29dc53724e279b0f2b7ac911b26cd13cd0c1
| 1,032
|
Projeto_final_Game_Catalog
|
MIT License
|
tangem-sdk-core/src/main/java/com/tangem/crypto/IssuerDataVerifier.kt
|
tangem
| 218,994,149
| false
| null |
package com.tangem.crypto
import com.squareup.moshi.JsonClass
import com.tangem.common.tlv.TlvEncoder
import com.tangem.common.tlv.TlvTag
import java.io.ByteArrayOutputStream
interface IssuerDataVerifier {
fun verify(issuerPublicKey: ByteArray, signature: ByteArray, issuerDataToVerify: IssuerDataToVerify): Boolean
}
@JsonClass(generateAdapter = true)
class IssuerDataToVerify(
val cardId: String,
val issuerData: ByteArray?,
val issuerDataCounter: Int? = null,
val issuerExtraDataSize: Int? = null
)
class DefaultIssuerDataVerifier : IssuerDataVerifier {
override fun verify(
issuerPublicKey: ByteArray,
signature: ByteArray,
issuerDataToVerify: IssuerDataToVerify
): Boolean {
val tlvEncoder = TlvEncoder()
val dataToVerify = ByteArrayOutputStream()
dataToVerify.write(tlvEncoder.encodeValue(TlvTag.CardId, issuerDataToVerify.cardId))
issuerDataToVerify.issuerData?.let { dataToVerify.write(it) }
issuerDataToVerify.issuerDataCounter?.let { counter ->
dataToVerify.write(tlvEncoder.encodeValue(TlvTag.IssuerDataCounter, counter))
}
issuerDataToVerify.issuerExtraDataSize?.let {
dataToVerify.write(tlvEncoder.encodeValue(TlvTag.Size, it))
}
return CryptoUtils.verify(issuerPublicKey, dataToVerify.toByteArray(), signature)
}
}
| 4
| null |
38
| 64
|
2ea3795fd521f23ecc6414913ab5d207c256fe84
| 1,385
|
tangem-sdk-android
|
MIT License
|
src/main/kotlin/com/melowetty/hsepermhelper/repository/DataRepository.kt
|
HSE-Perm-Helper
| 682,010,195
| false
|
{"Kotlin": 129695, "Dockerfile": 462}
|
package com.melowetty.hsepermhelper.repository
import com.melowetty.hsepermhelper.entity.DataEntity
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
@Repository
interface DataRepository: CrudRepository<DataEntity, String>
| 3
|
Kotlin
|
0
| 0
|
a75bcea3cb08e96d902e1e60a4b2f78793554afb
| 281
|
main-backend
|
MIT License
|
app/src/main/java/com/programmersbox/otakuworld/PlaygroundApp.kt
|
jakepurple13
| 353,155,453
| false
| null |
package com.programmersbox.otakuworld
import android.app.Application
import com.google.android.material.color.DynamicColors
class PlaygroundApp : Application() {
override fun onCreate() {
super.onCreate()
//TODO: This acts funky if user enabled force dark mode from developer options
DynamicColors.applyToActivitiesIfAvailable(this)
}
}
| 1
|
Kotlin
|
5
| 83
|
6c24eb3f85c9ebc1795a1eb04f916104031d672a
| 370
|
OtakuWorld
|
Apache License 2.0
|
app/src/androidTest/java/com/fer1592/k8s_android_console/view/SetClusterTest.kt
|
fer1592
| 474,361,761
| false
|
{"HTML": 583069, "Kotlin": 69474}
|
package com.fer1592.k8s_android_console.view
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.replaceText
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.hasDescendant
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.fer1592.k8s_android_console.R
import com.fer1592.k8s_android_console.data.repository_implementation.ClusterRepositoryImplementation
import com.fer1592.k8s_android_console.view.activities.MainActivity
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.hamcrest.CoreMatchers.instanceOf
import org.hamcrest.Matchers.allOf
import org.hamcrest.Matchers.`is`
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
@RunWith(AndroidJUnit4::class)
class SetClusterTest {
@get:Rule
val activityRule = ActivityScenarioRule(MainActivity::class.java)
private lateinit var context: Context
private lateinit var clusterAddress: String
private lateinit var clusterPort: String
private lateinit var clusterBearerToken: String
@Before
fun setup() {
context = ApplicationProvider.getApplicationContext()
clusterAddress = System.getProperty("address")?.toString() ?: "192.168.100.114"
clusterPort = System.getProperty("port")?.toString() ?: "16443"
clusterBearerToken = System.getProperty("token")?.toString() ?: "<KEY>"
}
@After
@ExperimentalCoroutinesApi
@Throws(IOException::class)
fun clearDatabase() = runTest {
val clusterRepository = ClusterRepositoryImplementation()
clusterRepository.cleanUpClusters()
}
@Test
fun addNewClusterWithIp() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("16443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("testToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withId(R.id.clusters_list)).check(matches(atPosition(0, hasDescendant(withText("Test Cluster")))))
}
@Test
fun addNewClusterWithUrl() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("test.cluster.com"))
onView(withId(R.id.cluster_port)).perform(replaceText("16443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("testToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withId(R.id.clusters_list)).check(matches(atPosition(0, hasDescendant(withText("Test Cluster")))))
}
@Test
fun addNewClusterDisplayEmptyNameError() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText(""))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("16443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("TestToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_name_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_empty_cluster_name)))))
}
@Test
fun addNewClusterDisplayWrongAddressError() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("16443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("TestToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_address_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_invalid_cluster_address)))))
onView(withId(R.id.cluster_address)).perform(replaceText("https://invalid.address"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_address_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_invalid_cluster_address)))))
onView(withId(R.id.cluster_address)).perform(replaceText(""))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_address_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_invalid_cluster_address)))))
}
@Test
fun addNewClusterDisplayWrongPortError() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("0"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("TestToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_port_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_invalid_port_address)))))
onView(withId(R.id.cluster_port)).perform(replaceText(""))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_port_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_invalid_port_address)))))
}
@Test
fun addNewClusterDisplayEmptyBearerError() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("8443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText(""))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_bearer_token_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_empty_cluster_bearer_token)))))
}
@Test
fun updateCluster() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("16443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("testToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withText(context.getString(R.string.edit))).perform(click())
onView(withId(R.id.cluster_name)).perform(replaceText("Test Cluster2"))
onView(withId(R.id.cluster_address)).perform(replaceText("192.168.1.2"))
onView(withId(R.id.cluster_port)).perform(replaceText("8443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(replaceText("testToken2"))
onView(withId(R.id.update_cluster)).perform(scrollTo(), click())
onView(withId(R.id.clusters_list)).check(matches(atPosition(0, hasDescendant(withText("Test Cluster2")))))
onView(withText(context.getString(R.string.edit))).perform(click())
onView(withId(R.id.cluster_address)).perform(replaceText("test.cluster.com"))
onView(withId(R.id.update_cluster)).perform(scrollTo(), click())
onView(withId(R.id.clusters_list)).check(matches(atPosition(0, hasDescendant(withText("Test Cluster2")))))
}
@Test
fun updateClusterDisplayEmptyNameError() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("16443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("TestToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withText(context.getString(R.string.edit))).perform(click())
onView(withId(R.id.cluster_name)).perform(replaceText(""))
onView(withId(R.id.update_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_name_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_empty_cluster_name)))))
}
@Test
fun updateClusterDisplayWrongAddressError() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("16443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("TestToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withText(context.getString(R.string.edit))).perform(click())
onView(withId(R.id.cluster_address)).perform(replaceText(""))
onView(withId(R.id.update_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_address_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_invalid_cluster_address)))))
onView(withId(R.id.cluster_address)).perform(replaceText("192.168.1"))
onView(withId(R.id.update_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_address_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_invalid_cluster_address)))))
onView(withId(R.id.cluster_address)).perform(replaceText("https://test.cluster.com"))
onView(withId(R.id.update_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_address_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_invalid_cluster_address)))))
}
@Test
fun updateClusterDisplayWrongPortError() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("16443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("TestToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withText(context.getString(R.string.edit))).perform(click())
onView(withId(R.id.cluster_port)).perform(replaceText("0"))
onView(withId(R.id.update_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_port_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_invalid_port_address)))))
onView(withId(R.id.cluster_port)).perform(replaceText(""))
onView(withId(R.id.update_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_port_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_invalid_port_address)))))
}
@Test
fun updateClusterDisplayEmptyBearerError() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("8443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("TestToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withText(context.getString(R.string.edit))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(replaceText(""))
onView(withId(R.id.update_cluster)).perform(scrollTo(), click())
onView(withId(R.id.cluster_bearer_token_input_layout)).check(matches(hasDescendant(withText(context.getString(R.string.validation_empty_cluster_bearer_token)))))
}
@Test
fun deleteCluster() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText("192.168.1.1"))
onView(withId(R.id.cluster_port)).perform(replaceText("8443"))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText("TestToken"))
onView(withId(R.id.add_cluster)).perform(scrollTo(), click())
onView(withText(context.getString(R.string.delete))).perform(click())
onView(withText(context.getString(R.string.accept))).perform(click())
onView(withText("Test Cluster")).check(doesNotExist())
}
@Test
fun testConnectionShowToast() {
onView(withId(R.id.add_cluster)).perform(click())
onView(withId(R.id.cluster_name)).perform(typeText("Test Cluster"))
onView(withId(R.id.cluster_address)).perform(typeText(clusterAddress))
onView(withId(R.id.cluster_port)).perform(replaceText(clusterPort))
onView(withId(R.id.cluster_authentication_method)).perform(click())
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Bearer Token"))).perform(click())
onView(withId(R.id.cluster_bearer_token)).perform(typeText(clusterBearerToken))
onView(withId(R.id.test_connection)).perform(scrollTo(), click())
onView(allOf(withText(R.string.connection_succeeded))).inRoot(ToastMatcher()).check(matches(isDisplayed()))
}
}
| 1
|
HTML
|
0
| 0
|
49c43ef65cd530d3978b2d2397b4024d3e269592
| 16,767
|
k8s-android-console
|
MIT License
|
ui-common/src/commonMain/kotlin/com/alexvanyo/composelife/ui/util/DraggableAnchors.kt
|
alexvanyo
| 375,146,193
| false
|
{"Kotlin": 1943779}
|
/*
* Copyright 2024 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.alexvanyo.composelife.ui.util
import androidx.compose.foundation.ExperimentalFoundationApi
interface DraggableAnchors<T> {
val size: Int
fun closestAnchor(position: Float): T?
fun closestAnchor(position: Float, searchUpwards: Boolean): T?
fun hasAnchorFor(value: T): Boolean
fun maxAnchor(): Float
fun minAnchor(): Float
fun positionOf(value: T): Float
fun forEach(block: (anchor: T, position: Float) -> Unit) = Unit
}
@ExperimentalFoundationApi
expect fun <T> DraggableAnchors<T>.asFoundationDraggableAnchors(
equalsKey: Any? = null,
): androidx.compose.foundation.gestures.DraggableAnchors<T>
internal interface WithEqualsKey {
val equalsKey: Any?
}
| 36
|
Kotlin
|
10
| 99
|
64595b8d36c559a70ca52d578069fe4df8d170c7
| 1,333
|
composelife
|
Apache License 2.0
|
libraries/api/src/main/kotlin/io/plastique/api/comments/CommentList.kt
|
plastiqueapp
| 150,879,887
| false
| null |
package io.plastique.api.comments
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class CommentList(
@Json(name = "has_more")
val hasMore: Boolean = false,
@Json(name = "next_offset")
val nextOffset: Int? = 0,
@Json(name = "thread")
val comments: List<CommentDto> = emptyList()
)
| 0
|
Kotlin
|
2
| 9
|
9271853f3741add18822858cbad9d4f8e8104f54
| 367
|
plastique
|
Apache License 2.0
|
mobile-ui/src/androidTest/java/com/thomaskioko/paybillmanager/mobile/factory/BillsDataFactory.kt
|
c0de-wizard
| 60,256,636
| false
| null |
package com.thomaskioko.paybillmanager.mobile.factory
import com.thomaskioko.paybillmanager.domain.model.Bill
import com.thomaskioko.paybillmanager.mobile.factory.TestDataFactory.randomInt
import com.thomaskioko.paybillmanager.mobile.factory.TestDataFactory.randomLong
import com.thomaskioko.paybillmanager.mobile.factory.TestDataFactory.randomUuid
import com.thomaskioko.paybillmanager.presentation.model.BillView
object BillsDataFactory {
fun makeStaticBill(): Bill {
return Bill("12", "Zuku", "320320",
"Zuku123443", "4900", "2",
156223772
)
}
fun makeBill(): Bill {
return Bill(randomUuid(), randomUuid(), randomUuid(),
randomUuid(), "2400", randomUuid(),
randomLong())
}
fun makeBillList(count: Int): List<Bill> {
val billEntities = mutableListOf<Bill>()
repeat(count) {
billEntities.add(makeBill())
}
return billEntities
}
fun makeBillView(): BillView {
return BillView("12", "Zuku", "320320",
"Zuku123443", "4900", "2",
156223772)
}
fun makeBillViewList(count: Int): List<BillView> {
val billEntities = mutableListOf<BillView>()
repeat(count) {
billEntities.add(makeBillView())
}
return billEntities
}
}
| 7
|
Kotlin
|
15
| 48
|
e79ca3f073764d78d9a34f640fdfaec78839fe45
| 1,377
|
paybill-manager
|
Apache License 2.0
|
src/main/kotlin/org/komamitsu/konessem/cpu/Opcode.kt
|
komamitsu
| 323,249,618
| false
| null |
package org.komamitsu.konessem.cpu
internal data class Opcode(
val instruction: Instruction,
val addressingMode: AddressingMode,
val cycle: Int
) {
companion object {
private val opcodeMap = mapOf(
0x69 to Opcode(Instruction.ADC, AddressingMode.IMMEDIATE, 2),
0x65 to Opcode(Instruction.ADC, AddressingMode.ZERO_PAGE, 3),
0x75 to Opcode(Instruction.ADC, AddressingMode.ZERO_PAGE_X, 4),
0x6D to Opcode(Instruction.ADC, AddressingMode.ABSOLUTE, 4),
0x7D to Opcode(Instruction.ADC, AddressingMode.ABSOLUTE_X, 4),
0x79 to Opcode(Instruction.ADC, AddressingMode.ABSOLUTE_Y, 4),
0x61 to Opcode(Instruction.ADC, AddressingMode.INDEXED_INDIRECT, 6),
0x71 to Opcode(Instruction.ADC, AddressingMode.INDIRECT_INDEXED, 5),
0x29 to Opcode(Instruction.AND, AddressingMode.IMMEDIATE, 2),
0x25 to Opcode(Instruction.AND, AddressingMode.ZERO_PAGE, 3),
0x35 to Opcode(Instruction.AND, AddressingMode.ZERO_PAGE_X, 4),
0x2D to Opcode(Instruction.AND, AddressingMode.ABSOLUTE, 4),
0x3D to Opcode(Instruction.AND, AddressingMode.ABSOLUTE_X, 4),
0x39 to Opcode(Instruction.AND, AddressingMode.ABSOLUTE_Y, 4),
0x21 to Opcode(Instruction.AND, AddressingMode.INDEXED_INDIRECT, 6),
0x31 to Opcode(Instruction.AND, AddressingMode.INDIRECT_INDEXED, 5),
0x0A to Opcode(Instruction.ASL, AddressingMode.ACCUMULATOR, 2),
0x06 to Opcode(Instruction.ASL, AddressingMode.ZERO_PAGE, 5),
0x16 to Opcode(Instruction.ASL, AddressingMode.ZERO_PAGE_X, 6),
0x0E to Opcode(Instruction.ASL, AddressingMode.ABSOLUTE, 6),
0x1E to Opcode(Instruction.ASL, AddressingMode.ABSOLUTE_X, 7),
0x90 to Opcode(Instruction.BCC, AddressingMode.RELATIVE, 2),
0xB0 to Opcode(Instruction.BCS, AddressingMode.RELATIVE, 2),
0xF0 to Opcode(Instruction.BEQ, AddressingMode.RELATIVE, 2),
0x24 to Opcode(Instruction.BIT, AddressingMode.ZERO_PAGE, 3),
0x2C to Opcode(Instruction.BIT, AddressingMode.ABSOLUTE, 4),
0x30 to Opcode(Instruction.BMI, AddressingMode.RELATIVE, 2),
0xD0 to Opcode(Instruction.BNE, AddressingMode.RELATIVE, 2),
0x10 to Opcode(Instruction.BPL, AddressingMode.RELATIVE, 2),
0x00 to Opcode(Instruction.BRK, AddressingMode.IMPLICIT, 7),
0x50 to Opcode(Instruction.BVC, AddressingMode.RELATIVE, 2),
0x70 to Opcode(Instruction.BVS, AddressingMode.RELATIVE, 2),
0x18 to Opcode(Instruction.CLC, AddressingMode.IMPLICIT, 2),
0xD8 to Opcode(Instruction.CLD, AddressingMode.IMPLICIT, 2),
0x58 to Opcode(Instruction.CLI, AddressingMode.IMPLICIT, 2),
0xB8 to Opcode(Instruction.CLV, AddressingMode.IMPLICIT, 2),
0xC9 to Opcode(Instruction.CMP, AddressingMode.IMMEDIATE, 2),
0xC5 to Opcode(Instruction.CMP, AddressingMode.ZERO_PAGE, 3),
0xD5 to Opcode(Instruction.CMP, AddressingMode.ZERO_PAGE_X, 4),
0xCD to Opcode(Instruction.CMP, AddressingMode.ABSOLUTE, 4),
0xDD to Opcode(Instruction.CMP, AddressingMode.ABSOLUTE_X, 4),
0xD9 to Opcode(Instruction.CMP, AddressingMode.ABSOLUTE_Y, 4),
0xC1 to Opcode(Instruction.CMP, AddressingMode.INDEXED_INDIRECT, 6),
0xD1 to Opcode(Instruction.CMP, AddressingMode.INDIRECT_INDEXED, 5),
0xE0 to Opcode(Instruction.CPX, AddressingMode.IMMEDIATE, 2),
0xE4 to Opcode(Instruction.CPX, AddressingMode.ZERO_PAGE, 3),
0xEC to Opcode(Instruction.CPX, AddressingMode.ABSOLUTE, 4),
0xC0 to Opcode(Instruction.CPY, AddressingMode.IMMEDIATE, 2),
0xC4 to Opcode(Instruction.CPY, AddressingMode.ZERO_PAGE, 3),
0xCC to Opcode(Instruction.CPY, AddressingMode.ABSOLUTE, 4),
0xC6 to Opcode(Instruction.DEC, AddressingMode.ZERO_PAGE, 5),
0xD6 to Opcode(Instruction.DEC, AddressingMode.ZERO_PAGE_X, 6),
0xCE to Opcode(Instruction.DEC, AddressingMode.ABSOLUTE, 6),
0xDE to Opcode(Instruction.DEC, AddressingMode.ABSOLUTE_X, 7),
0xCA to Opcode(Instruction.DEX, AddressingMode.IMPLICIT, 2),
0x88 to Opcode(Instruction.DEY, AddressingMode.IMPLICIT, 2),
0x49 to Opcode(Instruction.EOR, AddressingMode.IMMEDIATE, 2),
0x45 to Opcode(Instruction.EOR, AddressingMode.ZERO_PAGE, 3),
0x55 to Opcode(Instruction.EOR, AddressingMode.ZERO_PAGE_X, 4),
0x4D to Opcode(Instruction.EOR, AddressingMode.ABSOLUTE, 4),
0x5D to Opcode(Instruction.EOR, AddressingMode.ABSOLUTE_X, 4),
0x59 to Opcode(Instruction.EOR, AddressingMode.ABSOLUTE_Y, 4),
0x41 to Opcode(Instruction.EOR, AddressingMode.INDEXED_INDIRECT, 6),
0x51 to Opcode(Instruction.EOR, AddressingMode.INDIRECT_INDEXED, 5),
0xE6 to Opcode(Instruction.INC, AddressingMode.ZERO_PAGE, 5),
0xF6 to Opcode(Instruction.INC, AddressingMode.ZERO_PAGE_X, 6),
0xEE to Opcode(Instruction.INC, AddressingMode.ABSOLUTE, 6),
0xFE to Opcode(Instruction.INC, AddressingMode.ABSOLUTE_X, 7),
0xE8 to Opcode(Instruction.INX, AddressingMode.IMPLICIT, 2),
0xC8 to Opcode(Instruction.INY, AddressingMode.IMPLICIT, 2),
0x4C to Opcode(Instruction.JMP, AddressingMode.ABSOLUTE, 3),
0x6C to Opcode(Instruction.JMP, AddressingMode.INDIRECT, 5),
0x20 to Opcode(Instruction.JSR, AddressingMode.ABSOLUTE, 6),
0xA9 to Opcode(Instruction.LDA, AddressingMode.IMMEDIATE, 2),
0xA5 to Opcode(Instruction.LDA, AddressingMode.ZERO_PAGE, 3),
0xB5 to Opcode(Instruction.LDA, AddressingMode.ZERO_PAGE_X, 4),
0xAD to Opcode(Instruction.LDA, AddressingMode.ABSOLUTE, 4),
0xBD to Opcode(Instruction.LDA, AddressingMode.ABSOLUTE_X, 4),
0xB9 to Opcode(Instruction.LDA, AddressingMode.ABSOLUTE_Y, 4),
0xA1 to Opcode(Instruction.LDA, AddressingMode.INDEXED_INDIRECT, 6),
0xB1 to Opcode(Instruction.LDA, AddressingMode.INDIRECT_INDEXED, 5),
0xA2 to Opcode(Instruction.LDX, AddressingMode.IMMEDIATE, 2),
0xA6 to Opcode(Instruction.LDX, AddressingMode.ZERO_PAGE, 3),
0xB6 to Opcode(Instruction.LDX, AddressingMode.ZERO_PAGE_Y, 4),
0xAE to Opcode(Instruction.LDX, AddressingMode.ABSOLUTE, 4),
0xBE to Opcode(Instruction.LDX, AddressingMode.ABSOLUTE_Y, 4),
0xA0 to Opcode(Instruction.LDY, AddressingMode.IMMEDIATE, 2),
0xA4 to Opcode(Instruction.LDY, AddressingMode.ZERO_PAGE, 3),
0xB4 to Opcode(Instruction.LDY, AddressingMode.ZERO_PAGE_X, 4),
0xAC to Opcode(Instruction.LDY, AddressingMode.ABSOLUTE, 4),
0xBC to Opcode(Instruction.LDY, AddressingMode.ABSOLUTE_X, 4),
0x4A to Opcode(Instruction.LSR, AddressingMode.ACCUMULATOR, 2),
0x46 to Opcode(Instruction.LSR, AddressingMode.ZERO_PAGE, 5),
0x56 to Opcode(Instruction.LSR, AddressingMode.ZERO_PAGE_X, 6),
0x4E to Opcode(Instruction.LSR, AddressingMode.ABSOLUTE, 6),
0x5E to Opcode(Instruction.LSR, AddressingMode.ABSOLUTE_X, 7),
0xEA to Opcode(Instruction.NOP, AddressingMode.IMPLICIT, 2),
0x09 to Opcode(Instruction.ORA, AddressingMode.IMMEDIATE, 2),
0x05 to Opcode(Instruction.ORA, AddressingMode.ZERO_PAGE, 3),
0x15 to Opcode(Instruction.ORA, AddressingMode.ZERO_PAGE_X, 4),
0x0D to Opcode(Instruction.ORA, AddressingMode.ABSOLUTE, 4),
0x1D to Opcode(Instruction.ORA, AddressingMode.ABSOLUTE_X, 4),
0x19 to Opcode(Instruction.ORA, AddressingMode.ABSOLUTE_Y, 4),
0x01 to Opcode(Instruction.ORA, AddressingMode.INDEXED_INDIRECT, 6),
0x11 to Opcode(Instruction.ORA, AddressingMode.INDIRECT_INDEXED, 5),
0x48 to Opcode(Instruction.PHA, AddressingMode.IMPLICIT, 3),
0x08 to Opcode(Instruction.PHP, AddressingMode.IMPLICIT, 3),
0x68 to Opcode(Instruction.PLA, AddressingMode.IMPLICIT, 4),
0x28 to Opcode(Instruction.PLP, AddressingMode.IMPLICIT, 4),
0x2A to Opcode(Instruction.ROL, AddressingMode.ACCUMULATOR, 2),
0x26 to Opcode(Instruction.ROL, AddressingMode.ZERO_PAGE, 5),
0x36 to Opcode(Instruction.ROL, AddressingMode.ZERO_PAGE_X, 6),
0x2E to Opcode(Instruction.ROL, AddressingMode.ABSOLUTE, 6),
0x3E to Opcode(Instruction.ROL, AddressingMode.ABSOLUTE_X, 7),
0x6A to Opcode(Instruction.ROR, AddressingMode.ACCUMULATOR, 2),
0x66 to Opcode(Instruction.ROR, AddressingMode.ZERO_PAGE, 5),
0x76 to Opcode(Instruction.ROR, AddressingMode.ZERO_PAGE_X, 6),
0x6E to Opcode(Instruction.ROR, AddressingMode.ABSOLUTE, 6),
0x7E to Opcode(Instruction.ROR, AddressingMode.ABSOLUTE_X, 7),
0x40 to Opcode(Instruction.RTI, AddressingMode.IMPLICIT, 6),
0x60 to Opcode(Instruction.RTS, AddressingMode.IMPLICIT, 6),
0xE9 to Opcode(Instruction.SBC, AddressingMode.IMMEDIATE, 2),
// Unofficial
0xEB to Opcode(Instruction.SBC, AddressingMode.IMMEDIATE, 2),
0xE5 to Opcode(Instruction.SBC, AddressingMode.ZERO_PAGE, 3),
0xF5 to Opcode(Instruction.SBC, AddressingMode.ZERO_PAGE_X, 4),
0xED to Opcode(Instruction.SBC, AddressingMode.ABSOLUTE, 4),
0xFD to Opcode(Instruction.SBC, AddressingMode.ABSOLUTE_X, 4),
0xF9 to Opcode(Instruction.SBC, AddressingMode.ABSOLUTE_Y, 4),
0xE1 to Opcode(Instruction.SBC, AddressingMode.INDEXED_INDIRECT, 6),
0xF1 to Opcode(Instruction.SBC, AddressingMode.INDIRECT_INDEXED, 5),
0x38 to Opcode(Instruction.SEC, AddressingMode.IMPLICIT, 2),
0xF8 to Opcode(Instruction.SED, AddressingMode.IMPLICIT, 2),
0x78 to Opcode(Instruction.SEI, AddressingMode.IMPLICIT, 2),
0x85 to Opcode(Instruction.STA, AddressingMode.ZERO_PAGE, 3),
0x95 to Opcode(Instruction.STA, AddressingMode.ZERO_PAGE_X, 4),
0x8D to Opcode(Instruction.STA, AddressingMode.ABSOLUTE, 4),
0x9D to Opcode(Instruction.STA, AddressingMode.ABSOLUTE_X, 5),
0x99 to Opcode(Instruction.STA, AddressingMode.ABSOLUTE_Y, 5),
0x81 to Opcode(Instruction.STA, AddressingMode.INDEXED_INDIRECT, 6),
0x91 to Opcode(Instruction.STA, AddressingMode.INDIRECT_INDEXED, 6),
0x86 to Opcode(Instruction.STX, AddressingMode.ZERO_PAGE, 3),
0x96 to Opcode(Instruction.STX, AddressingMode.ZERO_PAGE_Y, 4),
0x8E to Opcode(Instruction.STX, AddressingMode.ABSOLUTE, 4),
0x84 to Opcode(Instruction.STY, AddressingMode.ZERO_PAGE, 3),
0x94 to Opcode(Instruction.STY, AddressingMode.ZERO_PAGE_X, 4),
0x8C to Opcode(Instruction.STY, AddressingMode.ABSOLUTE, 4),
0xAA to Opcode(Instruction.TAX, AddressingMode.IMPLICIT, 2),
0xA8 to Opcode(Instruction.TAY, AddressingMode.IMPLICIT, 2),
0xBA to Opcode(Instruction.TSX, AddressingMode.IMPLICIT, 2),
0x8A to Opcode(Instruction.TXA, AddressingMode.IMPLICIT, 2),
0x9A to Opcode(Instruction.TXS, AddressingMode.IMPLICIT, 2),
0x98 to Opcode(Instruction.TYA, AddressingMode.IMPLICIT, 2),
0x4B to Opcode(Instruction.ALR, AddressingMode.IMMEDIATE, 2),
0x0B to Opcode(Instruction.ANC, AddressingMode.IMMEDIATE, 2),
0x2B to Opcode(Instruction.ANC, AddressingMode.IMMEDIATE, 2),
0x6B to Opcode(Instruction.ARR, AddressingMode.IMMEDIATE, 2),
0xCB to Opcode(Instruction.AXS, AddressingMode.IMMEDIATE, 2),
0xA3 to Opcode(Instruction.LAX, AddressingMode.INDEXED_INDIRECT, 6),
0xA7 to Opcode(Instruction.LAX, AddressingMode.ZERO_PAGE, 3),
0xAF to Opcode(Instruction.LAX, AddressingMode.ABSOLUTE, 4),
0xB3 to Opcode(Instruction.LAX, AddressingMode.INDIRECT_INDEXED, 5),
0xB7 to Opcode(Instruction.LAX, AddressingMode.ZERO_PAGE_Y, 4),
0xBF to Opcode(Instruction.LAX, AddressingMode.ABSOLUTE_Y, 4),
0x83 to Opcode(Instruction.SAX, AddressingMode.INDEXED_INDIRECT, 6),
0x87 to Opcode(Instruction.SAX, AddressingMode.ZERO_PAGE, 3),
0x8F to Opcode(Instruction.SAX, AddressingMode.ABSOLUTE, 4),
0x97 to Opcode(Instruction.SAX, AddressingMode.ZERO_PAGE_Y, 4),
0xC3 to Opcode(Instruction.DCP, AddressingMode.INDEXED_INDIRECT, 8),
0xC7 to Opcode(Instruction.DCP, AddressingMode.ZERO_PAGE, 5),
0xCF to Opcode(Instruction.DCP, AddressingMode.ABSOLUTE, 6),
0xD3 to Opcode(Instruction.DCP, AddressingMode.INDIRECT_INDEXED, 8),
0xD7 to Opcode(Instruction.DCP, AddressingMode.ZERO_PAGE_X, 6),
0xDB to Opcode(Instruction.DCP, AddressingMode.ABSOLUTE_Y, 7),
0xDF to Opcode(Instruction.DCP, AddressingMode.ABSOLUTE_X, 7),
0xE3 to Opcode(Instruction.ISC, AddressingMode.INDEXED_INDIRECT, 8),
0xE7 to Opcode(Instruction.ISC, AddressingMode.ZERO_PAGE, 5),
0xEF to Opcode(Instruction.ISC, AddressingMode.ABSOLUTE, 6),
0xF3 to Opcode(Instruction.ISC, AddressingMode.INDIRECT_INDEXED, 8),
0xF7 to Opcode(Instruction.ISC, AddressingMode.ZERO_PAGE_X, 6),
0xFB to Opcode(Instruction.ISC, AddressingMode.ABSOLUTE_Y, 7),
0xFF to Opcode(Instruction.ISC, AddressingMode.ABSOLUTE_X, 7),
0x23 to Opcode(Instruction.RLA, AddressingMode.INDEXED_INDIRECT, 8),
0x27 to Opcode(Instruction.RLA, AddressingMode.ZERO_PAGE, 5),
0x2F to Opcode(Instruction.RLA, AddressingMode.ABSOLUTE, 6),
0x33 to Opcode(Instruction.RLA, AddressingMode.INDIRECT_INDEXED, 8),
0x37 to Opcode(Instruction.RLA, AddressingMode.ZERO_PAGE_X, 6),
0x3B to Opcode(Instruction.RLA, AddressingMode.ABSOLUTE_Y, 7),
0x3F to Opcode(Instruction.RLA, AddressingMode.ABSOLUTE_X, 7),
0x63 to Opcode(Instruction.RRA, AddressingMode.INDEXED_INDIRECT, 8),
0x67 to Opcode(Instruction.RRA, AddressingMode.ZERO_PAGE, 5),
0x6F to Opcode(Instruction.RRA, AddressingMode.ABSOLUTE, 6),
0x73 to Opcode(Instruction.RRA, AddressingMode.INDIRECT_INDEXED, 8),
0x77 to Opcode(Instruction.RRA, AddressingMode.ZERO_PAGE_X, 6),
0x7B to Opcode(Instruction.RRA, AddressingMode.ABSOLUTE_Y, 7),
0x7F to Opcode(Instruction.RRA, AddressingMode.ABSOLUTE_X, 7),
0x03 to Opcode(Instruction.SLO, AddressingMode.INDEXED_INDIRECT, 8),
0x07 to Opcode(Instruction.SLO, AddressingMode.ZERO_PAGE, 5),
0x0F to Opcode(Instruction.SLO, AddressingMode.ABSOLUTE, 6),
0x13 to Opcode(Instruction.SLO, AddressingMode.INDIRECT_INDEXED, 8),
0x17 to Opcode(Instruction.SLO, AddressingMode.ZERO_PAGE_X, 6),
0x1B to Opcode(Instruction.SLO, AddressingMode.ABSOLUTE_Y, 7),
0x1F to Opcode(Instruction.SLO, AddressingMode.ABSOLUTE_X, 7),
0x43 to Opcode(Instruction.SRE, AddressingMode.INDEXED_INDIRECT, 8),
0x47 to Opcode(Instruction.SRE, AddressingMode.ZERO_PAGE, 5),
0x4F to Opcode(Instruction.SRE, AddressingMode.ABSOLUTE, 6),
0x53 to Opcode(Instruction.SRE, AddressingMode.INDIRECT_INDEXED, 8),
0x57 to Opcode(Instruction.SRE, AddressingMode.ZERO_PAGE_X, 6),
0x5B to Opcode(Instruction.SRE, AddressingMode.ABSOLUTE_Y, 7),
0x5F to Opcode(Instruction.SRE, AddressingMode.ABSOLUTE_X, 7),
0x1A to Opcode(Instruction.NOP, AddressingMode.IMPLICIT, 2),
0x3A to Opcode(Instruction.NOP, AddressingMode.IMPLICIT, 2),
0x5A to Opcode(Instruction.NOP, AddressingMode.IMPLICIT, 2),
0x7A to Opcode(Instruction.NOP, AddressingMode.IMPLICIT, 2),
0xDA to Opcode(Instruction.NOP, AddressingMode.IMPLICIT, 2),
0xFA to Opcode(Instruction.NOP, AddressingMode.IMPLICIT, 2),
0x80 to Opcode(Instruction.SKB, AddressingMode.IMMEDIATE, 2),
0x82 to Opcode(Instruction.SKB, AddressingMode.IMMEDIATE, 2),
0x89 to Opcode(Instruction.SKB, AddressingMode.IMMEDIATE, 2),
0xC2 to Opcode(Instruction.SKB, AddressingMode.IMMEDIATE, 2),
0xE2 to Opcode(Instruction.SKB, AddressingMode.IMMEDIATE, 2),
0x0C to Opcode(Instruction.IGN, AddressingMode.ABSOLUTE, 4),
0x1C to Opcode(Instruction.IGN, AddressingMode.ABSOLUTE_X, 5),
0x3C to Opcode(Instruction.IGN, AddressingMode.ABSOLUTE_X, 5),
0x5C to Opcode(Instruction.IGN, AddressingMode.ABSOLUTE_X, 5),
0x7C to Opcode(Instruction.IGN, AddressingMode.ABSOLUTE_X, 5),
0xDC to Opcode(Instruction.IGN, AddressingMode.ABSOLUTE_X, 5),
0xFC to Opcode(Instruction.IGN, AddressingMode.ABSOLUTE_X, 5),
0x04 to Opcode(Instruction.IGN, AddressingMode.ZERO_PAGE, 3),
0x44 to Opcode(Instruction.IGN, AddressingMode.ZERO_PAGE, 3),
0x64 to Opcode(Instruction.IGN, AddressingMode.ZERO_PAGE, 3),
0x14 to Opcode(Instruction.IGN, AddressingMode.ZERO_PAGE_X, 4),
0x34 to Opcode(Instruction.IGN, AddressingMode.ZERO_PAGE_X, 4),
0x54 to Opcode(Instruction.IGN, AddressingMode.ZERO_PAGE_X, 4),
0x74 to Opcode(Instruction.IGN, AddressingMode.ZERO_PAGE_X, 4),
0xD4 to Opcode(Instruction.IGN, AddressingMode.ZERO_PAGE_X, 4),
0xF4 to Opcode(Instruction.IGN, AddressingMode.ZERO_PAGE_X, 4)
)
fun find(code: Int): Opcode {
return opcodeMap.getValue(code)
}
}
}
internal enum class Instruction {
ADC, // add with carry
AND, // and (with accumulator)
ASL, // arithmetic shift left
BCC, // branch on carry clear
BCS, // branch on carry set
BEQ, // branch on equal (zero set)
BIT, // bit test
BMI, // branch on minus (negative set)
BNE, // branch on not equal (zero clear)
BPL, // branch on plus (negative clear)
BRK, // break / interrupt
BVC, // branch on overflow clear
BVS, // on overflow set
CLC, // clear carry
CLD, // clear decimal
CLI, // clear interrupt disable
CLV, // clear overflow
CMP, // compare (with accumulator)
CPX, // compare with X
CPY, // compare with Y
DEC, // decrement
DEX, // decrement X
DEY, // decrement Y
EOR, // exclusive or (with accumulator)
INC, // increment
INX, // increment X
INY, // increment Y
JMP, // jump
JSR, // jump subroutine
LDA, // load accumulator
LDX, // load X
LDY, // load Y
LSR, // logical shift right
NOP, // no operation
ORA, // or with accumulator
PHA, // push accumulator
PHP, // push processor status (SR)
PLA, // pull accumulator
PLP, // pull processor status (SR)
ROL, // rotate left
ROR, // rotate right
RTI, // return from interrupt
RTS, // return from subroutine
SBC, // subtract with carry
SEC, // set carry
SED, // set decimal
SEI, // set interrupt disable
STA, // store accumulator
STX, // store X
STY, // store Y
TAX, // transfer accumulator to X
TAY, // transfer accumulator to Y
TSX, // transfer stack pointer to X
TXA, // transfer X to accumulator
TXS, // transfer X to stack pointer
TYA, // transfer Y to accumulator
// https://wiki.nesdev.com/w/index.php/Programming_with_unofficial_opcodes
ALR, // Equivalent to AND #i then LSR A
ANC, // Does AND #i, setting N and Z flags based on the result. Then it copies N (bit 7) to C
ARR, // Similar to AND #i then ROR A, except sets the flags differently. N and Z are normal, but C is bit 6 and V is bit 6 xor bit 5
AXS, // Sets X to {(A AND X) - #value without borrow}, and updates NZC
LAX, // Shortcut for LDA value then TAX
SAX, // Stores the bitwise AND of A and X
DCP, // Equivalent to DEC value then CMP value
ISC, // Equivalent to INC value then SBC value
RLA, // Equivalent to ROL value then AND value
RRA, // Equivalent to ROR value then ADC value
SLO, // Equivalent to ASL value then ORA value
SRE, // Equivalent to LSR value then EOR value
SKB, // These unofficial opcodes just read an immediate byte and skip it
IGN, // Reads from memory at the specified address and ignores the value
}
internal enum class AddressingMode {
IMPLICIT,
ACCUMULATOR,
IMMEDIATE,
ZERO_PAGE,
ZERO_PAGE_X,
ZERO_PAGE_Y,
RELATIVE,
ABSOLUTE,
ABSOLUTE_X,
ABSOLUTE_Y,
INDIRECT,
INDEXED_INDIRECT,
INDIRECT_INDEXED,
}
| 0
|
Kotlin
|
0
| 1
|
96d02a897078f62aacafb13a09a8c3c0155d20e2
| 21,343
|
konessem
|
Apache License 2.0
|
generated/src/main/kotlin/com/laidpack/sourcerer/generated/ViewFactory.kt
|
kaizhiyu
| 271,434,423
| true
|
{"Kotlin": 3920018, "JavaScript": 1617829, "TypeScript": 115897, "CSS": 39708}
|
package com.laidpack.sourcerer.generated
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import androidx.core.content.ContextCompat
import com.laidpack.generator.api.ViewGroupElement
import com.laidpack.sourcerer.services.api.BaseViewFactory
import com.laidpack.sourcerer.services.api.toPorterDuffMode
import java.lang.Class
import kotlin.String
@ViewGroupElement(
elementType = ViewFactory.elementType,
attributesClazz = ViewAttributes::class,
layoutParamAttributesClazz = ViewGroupLayoutParamsAttributes::class
)
open class ViewFactory<TView : View, TAttributes : ViewAttributes>(instanceType: Class<TView>, attributesType: Class<TAttributes>) : BaseViewFactory<TView, TAttributes>(instanceType, attributesType) {
override val elementType: String = Companion.elementType
override fun createInstance(context: Context): View = View(context)
override fun init(
view: View,
context: Context,
attributes: TAttributes
) {
view.apply {
attributes.id?.let {
if (id != it) {
id = it
}
}
attributes.tag?.let {
val localTag = it
if (tag != localTag) {
tag = localTag
}
}
if (attributes.scrollX != null || attributes.scrollY != null) {
val localScrollX = attributes.scrollX ?: scrollX
val localScrollY = attributes.scrollY ?: scrollY
if (scrollX != localScrollX || scrollY != localScrollY) {
scrollTo(localScrollX, localScrollY)
}
}
attributes.focusableInTouchMode?.let {
if (isFocusableInTouchMode != it) {
isFocusableInTouchMode = it
}
}
attributes.visibility?.let {
if (visibility != it.value) {
visibility = it.value
}
}
attributes.scrollbarStyle?.let {
if (scrollBarStyle != it.value) {
scrollBarStyle = it.value
}
}
attributes.nextFocusLeft?.let {
if (nextFocusLeftId != it) {
nextFocusLeftId = it
}
}
attributes.nextFocusRight?.let {
if (nextFocusRightId != it) {
nextFocusRightId = it
}
}
attributes.nextFocusUp?.let {
if (nextFocusUpId != it) {
nextFocusUpId = it
}
}
attributes.nextFocusDown?.let {
if (nextFocusDownId != it) {
nextFocusDownId = it
}
}
attributes.clickable?.let {
if (isClickable != it) {
isClickable = it
}
}
attributes.longClickable?.let {
if (isLongClickable != it) {
isLongClickable = it
}
}
attributes.saveEnabled?.let {
if (isEnabled != it) {
isSaveEnabled = it
}
}
attributes.keepScreenOn?.let {
if (keepScreenOn != it) {
keepScreenOn = it
}
}
attributes.soundEffectsEnabled?.let {
if (isSoundEffectsEnabled != it) {
isSoundEffectsEnabled = it
}
}
attributes.drawingCacheQuality?.let {
if (drawingCacheQuality != it.value) {
drawingCacheQuality = it.value
}
}
attributes.hapticFeedbackEnabled?.let {
if (isHapticFeedbackEnabled != it) {
isHapticFeedbackEnabled = it
}
}
attributes.contentDescription?.let {
if (contentDescription != it) {
contentDescription = it
}
}
attributes.fadeScrollbars?.let {
if (isScrollbarFadingEnabled != it) {
isScrollbarFadingEnabled = it
}
}
attributes.filterTouchesWhenObscured?.let {
if (isEnabled != it) {
filterTouchesWhenObscured = it
}
}
attributes.overScrollMode?.let {
if (overScrollMode != it.value) {
overScrollMode = it.value
}
}
attributes.nextFocusForward?.let {
if (nextFocusForwardId != it) {
nextFocusForwardId = it
}
}
attributes.alpha?.let {
if (alpha != it) {
alpha = it
}
}
attributes.translationX?.let {
val localTranslationX = it.toFloat()
if (translationX != localTranslationX) {
translationX = localTranslationX
}
}
attributes.translationY?.let {
val localTranslationY = it.toFloat()
if (translationY != localTranslationY) {
translationY = localTranslationY
}
}
attributes.transformPivotX?.let {
val localTransformPivotX = it.toFloat()
if (pivotX != localTransformPivotX) {
pivotX = localTransformPivotX
}
}
attributes.transformPivotY?.let {
val localTransformPivotY = it.toFloat()
if (pivotY != localTransformPivotY) {
pivotY = localTransformPivotY
}
}
attributes.rotation?.let {
if (rotation != it) {
rotation = it
}
}
attributes.rotationX?.let {
if (rotationX != it) {
rotationX = it
}
}
attributes.rotationY?.let {
if (rotationY != it) {
rotationY = it
}
}
attributes.scaleX?.let {
if (scaleX != it) {
scaleX = it
}
}
attributes.scaleY?.let {
if (scaleY != it) {
scaleY = it
}
}
attributes.verticalScrollbarPosition?.let {
if (verticalScrollbarPosition != it.value) {
verticalScrollbarPosition = it.value
}
}
attributes.layerType?.let {
if (layerType != it.value) {
setLayerType(it.value, null)
}
}
if (Build.VERSION.SDK_INT >= 16) {
if (attributes.background.hasColor || attributes.background.hasReference) {
val localBackground = when {
attributes.background.hasColor -> ColorDrawable(attributes.background.color)
else -> ContextCompat.getDrawable(context, attributes.background.reference) as Drawable
}
if (background != localBackground) {
background = localBackground
}
}
attributes.fitsSystemWindows?.let {
if (fitsSystemWindows != it) {
fitsSystemWindows = it
}
}
attributes.isScrollContainer?.let {
if (isScrollContainer != it) {
isScrollContainer = it
}
}
attributes.scrollbarFadeDuration?.let {
if (scrollBarFadeDuration != it) {
scrollBarFadeDuration = it
}
}
attributes.scrollbarDefaultDelayBeforeFade?.let {
if (scrollBarDefaultDelayBeforeFade != it) {
scrollBarDefaultDelayBeforeFade = it
}
}
attributes.scrollbarSize?.let {
if (scrollBarSize != it) {
scrollBarSize = it
}
}
attributes.minHeight?.let {
if (minimumHeight != it) {
minimumHeight = it
}
}
attributes.minWidth?.let {
if (minimumWidth != it) {
minimumWidth = it
}
}
if (attributes.importantForAccessibility.hasInteger || attributes.importantForAccessibility.hasEnum) {
val localImportantForAccessibility = when {
attributes.importantForAccessibility.hasInteger -> attributes.importantForAccessibility.integer
else -> attributes.importantForAccessibility.enum
}
if (importantForAccessibility != localImportantForAccessibility) {
importantForAccessibility = localImportantForAccessibility
}
}
}
if (Build.VERSION.SDK_INT >= 17) {
if (attributes.paddingLeft != null || attributes.paddingBottom != null || attributes.paddingEnd != null || attributes.paddingStart != null || attributes.paddingTop != null || attributes.paddingRight != null) {
val localPaddingBottomDimension = attributes.paddingBottom ?: bottom
val localPaddingLeftDimension = attributes.paddingLeft ?: left
val localPaddingRightDimension = attributes.paddingRight ?: right
val localPaddingTopDimension = attributes.paddingTop ?: top
if (bottom != localPaddingBottomDimension || left != localPaddingLeftDimension || right != localPaddingRightDimension || top != localPaddingTopDimension) {
setPadding(localPaddingLeftDimension, localPaddingTopDimension, localPaddingRightDimension, localPaddingBottomDimension)
}
val localPaddingEndDimension = attributes.paddingEnd ?: paddingEnd
val localPaddingStartDimension = attributes.paddingStart ?: paddingStart
if (bottom != localPaddingBottomDimension || paddingEnd != localPaddingEndDimension || paddingStart != localPaddingStartDimension || top != localPaddingTopDimension) {
setPaddingRelative(localPaddingStartDimension, localPaddingTopDimension, localPaddingEndDimension, localPaddingBottomDimension)
}
}
attributes.layoutDirection?.let {
if (layoutDirection != it.value) {
layoutDirection = it.value
}
}
if (attributes.textDirection.hasInteger || attributes.textDirection.hasEnum) {
val localTextDirection = when {
attributes.textDirection.hasInteger -> attributes.textDirection.integer
else -> attributes.textDirection.enum
}
if (textDirection != localTextDirection) {
textDirection = localTextDirection
}
}
if (attributes.textAlignment.hasInteger || attributes.textAlignment.hasEnum) {
val localTextAlignment = when {
attributes.textAlignment.hasInteger -> attributes.textAlignment.integer
else -> attributes.textAlignment.enum
}
if (textAlignment != localTextAlignment) {
textAlignment = localTextAlignment
}
}
attributes.labelFor?.let {
if (labelFor != it) {
labelFor = it
}
}
}
if (Build.VERSION.SDK_INT >= 19) {
if (attributes.accessibilityLiveRegion.hasInteger || attributes.accessibilityLiveRegion.hasEnum) {
val localAccessibilityLiveRegion = when {
attributes.accessibilityLiveRegion.hasInteger -> attributes.accessibilityLiveRegion.integer
else -> attributes.accessibilityLiveRegion.enum
}
if (accessibilityLiveRegion != localAccessibilityLiveRegion) {
accessibilityLiveRegion = localAccessibilityLiveRegion
}
}
}
if (Build.VERSION.SDK_INT >= 21) {
attributes.elevation?.let {
val localElevation = it.toFloat()
if (elevation != localElevation) {
elevation = localElevation
}
}
attributes.translationZ?.let {
val localTranslationZ = it.toFloat()
if (translationZ != localTranslationZ) {
translationZ = localTranslationZ
}
}
attributes.transitionName?.let {
if (transitionName != it) {
transitionName = it
}
}
attributes.nestedScrollingEnabled?.let {
if (isEnabled != it) {
isNestedScrollingEnabled = it
}
}
attributes.backgroundTint?.let {
val localBackgroundTint = ColorStateList.valueOf(it)
if (backgroundTintList != localBackgroundTint) {
backgroundTintList = localBackgroundTint
}
}
attributes.backgroundTintMode?.let {
val localBackgroundTintMode = it.value.toPorterDuffMode()
if (backgroundTintMode != localBackgroundTintMode) {
backgroundTintMode = localBackgroundTintMode
}
}
}
if (Build.VERSION.SDK_INT >= 22) {
attributes.accessibilityTraversalBefore?.let {
if (accessibilityTraversalBefore != it) {
accessibilityTraversalBefore = it
}
}
attributes.accessibilityTraversalAfter?.let {
if (accessibilityTraversalAfter != it) {
accessibilityTraversalAfter = it
}
}
}
if (Build.VERSION.SDK_INT >= 23) {
attributes.contextClickable?.let {
if (isContextClickable != it) {
isContextClickable = it
}
}
if (attributes.foreground.hasColor || attributes.foreground.hasReference) {
val localForeground = when {
attributes.foreground.hasColor -> ColorDrawable(attributes.foreground.color)
else -> ContextCompat.getDrawable(context, attributes.foreground.reference) as Drawable
}
if (foreground != localForeground) {
foreground = localForeground
}
}
attributes.foregroundGravity?.let {
val localForegroundGravity = it.value
if (foregroundGravity != localForegroundGravity) {
foregroundGravity = localForegroundGravity
}
}
attributes.foregroundTint?.let {
val localForegroundTint = ColorStateList.valueOf(it)
if (foregroundTintList != localForegroundTint) {
foregroundTintList = localForegroundTint
}
}
attributes.foregroundTintMode?.let {
val localForegroundTintMode = it.value.toPorterDuffMode()
if (foregroundTintMode != localForegroundTintMode) {
foregroundTintMode = localForegroundTintMode
}
}
attributes.scrollIndicators?.let {
val localScrollIndicators = it.value
if (scrollIndicators != localScrollIndicators) {
scrollIndicators = localScrollIndicators
}
}
}
if (Build.VERSION.SDK_INT >= 24) {
attributes.forceHasOverlappingRendering?.let {
if (hasOverlappingRendering != it) {
forceHasOverlappingRendering(it)
}
}
}
if (Build.VERSION.SDK_INT >= 26) {
when {
attributes.focusable.hasBoolean -> {
val localFocusable = attributes.focusable.boolean
isFocusable = localFocusable
}
attributes.focusable.hasEnum -> {
val localFocusable = attributes.focusable.enum
focusable = localFocusable
}
}
if (attributes.autofillHints.hasReference || attributes.autofillHints.hasString) {
val localAutofillHints = when {
attributes.autofillHints.hasReference -> context.resources.getString(attributes.autofillHints.reference)
else -> attributes.autofillHints.string
}
setAutofillHints(localAutofillHints)
}
attributes.importantForAutofill?.let {
val localImportantForAutofill = it.value
if (importantForAutofill != localImportantForAutofill) {
importantForAutofill = localImportantForAutofill
}
}
attributes.tooltipText?.let {
if (tooltipText != it) {
tooltipText = it
}
}
attributes.keyboardNavigationCluster?.let {
if (isKeyboardNavigationCluster != it) {
isKeyboardNavigationCluster = it
}
}
attributes.nextClusterForward?.let {
if (nextClusterForwardId != it) {
nextClusterForwardId = it
}
}
attributes.focusedByDefault?.let {
if (isFocusedByDefault != it) {
isFocusedByDefault = it
}
}
attributes.defaultFocusHighlightEnabled?.let {
if (defaultFocusHighlightEnabled != it) {
defaultFocusHighlightEnabled = it
}
}
}
if (Build.VERSION.SDK_INT >= 28) {
attributes.screenReaderFocusable?.let {
if (isScreenReaderFocusable != it) {
isScreenReaderFocusable = it
}
}
attributes.accessibilityPaneTitle?.let {
if (accessibilityPaneTitle != it) {
accessibilityPaneTitle = it
}
}
attributes.accessibilityHeading?.let {
if (isAccessibilityHeading != it) {
isAccessibilityHeading = it
}
}
attributes.outlineSpotShadowColor?.let {
if (outlineSpotShadowColor != it) {
outlineSpotShadowColor = it
}
}
attributes.outlineAmbientShadowColor?.let {
if (outlineAmbientShadowColor != it) {
outlineAmbientShadowColor = it
}
}
}
}
}
companion object {
const val elementType: String = "view"
inline operator fun <reified TView : View, reified TAttributes : ViewAttributes> invoke() = ViewFactory(TView::class.java, TAttributes::class.java)
}
}
| 0
| null |
0
| 0
|
9513bbc54768e9248c450b0aba125b433c447e68
| 21,156
|
sourcerer
|
Apache License 2.0
|
src/main/java/com/jwg/launcher/launcher.kt
|
JuneDeveloper
| 510,437,513
| false
| null |
package com.jwg.launcher
import mainMenu
import javax.swing.UIManager
fun start() {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
mainMenu()
}
| 7
|
Kotlin
|
1
| 2
|
7ddc8ff8c0936dc390ecebe1bfc23bd063562537
| 175
|
JWG-Minecraft-Launcher
|
Apache License 2.0
|
src/lang-core/main/uk/co/reecedunn/intellij/plugin/intellij/lang/Model.kt
|
rhdunn
| 62,201,764
| false
|
{"Kotlin": 8262637, "XQuery": 996770, "HTML": 39377, "XSLT": 6853}
|
/*
* Copyright (C) 2017-2019 <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 uk.co.reecedunn.intellij.plugin.intellij.lang
interface Versioned {
val id: String
val name: String
val versions: List<Version>
fun versionsFor(product: Product, version: Version): List<Version> =
versions.filter { spec -> product.conformsTo(version, spec) }
fun supportsDialect(dialect: Versioned): Boolean = dialect === this
}
sealed class Version(val id: String, val value: Double, val kind: Versioned, val features: String? = null) {
fun toFeatureString(): String = features?.let { "$this - $it" } ?: toString()
}
class ProductVersion(id: String, kind: Versioned, features: String? = null) :
Version(id, id.toDouble(), kind, features) {
override fun toString(): String = "${kind.name} $id"
}
internal class UntilVersion(val until: Version) :
Version(until.id, until.value, until.kind, until.features) {
override fun toString(): String = "${kind.name} < $id"
override fun equals(other: Any?): Boolean = other is UntilVersion && until == other.until
override fun hashCode(): Int = until.hashCode()
}
fun until(until: Version): Version = UntilVersion(until)
class NamedVersion(id: String, value: Double, val name: String, kind: Versioned) : Version(id, value, kind) {
override fun toString(): String = kind.name + " " + name
}
open class Specification(
id: String,
value: Double,
val versionId: String,
kind: Versioned,
features: String? = null
) :
Version(id, value, kind, features) {
override fun toString(): String = kind.name + " " + versionId
}
class DraftSpecification(
id: String,
value: Double,
versionId: String,
kind: Versioned,
private val status: String,
features: String? = null
) :
Specification(id, value, versionId, kind, features) {
override fun toString(): String = "${super.toString()} ($status)"
}
enum class XQueryFeature {
MINIMAL_CONFORMANCE, // XQuery 1.0 - 3.1
FULL_AXIS, // XQuery 1.0
HIGHER_ORDER_FUNCTION, // XQuery 3.0 - 3.1
MODULE, // XQuery 1.0 - 3.1
SCHEMA_IMPORT, // XQuery 1.0; XQuery 3.0 - 3.1 ("Schema Aware")
SCHEMA_VALIDATION, // XQuery 1.0; XQuery 3.0 - 3.1 ("Schema Aware")
SERIALIZATION, // XQuery 1.0 - 3.1
STATIC_TYPING, // XQuery 1.0 - 3.1
TYPED_DATA, // XQuery 3.0 - 3.1
}
abstract class Product(val id: String, val name: String, val implementation: Implementation) {
override fun toString(): String = implementation.name + " " + name
abstract fun supportsFeature(version: Version, feature: XQueryFeature): Boolean
abstract fun conformsTo(productVersion: Version, ref: Version): Boolean
abstract fun flavoursForXQueryVersion(productVersion: Version, version: String): List<Versioned>
}
abstract class Implementation(
override val id: String,
override val name: String,
@Suppress("unused") val vendorUri: String
) :
Versioned {
abstract val products: List<Product>
abstract fun staticContext(product: Product?, productVersion: Version?, xqueryVersion: Specification?): String?
}
var DIALECTS: List<Versioned> = listOf(
// W3C Standard Dialects
XQuerySpec,
FullTextSpec,
UpdateFacilitySpec,
ScriptingSpec,
// Vendor Dialects
BaseX,
MarkLogic,
Saxon
)
fun dialectById(id: CharSequence?): Versioned? = DIALECTS.firstOrNull { dialect -> dialect.id == id }
/**
* Supports IDs used in XQueryProjectSettings to refer to XQuery implementations.
*
* This is designed to preserve the interoperability with the versioning scheme
* established in previous versions of the plugin.
*/
class VersionedProductId {
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(id: String?) {
this.id = id
}
constructor(product: Product?, productVersion: Version?) {
this.vendor = product?.implementation
this.product = product
this.productVersion = productVersion
}
var vendor: Implementation? = null
var product: Product? = null
var productVersion: Version? = null
var id: String?
get() = when (vendor) {
BaseX, EXistDB ->
if (productVersion == null) {
vendor?.id
} else {
"${vendor?.id}/v${productVersion?.id}"
}
MarkLogic ->
if (productVersion == null) {
vendor?.id
} else {
"${vendor?.id}/v${productVersion?.id?.replace(".0", "")}"
}
else ->
if (productVersion == null) {
if (product == null) {
vendor?.id
} else {
"${vendor?.id}/${product?.id}"
}
} else {
"${vendor?.id}/${product?.id}/v${productVersion?.id}"
}
}
set(value) {
val parts = value?.split("/") ?: listOf()
vendor = if (parts.isNotEmpty()) {
when (parts[0]) {
"basex" -> BaseX
"exist-db" -> EXistDB
"marklogic" -> MarkLogic
"saxon" -> Saxon
"w3c" -> W3C
else -> null
}
} else {
null
}
var version: Version? = null
if (parts.size >= 2 && vendor != null) {
if (parts[1].startsWith("v")) {
val versionId = parts[1].substring(1)
product = vendor!!.products[0]
// Support MarkLogic compatibility IDs -- e.g. mapping from v9 (old) to v9.0 (new).
version =
vendor!!.versions.find { v -> v.id == versionId }
?: vendor!!.versions.find { v -> v.id == "$versionId.0" }
} else {
product = vendor!!.products.find { p -> p.id == parts[1] }
}
} else {
product = null
}
if (parts.size >= 3 && vendor != null && product != null) {
if (parts[2].startsWith("v")) {
val versionId = parts[2].substring(1)
version = vendor!!.versions.find { v -> v.id == versionId }
}
}
if (version == null && product === W3C.SPECIFICATIONS) {
this.productVersion = when (parts.getOrNull(2)) {
"wd" -> W3C.WORKING_DRAFT
"2ed" -> W3C.SECOND_EDITION
else -> W3C.FIRST_EDITION
}
} else {
this.productVersion = version
}
}
}
| 49
|
Kotlin
|
9
| 25
|
d8d460d31334e8b2376a22f3832a20b2845bacab
| 7,360
|
xquery-intellij-plugin
|
Apache License 2.0
|
core/ui/src/main/kotlin/com/nsa/ui/ext/TimestampExt.kt
|
AkashShahriar55
| 752,580,500
| false
|
{"Kotlin": 380282, "Shell": 1395}
|
package com.nsa.ui.ext
import android.icu.text.SimpleDateFormat
import android.icu.util.TimeZone
import android.util.Log
import java.sql.Timestamp
import java.util.Date
import java.util.Locale
fun Timestamp.getFormatedText(outputFormat:String): String {
val timestampFormat = "yyyy-mm-dd hh:mm:ss.fffffffff"
val dateFormatter = SimpleDateFormat(outputFormat, Locale.getDefault())
dateFormatter.timeZone = TimeZone.getTimeZone("GMT")
val parser = SimpleDateFormat(timestampFormat, Locale.getDefault())
parser.timeZone = TimeZone.getTimeZone("GMT")
try {
val date = Date(this.time)
dateFormatter.timeZone = TimeZone.getDefault()
return dateFormatter.format(date)
} catch (e: Exception) {
// Handle parsing error
Log.d("check_date", "getFormatedText: ${e.localizedMessage}")
e.printStackTrace()
}
// If parsing fails, return the original timestamp
return toString()
}
| 0
|
Kotlin
|
0
| 1
|
0d8878200fe6aa45401287799da0740510350e3d
| 959
|
e2e-signal-compose-app
|
Apache License 2.0
|
src/main/kotlin/org/wint3794/ftc/pathfollower/debug/telemetries/UdpServer.kt
|
WinT-3794
| 267,687,048
| false
| null |
package org.wint3794.ftc.pathfollower.debug.telemetries
import org.wint3794.ftc.pathfollower.debug.Log
import org.wint3794.ftc.pathfollower.debug.Telemetry
import org.wint3794.ftc.pathfollower.util.Range
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.util.concurrent.Semaphore
class UdpServer : Telemetry, Runnable {
private val clientPort: Int
private var ip: InetAddress? = null
private val sendLock = Semaphore(1)
private var lastSendMillis: Long = 0
private var currentUpdate = ""
constructor(clientPort: Int) {
this.clientPort = clientPort
ip = InetAddress.getLocalHost()
}
constructor(ip: String?, clientPort: Int) {
this.clientPort = clientPort
this.ip = InetAddress.getByName(ip)
}
override fun run() {
while (isRunning) {
try {
if (System.currentTimeMillis() - lastSendMillis < 50) {
continue
}
lastSendMillis = System.currentTimeMillis()
sendLock.acquire()
if (currentUpdate.length > 0) {
send(currentUpdate)
currentUpdate = ""
}
sendLock.release()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}
fun send(message: String) {
var startIndex = 0
var endIndex: Int
do {
endIndex = Range.clip(startIndex + 600, 0, message.length - 1)
while (message[endIndex] != '%') {
endIndex--
}
val packet = message.substring(startIndex, endIndex + 1)
try {
DatagramSocket().use { serverSocket ->
val datagramPacket = DatagramPacket(
packet.toByteArray(),
packet.length,
ip,
clientPort
)
serverSocket.send(datagramPacket)
}
} catch (e: IOException) {
e.printStackTrace()
Log.error("Oh no! ${e.message}. Graphical Debugger will be disabled.", "UDP Server")
isRunning = false
break
}
startIndex = endIndex + 1
} while (endIndex != message.length - 1)
}
override fun print(log: String) {
println(log)
}
override fun close() {}
companion object {
@get:Synchronized
@set:Synchronized
var isRunning = false
}
}
| 0
|
Kotlin
|
1
| 0
|
8b05c46ddc25317158c9cf92ce9c68fd3e1b9c6e
| 2,675
|
PathFollower
|
Apache License 2.0
|
app/src/main/java/com/therxmv/dirolreader/ui/profile/utils/ProfileUiState.kt
|
therxmv
| 651,629,829
| false
| null |
package com.therxmv.dirolreader.ui.profile.utils
data class ProfileUiState(
val appBarState: AppBarState = AppBarState(),
)
data class AppBarState(
val avatarPath: String = "",
val userName: String = "",
)
| 0
|
Kotlin
|
0
| 8
|
c01fdd429a3a1105f9127312c3c94acec48a4f89
| 219
|
Dirol-Reader
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/ToDo.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.ToDo: ImageVector
get() {
if (_toDo != null) {
return _toDo!!
}
_toDo = Builder(name = "ToDo", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(16.5f, 18.0f)
horizontalLineToRelative(-0.5f)
lineTo(16.0f, 4.5f)
curveToRelative(0.0f, -2.481f, -2.019f, -4.5f, -4.5f, -4.5f)
horizontalLineToRelative(-7.0f)
curveTo(2.019f, 0.0f, 0.0f, 2.019f, 0.0f, 4.5f)
verticalLineToRelative(16.0f)
curveToRelative(0.0f, 1.93f, 1.569f, 3.499f, 3.498f, 3.5f)
horizontalLineToRelative(12.502f)
curveToRelative(1.654f, 0.0f, 3.0f, -1.346f, 3.0f, -3.0f)
verticalLineToRelative(-0.5f)
curveToRelative(0.0f, -1.379f, -1.121f, -2.5f, -2.5f, -2.5f)
close()
moveTo(5.0f, 20.5f)
curveToRelative(0.0f, 0.827f, -0.673f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.673f, -1.5f, -1.5f)
lineTo(2.0f, 4.5f)
curveToRelative(0.0f, -1.379f, 1.121f, -2.5f, 2.5f, -2.5f)
horizontalLineToRelative(7.0f)
curveToRelative(1.379f, 0.0f, 2.5f, 1.121f, 2.5f, 2.5f)
verticalLineToRelative(13.5f)
horizontalLineToRelative(-6.5f)
curveToRelative(-1.379f, 0.0f, -2.5f, 1.121f, -2.5f, 2.5f)
close()
moveTo(17.0f, 21.0f)
curveToRelative(0.0f, 0.552f, -0.448f, 1.0f, -1.0f, 1.0f)
lineTo(6.662f, 22.0f)
curveToRelative(0.217f, -0.455f, 0.338f, -0.964f, 0.338f, -1.5f)
curveToRelative(0.0f, -0.275f, 0.225f, -0.5f, 0.5f, -0.5f)
horizontalLineToRelative(9.0f)
curveToRelative(0.275f, 0.0f, 0.5f, 0.225f, 0.5f, 0.5f)
verticalLineToRelative(0.5f)
close()
moveTo(21.0f, 0.0f)
curveToRelative(-1.654f, 0.0f, -3.0f, 1.346f, -3.0f, 3.0f)
verticalLineToRelative(10.343f)
curveToRelative(0.0f, 1.336f, 0.521f, 2.592f, 1.465f, 3.536f)
lineToRelative(0.828f, 0.828f)
curveToRelative(0.195f, 0.195f, 0.451f, 0.293f, 0.707f, 0.293f)
reflectiveCurveToRelative(0.512f, -0.098f, 0.707f, -0.293f)
lineToRelative(0.828f, -0.828f)
curveToRelative(0.944f, -0.944f, 1.465f, -2.2f, 1.465f, -3.536f)
lineTo(24.0f, 3.0f)
curveToRelative(0.0f, -1.654f, -1.346f, -3.0f, -3.0f, -3.0f)
close()
moveTo(22.0f, 13.343f)
curveToRelative(0.0f, 0.802f, -0.313f, 1.556f, -0.879f, 2.122f)
lineToRelative(-0.121f, 0.121f)
lineToRelative(-0.121f, -0.121f)
curveToRelative(-0.566f, -0.566f, -0.879f, -1.32f, -0.879f, -2.122f)
lineTo(20.0f, 3.0f)
curveToRelative(0.0f, -0.552f, 0.448f, -1.0f, 1.0f, -1.0f)
reflectiveCurveToRelative(1.0f, 0.448f, 1.0f, 1.0f)
verticalLineToRelative(10.343f)
close()
moveTo(3.293f, 7.097f)
curveToRelative(-0.391f, -0.391f, -0.391f, -1.024f, 0.0f, -1.414f)
curveToRelative(0.391f, -0.391f, 1.023f, -0.391f, 1.414f, 0.0f)
lineToRelative(1.288f, 1.289f)
curveToRelative(0.033f, 0.033f, 0.105f, 0.033f, 0.139f, 0.0f)
lineToRelative(2.179f, -2.179f)
curveToRelative(0.391f, -0.391f, 1.023f, -0.391f, 1.414f, 0.0f)
reflectiveCurveToRelative(0.391f, 1.023f, 0.0f, 1.414f)
lineToRelative(-2.179f, 2.179f)
curveToRelative(-0.409f, 0.409f, -0.946f, 0.613f, -1.483f, 0.613f)
reflectiveCurveToRelative(-1.074f, -0.204f, -1.483f, -0.613f)
lineToRelative(-1.288f, -1.289f)
close()
moveTo(7.548f, 14.386f)
curveToRelative(-0.409f, 0.409f, -0.946f, 0.613f, -1.483f, 0.613f)
reflectiveCurveToRelative(-1.074f, -0.204f, -1.483f, -0.613f)
lineToRelative(-1.288f, -1.289f)
curveToRelative(-0.391f, -0.391f, -0.391f, -1.024f, 0.0f, -1.414f)
curveToRelative(0.391f, -0.391f, 1.023f, -0.391f, 1.414f, 0.0f)
lineToRelative(1.288f, 1.289f)
curveToRelative(0.033f, 0.033f, 0.105f, 0.033f, 0.139f, 0.0f)
lineToRelative(2.179f, -2.179f)
curveToRelative(0.391f, -0.391f, 1.023f, -0.391f, 1.414f, 0.0f)
reflectiveCurveToRelative(0.391f, 1.023f, 0.0f, 1.414f)
lineToRelative(-2.179f, 2.179f)
close()
}
}
.build()
return _toDo!!
}
private var _toDo: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 5,864
|
icons
|
MIT License
|
livekit-android-sdk/src/main/java/io/livekit/android/util/LoggingLevel.kt
|
livekit
| 339,892,560
| false
|
{"Kotlin": 1030460, "Java": 14523, "Shell": 3321}
|
/*
* Copyright 2023-2024 LiveKit, 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 io.livekit.android.util
import android.util.Log
enum class LoggingLevel {
VERBOSE,
DEBUG,
INFO,
WARN,
ERROR,
WTF,
OFF,
;
fun toAndroidLogPriority(): Int {
return when (this) {
VERBOSE -> Log.VERBOSE
INFO -> Log.INFO
DEBUG -> Log.DEBUG
WARN -> Log.WARN
ERROR -> Log.ERROR
WTF -> Log.ERROR
OFF -> 0
}
}
}
| 64
|
Kotlin
|
70
| 176
|
bee0a1e1e23725c77b97b2b94e3c1be3b9d12e8a
| 1,057
|
client-sdk-android
|
Apache License 2.0
|
elmslie-coroutines/src/main/java/vivid/money/elmslie/coroutines/MappingActorCompat.kt
|
vivid-money
| 328,970,240
| false
| null |
package vivid.money.elmslie.coroutines
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.onEach
import vivid.money.elmslie.core.store.MappingActor
/**
* Contains internal event mapping helpers for coroutines
*/
@Suppress("ComplexInterface", "TooManyFunctions")
interface MappingActorCompat<Event : Any> : MappingActor<Event> {
fun <T : Any> Flow<T>.mapEvents(
eventMapper: (T) -> Event? = { null },
errorMapper: (error: Throwable) -> Event? = { null }
) = mapNotNull { eventMapper(it) }
.onEach { it.logSuccessEvent() }
.catch { it.logErrorEvent(errorMapper)?.let { emit(it) } ?: throw it }
@Deprecated(
"Use mapEvents with mapping",
ReplaceWith("this.mapEvents({ successEvent }, { errorEvent })")
)
fun <T : Any> Flow<T>.mapEvents(
successEvent: Event,
errorEvent: Event
) = mapEvents({ successEvent }, { errorEvent })
@Deprecated(
"Use mapEvents with mapping",
ReplaceWith("this.mapEvents(eventMapper, { errorEvent })")
)
fun <T : Any> Flow<T>.mapEvents(
eventMapper: (T) -> Event,
errorEvent: Event
) = mapEvents(eventMapper, { errorEvent })
@Deprecated(
"Use mapEvents with mapping",
ReplaceWith("this.mapEvents { successEvent }")
)
fun <T : Any> Flow<T>.mapSuccessEvent(
successEvent: Event
) = mapEvents({ successEvent })
@Deprecated(
"Use mapEvents with mapping",
ReplaceWith("this.mapEvents(eventMapper)")
)
fun <T : Any> Flow<T>.mapSuccessEvent(
eventMapper: (T) -> Event
) = mapEvents(eventMapper)
@Deprecated(
"Use mapEvents with mapping",
ReplaceWith("this.mapEvents(errorMapper = { errorEvent })")
)
fun <T : Any> Flow<T>.mapErrorEvent(
errorEvent: Event
) = mapEvents(errorMapper = { errorEvent })
@Deprecated(
"Use mapEvents with mapping",
ReplaceWith("this.mapEvents(errorMapper = errorMapper)")
)
fun Flow<Event>.mapErrorEvent(
errorMapper: (Throwable) -> Event
) = mapEvents(errorMapper = errorMapper)
@Deprecated(
"Use mapEvents with mapping",
ReplaceWith("this.mapEvents()")
)
fun <T : Any> Flow<T>.ignoreEvents() = mapEvents()
}
| 7
|
Kotlin
|
12
| 94
|
fb50f3714da87a912e50bfe95edd6b08eb020b26
| 2,382
|
elmslie
|
Apache License 2.0
|
app/src/main/java/com/example/newsiuuu/util/Resource.kt
|
mihirdev7
| 774,907,209
| false
|
{"Kotlin": 33631}
|
package com.example.newsiuuu.util
sealed class Resource<T>(val data: T?=null, val message:String? =null)
{
class Success<T>(data: T):Resource<T>(data)
class Failure<T>(message: String, data: T?=null):Resource<T>(data,message)
class Loading<T>:Resource<T>()
}
| 0
|
Kotlin
|
0
| 1
|
b7d049477ee459e003505ceb3092615cdd634931
| 271
|
Newsiuuu
|
MIT License
|
src/main/kotlin/com/rbkmoney/porter/service/NotificationSenderService.kt
|
rbkmoney
| 377,151,676
| false
| null |
package com.rbkmoney.porter.service
import com.rbkmoney.porter.repository.entity.NotificationTemplateStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
class NotificationSenderService(
private val notificationTemplateService: NotificationTemplateService,
private val notificationService: NotificationService,
) {
@Transactional
fun sendNotification(templateId: String, partyIds: Collection<String>) {
notificationTemplateService.editNotificationTemplate(
templateId = templateId,
status = NotificationTemplateStatus.final
)
notificationService.createNotifications(templateId, partyIds)
}
@Transactional
fun sendNotificationAll(templateId: String) {
notificationTemplateService.editNotificationTemplate(
templateId = templateId,
status = NotificationTemplateStatus.final
)
notificationService.createNotifications(templateId)
}
}
| 0
|
Kotlin
|
1
| 0
|
af408a1d6cbe46a22ec56a14fb0485dcb72830f1
| 1,035
|
porter
|
Apache License 2.0
|
components/ledger/ledger-utxo-flow/src/test/kotlin/net/corda/ledger/utxo/flow/impl/flows/backchain/TransactionBackchainResolutionFlowTest.kt
|
corda
| 346,070,752
| false
| null |
package net.corda.ledger.utxo.flow.impl.flows.backchain
import net.corda.ledger.common.data.transaction.TransactionStatus
import net.corda.ledger.utxo.flow.impl.persistence.UtxoLedgerPersistenceService
import net.corda.v5.application.flows.FlowEngine
import net.corda.v5.application.messaging.FlowSession
import net.corda.v5.base.exceptions.CordaRuntimeException
import net.corda.v5.crypto.SecureHash
import net.corda.v5.ledger.utxo.StateRef
import net.corda.v5.ledger.utxo.transaction.UtxoSignedTransaction
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoInteractions
import org.mockito.kotlin.verifyNoMoreInteractions
import org.mockito.kotlin.whenever
class TransactionBackchainResolutionFlowTest {
private companion object {
val TX_ID_1 = SecureHash("SHA", byteArrayOf(2, 2, 2, 2))
val TX_ID_2 = SecureHash("SHA", byteArrayOf(3, 3, 3, 3))
val TX_ID_3 = SecureHash("SHA", byteArrayOf(4, 4, 4, 4))
val TX_2_INPUT_DEPENDENCY_STATE_REF_1 = StateRef(TX_ID_3, 0)
val TX_3_INPUT_DEPENDENCY_STATE_REF_1 = StateRef(TX_ID_3, 0)
val TX_3_INPUT_DEPENDENCY_STATE_REF_2 = StateRef(TX_ID_3, 1)
val TX_3_INPUT_REFERENCE_DEPENDENCY_STATE_REF_1 = StateRef(TX_ID_3, 0)
val TX_3_INPUT_REFERENCE_DEPENDENCY_STATE_REF_2 = StateRef(TX_ID_3, 1)
}
private val flowEngine = mock<FlowEngine>()
private val transactionBackchainVerifier = mock<TransactionBackchainVerifier>()
private val utxoLedgerPersistenceService = mock<UtxoLedgerPersistenceService>()
private val session = mock<FlowSession>()
private val transaction = mock<UtxoSignedTransaction>()
@BeforeEach
fun beforeEach() {
whenever(transaction.id).thenReturn(TX_ID_1)
whenever(transactionBackchainVerifier.verify(any(), any())).thenReturn(true)
}
@Test
fun `does nothing when the transaction has no dependencies`() {
whenever(transaction.inputStateRefs).thenReturn(emptyList())
whenever(transaction.referenceStateRefs).thenReturn(emptyList())
callTransactionBackchainResolutionFlow()
verifyNoInteractions(flowEngine)
verifyNoInteractions(transactionBackchainVerifier)
verifyNoInteractions(utxoLedgerPersistenceService)
}
@Test
fun `does nothing when the transactions dependencies are already verified`() {
whenever(transaction.inputStateRefs).thenReturn(
listOf(
TX_2_INPUT_DEPENDENCY_STATE_REF_1,
TX_3_INPUT_DEPENDENCY_STATE_REF_1,
TX_3_INPUT_DEPENDENCY_STATE_REF_2
)
)
whenever(transaction.referenceStateRefs).thenReturn(
listOf(
TX_3_INPUT_REFERENCE_DEPENDENCY_STATE_REF_1,
TX_3_INPUT_REFERENCE_DEPENDENCY_STATE_REF_2
)
)
whenever(utxoLedgerPersistenceService.find(any(), eq(TransactionStatus.VERIFIED))).thenReturn(mock())
callTransactionBackchainResolutionFlow()
verifyNoInteractions(flowEngine)
verifyNoInteractions(transactionBackchainVerifier)
}
@Test
fun `retrieves and verifies transactions dependencies that are not verified`() {
whenever(transaction.inputStateRefs).thenReturn(
listOf(
TX_2_INPUT_DEPENDENCY_STATE_REF_1,
TX_3_INPUT_DEPENDENCY_STATE_REF_1,
TX_3_INPUT_DEPENDENCY_STATE_REF_2
)
)
whenever(transaction.referenceStateRefs).thenReturn(
listOf(
TX_3_INPUT_REFERENCE_DEPENDENCY_STATE_REF_1,
TX_3_INPUT_REFERENCE_DEPENDENCY_STATE_REF_2
)
)
whenever(utxoLedgerPersistenceService.find(TX_ID_2, TransactionStatus.VERIFIED)).thenReturn(mock())
whenever(utxoLedgerPersistenceService.find(TX_ID_3, TransactionStatus.VERIFIED)).thenReturn(null)
whenever(flowEngine.subFlow(any<TransactionBackchainReceiverFlow>())).thenReturn(TopologicalSort())
callTransactionBackchainResolutionFlow()
verify(flowEngine).subFlow(TransactionBackchainReceiverFlow(TX_ID_1, setOf(TX_ID_3), session))
verifyNoMoreInteractions(flowEngine)
verify(transactionBackchainVerifier).verify(eq(TX_ID_1), any())
}
@Test
fun `throws exception when verification fails`() {
whenever(transaction.inputStateRefs).thenReturn(
listOf(
TX_2_INPUT_DEPENDENCY_STATE_REF_1,
TX_3_INPUT_DEPENDENCY_STATE_REF_1,
TX_3_INPUT_DEPENDENCY_STATE_REF_2
)
)
whenever(transaction.referenceStateRefs).thenReturn(
listOf(
TX_3_INPUT_REFERENCE_DEPENDENCY_STATE_REF_1,
TX_3_INPUT_REFERENCE_DEPENDENCY_STATE_REF_2
)
)
whenever(utxoLedgerPersistenceService.find(TX_ID_2, TransactionStatus.VERIFIED)).thenReturn(mock())
whenever(utxoLedgerPersistenceService.find(TX_ID_3, TransactionStatus.VERIFIED)).thenReturn(null)
whenever(transactionBackchainVerifier.verify(eq(TX_ID_1), any())).thenReturn(false)
whenever(flowEngine.subFlow(any<TransactionBackchainReceiverFlow>())).thenReturn(TopologicalSort())
assertThatThrownBy { callTransactionBackchainResolutionFlow() }.isExactlyInstanceOf(CordaRuntimeException::class.java)
verify(flowEngine).subFlow(TransactionBackchainReceiverFlow(TX_ID_1, setOf(TX_ID_3), session))
verifyNoMoreInteractions(flowEngine)
}
private fun callTransactionBackchainResolutionFlow() {
TransactionBackchainResolutionFlow(transaction, session).apply {
flowEngine = this@TransactionBackchainResolutionFlowTest.flowEngine
transactionBackchainVerifier = this@TransactionBackchainResolutionFlowTest.transactionBackchainVerifier
utxoLedgerPersistenceService = this@TransactionBackchainResolutionFlowTest.utxoLedgerPersistenceService
}.call()
}
}
| 82
|
Kotlin
|
7
| 24
|
17f5d2e5585a8ac56e559d1c099eaee414e6ec5a
| 6,220
|
corda-runtime-os
|
Apache License 2.0
|
src/main/kotlin/app/softwork/serviceloader/CreateServiceLoadersResourcesFileAction.kt
|
hfhbd
| 589,746,751
| false
| null |
package app.softwork.serviceloader
import org.gradle.api.file.*
import org.gradle.api.provider.*
import org.gradle.workers.*
import java.io.*
import java.net.*
internal abstract class CreateServiceLoadersResourcesFileAction :
WorkAction<CreateServiceLoadersResourcesFileAction.Parameters> {
interface Parameters : WorkParameters {
val serviceLoader: Property<String>
val implementationClasses: ListProperty<String>
val resourcesDir: DirectoryProperty
val classes: ConfigurableFileCollection
}
override fun execute() {
val classLoader = CreateServiceLoadersResourcesFileAction::class.java.classLoader
classLoader.loadClass(parameters.serviceLoader.get())
val serviceLoaderFile = File(parameters.resourcesDir.asFile.get(), parameters.serviceLoader.get())
if (!serviceLoaderFile.exists()) {
serviceLoaderFile.createNewFile()
}
val urls = parameters.classes.flatMap {
it.walk()
}.map { it.toURI().toURL() }
val classes = URLClassLoader.newInstance(urls.toTypedArray(), classLoader)
serviceLoaderFile.writeText(parameters.implementationClasses.get().joinToString("\n", postfix = "\n") {
val klass = classes.loadClass(it)
require(klass.constructors.any { it.parameterCount == 0 }) {
"Class $it has a non-zero arg public constructor."
}
it
})
}
}
| 4
|
Kotlin
|
0
| 0
|
b6afc908d74448489954741a6abb30f6f8ed9194
| 1,492
|
serviceloader-gradle-plugin
|
Apache License 2.0
|
workflix/backend/backend/src/main/kotlin/de/se/team3/webservice/handlers/ProcessesHandler.kt
|
elite-se
| 221,695,449
| false
|
{"JavaScript": 227922, "Kotlin": 209131, "HTML": 6665, "CSS": 238}
|
package de.se.team3.webservice.handlers
import de.se.team3.logic.container.ProcessContainer
import de.se.team3.logic.container.ProcessGroupsContainer
import de.se.team3.logic.container.ProcessTemplatesContainer
import de.se.team3.logic.container.UserContainer
import de.se.team3.logic.domain.Process
import de.se.team3.logic.domain.ProcessQueryPredicate
import de.se.team3.logic.domain.ProcessStatus
import de.se.team3.webservice.containerInterfaces.ProcessContainerInterface
import de.se.team3.webservice.containerInterfaces.ProcessGroupsContainerInterface
import de.se.team3.webservice.containerInterfaces.ProcessTemplateContainerInterface
import de.se.team3.webservice.containerInterfaces.UserContainerInterface
import de.se.team3.webservice.util.JsonHelper
import de.se.team3.webservice.util.PagingHelper
import io.javalin.http.Context
import org.json.JSONObject
/**
* Handles requests due to the general properties of processes.
*/
object ProcessesHandler {
private val processesContainer: ProcessContainerInterface = ProcessContainer
private val usersContainer: UserContainerInterface = UserContainer
private val processGroupsContainer: ProcessGroupsContainerInterface = ProcessGroupsContainer
private val processTemplatesContainer: ProcessTemplateContainerInterface = ProcessTemplatesContainer
/**
* Parses the selection predicate that is specified via query parameters in the request url.
*/
private fun parseSelectionPredicate(ctx: Context): ProcessQueryPredicate {
val statuses = ArrayList<ProcessStatus>()
val groupIds = ArrayList<Int>()
var involvingUserId: String? = null
for (param in ctx.queryParamMap()) {
if (param.key == "status") // loops over all query parameters named status
for (statusEntry in param.value)
statuses.add(ProcessStatus.valueOf(statusEntry))
if (param.key == "processGroupId") // loops over all query parameters named groupId
for (groupIdEntry in param.value)
groupIds.add(groupIdEntry.toInt())
if (param.key == "involving") {
if (param.value.size != 1)
ctx.status(400).result("query must not contain more than one involving parameter")
involvingUserId = param.value[0]
}
}
return ProcessQueryPredicate(statuses, groupIds, involvingUserId)
}
/**
* Handles the request for all processes.
*/
fun getAll(ctx: Context) {
try {
val predicate = parseSelectionPredicate(ctx)
val processes = processesContainer.getAllProcesses(predicate)
val pagingContainer = PagingHelper.getPagingContainer(1, 1)
val processesJsonArray = JsonHelper.toJsonArray(processes)
pagingContainer.put("processes", processesJsonArray)
ctx.result(pagingContainer.toString())
.contentType("application/json")
} catch (e: IllegalArgumentException) {
ctx.status(400).result("predicate parsing error: unknown or malformed status, group ID or user ID")
}
}
/**
* Handles the request for a single process.
*/
fun getOne(ctx: Context, processId: Int) {
val process = processesContainer.getProcess(processId)
// Building json
val processJsonObject = JsonHelper.toJsonObject(process)
val tasksJsonArray = JsonHelper.toJsonArray(process.tasks.map { it.value })
processJsonObject.put("tasks", tasksJsonArray)
ctx.result(processJsonObject.toString())
.contentType("application/json")
}
/**
* Handles the creation of a process.
*/
fun create(ctx: Context) {
val content = ctx.body()
val processJsonObject = JSONObject(content)
val starterId = processJsonObject.getString("starterId")
val processGroupId = processJsonObject.getInt("processGroupId")
val processTemplateId = processJsonObject.getInt("processTemplateId")
val title = processJsonObject.getString("title")
val description = processJsonObject.getString("description")
val deadline = JsonHelper.getInstantFromString(processJsonObject.getString("deadline"))
val starter = usersContainer.getUser(starterId)
val processGroup = processGroupsContainer.getProcessGroup(processGroupId)
val processTemplate = processTemplatesContainer.getProcessTemplate(processTemplateId)
val process = Process(starter, processGroup, processTemplate, title, description, deadline)
val newId = processesContainer.createProcess(process)
val newIdJsonObject = JSONObject()
newIdJsonObject.put("newId", newId)
ctx.result(newIdJsonObject.toString())
.contentType("application/json")
}
/**
* Handles requests for updating a process.
*/
fun update(ctx: Context, processId: Int) {
val content = ctx.body()
val processJsonObject = JSONObject(content)
val title = processJsonObject.getString("title")
val description = processJsonObject.getString("description")
val deadline = JsonHelper.getInstantFromString(processJsonObject.getString("deadline"))
processesContainer.updateProcess(processId, title, description, deadline)
}
/**
* Handles requests for aborting a process.
*
* Nevertheless the function is named delete, because of the http method used.
*/
fun delete(ctx: Context, processId: Int) {
processesContainer.abortProcess(processId)
}
}
| 7
|
JavaScript
|
0
| 1
|
c3d4bf7aea5b009f36deb7a4137df3107a8923c4
| 5,646
|
workflix
|
MIT License
|
app/src/main/java/com/hits/coded/presentation/activities/editorActivity/fragments/variableTypeChangerBottomSheet/viewModel/VariableTypeChangerViewModel.kt
|
delet-dis
| 482,704,007
| false
| null |
package com.hits.coded.presentation.activities.editorActivity.fragments.variableTypeChangerBottomSheet.viewModel
import androidx.lifecycle.ViewModel
import com.hits.coded.data.models.sharedTypes.VariableType
import com.hits.coded.data.models.typeChangerBottomSheet.dataClasses.BottomSheetTypeChangerScreen
import com.hits.coded.data.models.typeChangerBottomSheet.enums.BottomSheetTypeChangersScreens
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class VariableTypeChangerViewModel @Inject constructor() : ViewModel() {
fun getTypeChangerScreens(): Array<BottomSheetTypeChangerScreen> {
val screens = ArrayList<BottomSheetTypeChangerScreen>()
BottomSheetTypeChangersScreens.values().forEach {
screens.add(it.bottomSheetTypeChangerScreen)
}
return screens.toTypedArray()
}
fun getVariablesTypes(): Array<VariableType> = VariableType.values()
}
| 0
|
Kotlin
|
0
| 0
|
2a9d9db6d86bcd535e24e487d1720977e596bf22
| 949
|
coded.
|
MIT License
|
app/src/main/java/com/monday8am/locationstream/LocationApp.kt
|
monday8am
| 180,102,402
| false
| null |
package com.monday8am.locationstream
import android.app.Application
import android.content.Context
import com.monday8am.locationstream.data.PhotoDataRepository
import com.monday8am.locationstream.data.local.PhotoDao
import com.monday8am.locationstream.data.local.PhotosDatabase
import com.monday8am.locationstream.data.local.PreferencesHelper
import com.monday8am.locationstream.data.remote.RemoteWebService
import com.monday8am.locationstream.redux.appStateReducer
import com.monday8am.locationstream.redux.loggingMiddleware
import com.monday8am.locationstream.redux.networkMiddleware
import org.rekotlin.Store
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
val store = Store(
reducer = ::appStateReducer,
state = null,
middleware = listOf(networkMiddleware, loggingMiddleware)
)
class LocationApp: Application() {
override fun onCreate() {
super.onCreate()
instance = this
repository = PhotoDataRepository(photoDao = providePhotoDataSource(applicationContext),
webService = provideRemoteWebService(),
preferences = providePreferences(applicationContext),
scheduleProvider = AppSchedulerProvider())
}
companion object {
@get:Synchronized lateinit var instance: LocationApp
private set
var repository: PhotoDataRepository? = null
}
private fun providePreferences(context: Context): PreferencesHelper {
return PreferencesHelper(context)
}
private fun providePhotoDataSource(context: Context): PhotoDao {
val database = PhotosDatabase.getInstance(context)
return database.photoDao()
}
private fun provideRemoteWebService(): RemoteWebService {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.flickr.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
return retrofit.create<RemoteWebService>(RemoteWebService::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
e4ef28339995990a9f9dcd9b311f6aa179739d1a
| 2,231
|
locationstream
|
MIT License
|
app/src/main/java/com/example/sunkai/heritage/database/entities/Collection.kt
|
sunkaiiii
| 92,040,914
| false
|
{"Kotlin": 292444}
|
package com.example.sunkai.heritage.database.entities
import androidx.room.*
import com.example.sunkai.heritage.R
import com.example.sunkai.heritage.tools.getString
import java.util.*
@Entity
@TypeConverters(Collection.CollectionTypeConverters::class)
data class Collection(
@ColumnInfo val collectionType: CollectionType,
@ColumnInfo val key: String,
@ColumnInfo val content:String,
@ColumnInfo val imageLink:String?,
@PrimaryKey(autoGenerate = true) val id: Int? = null,
@ColumnInfo val collectDate: String = Calendar.getInstance().toString()
) {
enum class CollectionType(val value: Int,private val text:String) {
NewsDetail(0, getString(R.string.news)),
ForumsDetail(1, getString(R.string.forums)),
SpeicialListDetail(2, getString(R.string.special_topic)),
PeopleDetail(3, getString(R.string.people)),
ProjectDetail(4, getString(R.string.project_page)),
InheritatePeopleDetail(5, getString(R.string.inheritors));
fun getName() = text
}
class CollectionTypeConverters {
@TypeConverter
fun toCollectionType(value: Int) = enumValues<CollectionType>()[value]
@TypeConverter
fun fromCollectionType(value: CollectionType) = value.value
}
}
| 0
|
Kotlin
|
0
| 6
|
bda95ace70e3dc8fcc14a98431401374aec2d4ef
| 1,272
|
heritage-online-android
|
Apache License 2.0
|
app/src/main/java/com/mastercard/webintegration/request/InitRequest.kt
|
mrzeng12
| 459,325,037
| true
|
{"Kotlin": 67090, "JavaScript": 6811, "HTML": 1247}
|
/* Copyright © 2022 Mastercard. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
=============================================================================*/
package com.mastercard.webintegration.request
import com.google.gson.annotations.SerializedName
/**
* Create an instance of this class with client specifications to invoke init API call.
*/
class InitRequest {
@field:SerializedName("cardBrands")
var cardBrands: MutableSet<String>? = null
@field:SerializedName("srcDpaId")
var srcDpaId: String? = null
@field:SerializedName("dpaTransactionOptions")
var dpaTransactionOptions: DpaTransactionOptions? = null
@field:SerializedName("dpaData")
var dpaData: DpaData? = null
}
class DpaData(
@field:SerializedName("dpaPresentationName")
val dpaPresentationName: String? = null,
@field:SerializedName("dpaName")
val dpaName: String? = null
)
class DpaTransactionOptions(
@field:SerializedName("dpaAcceptedShippingCountries")
val dpaAcceptedShippingCountries: List<Any?>? = null,
@field:SerializedName("consumerEmailAddressRequested")
val consumerEmailAddressRequested: Boolean? = null,
@field:SerializedName("threeDsPreference")
val threeDsPreference: String? = null,
@field:SerializedName("dpaShippingPreference")
val dpaShippingPreference: String? = null,
@field:SerializedName("consumerNameRequested")
val consumerNameRequested: Boolean? = null,
@field:SerializedName("paymentOptions")
val paymentOptions: List<PaymentOptionsItem?>? = null,
@field:SerializedName("consumerPhoneNumberRequested")
val consumerPhoneNumberRequested: Boolean? = null,
@field:SerializedName("transactionAmount")
val transactionAmount: TransactionAmount? = null,
@field:SerializedName("dpaAcceptedBillingCountries")
val dpaAcceptedBillingCountries: List<Any?>? = null,
@field:SerializedName("dpaLocale")
val dpaLocale: String? = null,
@field:SerializedName("dpaBillingPreference")
val dpaBillingPreference: String? = null
)
class PaymentOptionsItem(
@field:SerializedName("dynamicDataType")
val dynamicDataType: String? = null,
@field:SerializedName("dpaDynamicDataTtlMinutes")
val dpaDynamicDataTtlMinutes: Int? = null
)
class TransactionAmount(
@field:SerializedName("transactionAmount")
val transactionAmount: Int? = null,
@field:SerializedName("transactionCurrencyCode")
val transactionCurrencyCode: String? = null
)
| 0
| null |
0
| 1
|
085de288395c81de10255fa6f7c37bd1baf3666c
| 2,946
|
web-native-integration
|
Apache License 2.0
|
app/src/main/java/com/jim/moviecritics/report/ReportDialog.kt
|
MIN-JING
| 503,330,525
| false
|
{"Kotlin": 286084}
|
package com.jim.moviecritics.report
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.jim.moviecritics.R
import com.jim.moviecritics.databinding.DialogReportBinding
import com.jim.moviecritics.ext.getVmFactory
import com.jim.moviecritics.ext.showToast
import com.jim.moviecritics.util.Logger
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class ReportDialog : AppCompatDialogFragment() {
private val viewModel by viewModels<ReportViewModel> {
getVmFactory(ReportDialogArgs.fromBundle(requireArguments()).comment)
}
private lateinit var binding: DialogReportBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ***** Let layout showing match constraint *****
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.ReportDialog)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
binding = DialogReportBinding.inflate(inflater, container, false)
binding.layoutReport.startAnimation(
AnimationUtils.loadAnimation(context, R.anim.anim_slide_up)
)
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
viewModel.leave.observe(viewLifecycleOwner) {
it?.let {
dismiss()
viewModel.onLeaveCompleted()
}
}
viewModel.invalidReport.observe(viewLifecycleOwner) {
Logger.i("Report invalidReport = $it")
it?.let {
when (it) {
ReportViewModel.INVALID_FORMAT_REASON_EMPTY -> {
activity.showToast(
"The reason of the report was empty, please try choice again."
)
}
ReportViewModel.INVALID_FORMAT_MESSAGE_EMPTY -> {
activity.showToast(
"The message of the report was empty, please try key-in again."
)
}
ReportViewModel.NO_ONE_KNOWS -> {
Logger.i("Unknown invalidReport value NO_ONE_KNOWS = $it")
}
}
}
}
return binding.root
}
override fun dismiss() {
binding.layoutReport.startAnimation(
AnimationUtils.loadAnimation(context, R.anim.anim_slide_down)
)
lifecycleScope.launch {
delay(200)
super.dismiss()
viewModel.onLeaveCompleted()
}
}
}
| 1
|
Kotlin
|
0
| 0
|
69587c4d556200a5df47d75c81fd6810ad0815a2
| 2,963
|
MovieCritics
|
Apache License 2.0
|
android/src/main/kotlin/software/handmade/flutter/flutter_siri_suggestions/FlutterSiriSuggestionsPlugin.kt
|
myriky
| 205,199,285
| false
| null |
package software.handmade.flutter.flutter_siri_suggestions
import android.util.Log
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
/** FlutterSiriSuggestionsPlugin */
class FlutterSiriSuggestionsPlugin: FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel : MethodChannel
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_siri_suggestions")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "becomeCurrent" || call.method == "deleteAllSavedUserActivities" || call.method == "deleteSavedUserActivitiesWithPersistentIdentifier" || call.method == "deleteSavedUserActivitiesWithPersistentIdentifiers") {
Log.d("siri_suggestion", "Not support ANDROID!");
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}
| 10
|
Dart
|
14
| 15
|
cd47a623ef53daf7d656ce402891c1c94536147a
| 1,593
|
flutter_siri_suggestions
|
MIT License
|
src/test/kotlin/no/skatteetaten/aurora/gillis/service/AbstractOpenShiftServerTest.kt
|
Skatteetaten
| 135,263,007
| false
|
{"Kotlin": 26109, "Shell": 428}
|
package no.skatteetaten.aurora.gillis.service
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.TestInstance
import no.skatteetaten.aurora.kubernetes.HttpClientTimeoutConfiguration
import no.skatteetaten.aurora.kubernetes.KubernetesConfiguration
import no.skatteetaten.aurora.kubernetes.RetryConfiguration
import no.skatteetaten.aurora.mockmvc.extensions.mockwebserver.url
import okhttp3.mockwebserver.MockWebServer
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
open class AbstractOpenShiftServerTest {
protected val mockServer = MockWebServer()
private val config = KubernetesConfiguration(
retry = RetryConfiguration(0),
timeout = HttpClientTimeoutConfiguration(),
url = mockServer.url
)
protected var mockClient = config.createTestClient("abc")
@AfterEach
fun tearDown() {
mockServer.shutdown()
}
}
| 0
|
Kotlin
|
0
| 0
|
fe3747a8dbc45fc0796e8cabed176d88df8a3453
| 889
|
gillis
|
Apache License 2.0
|
IPassPlusSdk/src/main/java/com/sdk/ipassplussdk/model/response/ceon/PostCeon/Foursquare.kt
|
yazanalqasem
| 808,584,767
| false
|
{"Kotlin": 308101, "Java": 4759}
|
package com.sdk.ipassplussdk.model.response.ceon.GetCeon
data class Foursquare(
val bio: Any,
val photo: Any,
val profile_url: Any,
val registered: Any
)
| 0
|
Kotlin
|
0
| 0
|
1fc3247607811f7f52e1d401c252b82e2c98c3a8
| 170
|
iPass2.0NativeAndroidSDK
|
Apple MIT License
|
feature/home/src/main/java/soup/movie/feature/home/HomeViewModel.kt
|
Moop-App
| 113,048,795
| false
|
{"Kotlin": 561399}
|
/*
* 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.feature.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import soup.movie.core.analytics.EventAnalytics
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val analytics: EventAnalytics,
) : ViewModel() {
private val _selectedMainTab = MutableStateFlow(MainTabUiModel.Home)
val selectedMainTab: StateFlow<MainTabUiModel> = _selectedMainTab
private val _selectedHomeTab = MutableStateFlow(HomeTabUiModel.Now)
val selectedHomeTab: StateFlow<HomeTabUiModel> = _selectedHomeTab
fun onMainTabSelected(mainTab: MainTabUiModel) {
viewModelScope.launch {
_selectedMainTab.emit(mainTab)
}
}
fun onHomeTabSelected(homeTab: HomeTabUiModel) {
viewModelScope.launch {
_selectedHomeTab.emit(homeTab)
}
}
fun onMovieClick() {
analytics.clickMovie()
}
fun onFilterButtonClick() {
analytics.clickMenuFilter()
}
}
| 4
|
Kotlin
|
17
| 165
|
e4654f8c761e3b113929d66d45c1846a1e24e1f2
| 1,782
|
Moop-Android
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/ru/slartus/boostbuddy/ui/screens/post/PostScreen.kt
|
slartus
| 767,913,639
| false
|
{"Kotlin": 299148, "Swift": 1264}
|
package ru.slartus.boostbuddy.ui.screens.post
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.arkivanov.decompose.extensions.compose.jetbrains.subscribeAsState
import com.seiko.imageloader.rememberImagePainter
import kotlinx.collections.immutable.ImmutableList
import ru.slartus.boostbuddy.components.post.PostComponent
import ru.slartus.boostbuddy.components.post.PostViewItem
import ru.slartus.boostbuddy.components.post.PostViewState
import ru.slartus.boostbuddy.data.repositories.comments.models.Comment
import ru.slartus.boostbuddy.data.repositories.models.Content
import ru.slartus.boostbuddy.data.repositories.models.Poll
import ru.slartus.boostbuddy.data.repositories.models.PollOption
import ru.slartus.boostbuddy.data.repositories.models.Post
import ru.slartus.boostbuddy.ui.common.HorizontalSpacer
import ru.slartus.boostbuddy.ui.common.VerticalSpacer
import ru.slartus.boostbuddy.ui.screens.blog.ContentView
import ru.slartus.boostbuddy.ui.screens.blog.FocusableBox
import ru.slartus.boostbuddy.ui.screens.blog.PostView
import ru.slartus.boostbuddy.ui.screens.blog.VideoTypeDialogView
import ru.slartus.boostbuddy.ui.widgets.ErrorView
import ru.slartus.boostbuddy.ui.widgets.LoaderView
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun PostScreen(component: PostComponent) {
val state by component.viewStates.subscribeAsState()
Scaffold(
topBar = {
TopAppBar(
title = { Text(state.post.title) },
navigationIcon = {
IconButton(onClick = {
component.onBackClicked()
}) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = "Назад"
)
}
}
)
},
) { innerPadding ->
Box(
modifier = Modifier.fillMaxSize().padding(innerPadding),
contentAlignment = Alignment.Center
) {
when (val progressState = state.progressProgressState) {
is PostViewState.ProgressState.Error -> ErrorView(
message = progressState.description,
onRepeatClick = {
component.onRepeatClicked()
}
)
PostViewState.ProgressState.Init,
PostViewState.ProgressState.Loading -> LoaderView()
is PostViewState.ProgressState.Loaded ->
if (state.items.isEmpty())
EmptyCommentsView()
else
FullPostView(
post = state.post,
items = state.items,
onMoreClick = {
component.onMoreCommentsClicked()
},
onMoreRepliesClick = {
component.onMoreRepliesClicked(it)
},
onVideoClick = {
component.onVideoItemClicked(state.post.id, it)
},
onPollOptionClick = { poll, option ->
component.onPollOptionClicked(poll, option)
},
onVoteClick = { component.onVoteClicked(it) },
onDeleteVoteClick = { component.onDeleteVoteClicked(it) }
)
}
}
}
val dialogSlot by component.dialogSlot.subscribeAsState()
dialogSlot.child?.instance?.also { videoTypeComponent ->
VideoTypeDialogView(
modifier = Modifier,
component = videoTypeComponent,
)
}
}
@Composable
private fun FullPostView(
post: Post,
items: ImmutableList<PostViewItem>,
onMoreClick: () -> Unit,
onMoreRepliesClick: (PostViewItem.CommentItem) -> Unit,
onVideoClick: (okVideoData: Content.OkVideo) -> Unit,
onPollOptionClick: (Poll, PollOption) -> Unit,
onVoteClick: (poll: Poll) -> Unit,
onDeleteVoteClick: (poll: Poll) -> Unit
) {
val state = rememberLazyListState(initialFirstVisibleItemIndex = 1)
LazyColumn(modifier = Modifier.fillMaxSize(), state = state) {
item(contentType = "post", key = "post_${post.id}") {
PostView(
post = post,
onVideoClick = onVideoClick,
onCommentsClick = {},
onPollOptionClick = onPollOptionClick,
onVoteClick = onVoteClick,
onDeleteVoteClick = onDeleteVoteClick
)
}
commentsView(items, onMoreClick, onMoreRepliesClick)
}
}
@Composable
private fun EmptyCommentsView() {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
text = "Список комментариев пуст",
style = MaterialTheme.typography.bodyMedium
)
}
}
private fun LazyListScope.commentsView(
items: ImmutableList<PostViewItem>,
onMoreClick: () -> Unit,
onMoreRepliesClick: (PostViewItem.CommentItem) -> Unit
) {
items(
items = items,
key = { it.id },
contentType = {
when (it) {
is PostViewItem.CommentItem -> "CommentItem"
PostViewItem.ErrorMore -> "ErrorMore"
PostViewItem.LoadMore -> "LoadMore"
PostViewItem.LoadingMore -> "LoadingMore"
}
}
) { commentItem ->
when (commentItem) {
is PostViewItem.CommentItem -> {
CommentView(
commentItem.comment,
onMoreRepliesClick = { onMoreRepliesClick(commentItem) })
VerticalSpacer(8.dp)
}
PostViewItem.ErrorMore -> FocusableBox(Modifier.fillMaxWidth()) {
Box(Modifier.clickable { onMoreClick() }.padding(8.dp)) {
Text(
text = "Ошибка загрузки. Нажми для повтора",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error
)
}
}
PostViewItem.LoadMore -> FocusableBox(Modifier.fillMaxWidth()) {
Box(Modifier.clickable { onMoreClick() }.padding(8.dp)) {
Text(
text = "Показать ещё комментарии",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.tertiary
)
}
}
PostViewItem.LoadingMore -> FocusableBox(Modifier.fillMaxWidth()) {
Box(Modifier.padding(8.dp)) {
Text(
text = "Загрузка",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.tertiary
)
}
}
}
}
}
@Composable
private fun CommentView(
comment: Comment,
isReply: Boolean = false,
onMoreRepliesClick: () -> Unit
) {
Row(
Modifier
.background(MaterialTheme.colorScheme.onPrimary)
.padding(8.dp)
) {
if (!comment.author.avatarUrl.isNullOrEmpty()) {
Image(
modifier = Modifier
.size(if (isReply) 36.dp else 48.dp)
.clip(CircleShape),
painter = rememberImagePainter(comment.author.avatarUrl),
contentDescription = "avatar",
contentScale = ContentScale.Fit
)
} else {
Icon(
modifier = Modifier
.size(if (isReply) 36.dp else 48.dp)
.clip(CircleShape),
imageVector = Icons.Default.Person,
tint = MaterialTheme.colorScheme.primary,
contentDescription = "empty avatar"
)
}
HorizontalSpacer(8.dp)
Column {
Text(
modifier = Modifier.fillMaxWidth(),
text = comment.author.name,
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.labelMedium
)
VerticalSpacer(4.dp)
comment.content.forEach { postData ->
ContentView("", postData, {})
}
Text(
modifier = Modifier.fillMaxWidth(),
text = comment.createdAtText,
style = MaterialTheme.typography.bodySmall
)
if (comment.replies.hasMore) {
FocusableBox(Modifier.fillMaxWidth()) {
Box(Modifier.clickable { onMoreRepliesClick() }.padding(8.dp)) {
Text(
text = "ещё ответы",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.tertiary
)
}
}
}
comment.replies.comments.forEach { reply ->
CommentView(reply, isReply = true, onMoreRepliesClick = {})
}
}
}
}
| 0
|
Kotlin
|
2
| 11
|
5d5c65497c094bf2a213be34bd3c346a6afa53a0
| 10,961
|
BoostBuddy
|
Apache License 2.0
|
build-logic/project/wasi-testsuite-codegen/src/main/kotlin/generator/ClassNames.kt
|
illarionov
| 848,247,126
| false
|
{"Kotlin": 1306808, "ANTLR": 6038, "TypeScript": 3148, "CSS": 1042, "FreeMarker": 450, "JavaScript": 89}
|
/*
* Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package at.released.weh.gradle.wasi.testsuite.codegen.generator
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.MemberName
import com.squareup.kotlinpoet.asClassName
internal object ClassNames {
const val ROOT_PACKAGE: String = "at.released.weh.wasi.bindings.test"
val WASI_TEST_SUITE_BASE_TEST = ClassName(ROOT_PACKAGE, "WasiTestSuiteBaseTest")
val WASI_TESTS_TESTSUITE_ROOT = MemberName(
"at.released.weh.wasi.bindings.test.ext",
"wasiTestsuiteRoot",
)
val RUNTIME_TEST_EXECUTOR = ClassName("$ROOT_PACKAGE.runner", "RuntimeTestExecutor")
val RUNTIME_TEST_EXECUTOR_FACTORY = RUNTIME_TEST_EXECUTOR.nestedClass("Factory")
object KotlinJvm {
val JVM_STATIC = JvmStatic::class.asClassName()
}
object KotlinxIo {
val KOTLINX_PATH = ClassName("kotlinx.io.files", "Path")
}
object KotlinTest {
val KOTLIN_TEST = ClassName("kotlin.test", "Test")
val KOTLIN_IGNORE = ClassName("kotlin.test", "Ignore")
}
object JunitTest {
val BEFORE_CLASS = ClassName("org.junit", "BeforeClass")
val AFTER_CLASS = ClassName("org.junit", "AfterClass")
}
}
| 0
|
Kotlin
|
0
| 4
|
8cb136a17cbece15d9e2b0cc9286f35613a149a4
| 1,451
|
wasi-emscripten-host
|
Apache License 2.0
|
intellij-plugin/src/main/kotlin/com/boolerules/prl/plugin/language/PrlElements.kt
|
booleworks
| 721,827,334
| false
|
{"Kotlin": 1495831, "JavaScript": 835976, "Vue": 132739, "TypeScript": 50565, "Java": 32652, "ANTLR": 15836, "Lex": 3646, "CSS": 2243, "Shell": 1735, "Dockerfile": 681, "Scheme": 505}
|
package com.boolerules.prl.plugin.language
import com.boolerules.prl.plugin.psi.FeatureDef
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
interface FeatureOrGroupDefinition: PsiElement {
fun getFeatureDef(): FeatureDef
}
interface PrlNamedElement : PsiNameIdentifierOwner
interface PrlReference : PsiReference, PsiElement
| 0
|
Kotlin
|
0
| 1
|
5c7d858a5358adfa0ce3c274bb74eb6b181f5949
| 494
|
boolerules
|
MIT License
|
src/main/kotlin/com/lvlifeng/jenkinshelper/helper/LogHelper.kt
|
itisokey
| 489,407,876
| false
| null |
package com.lvlifeng.jenkinshelper.helper
import cn.hutool.core.date.DateUtil
import com.lvlifeng.jenkinshelper.Bundle
import com.lvlifeng.jenkinshelper.bean.FontAttrib
import javax.swing.JTextPane
/**
*
*
* @author <NAME>
* @date 2022-05-14 22:46
*/
class LogHelper {
companion object {
fun append(textPane: JTextPane, log: String) {
val doc = textPane.styledDocument
var attr = FontAttrib(DateUtil.now() + " " + log + Bundle.message("newLine"))
attr?.let {
doc.insertString(doc.length, attr.text, attr.getSattrSet())
textPane.caretPosition = doc.length
}
}
}
}
| 1
|
Kotlin
|
0
| 2
|
32a95d848cb972ecdcdf1ebfac559173d95babd2
| 675
|
jenkinshelper
|
Apache License 2.0
|
AcornUiCore/src/com/acornui/component/ItemRenderer.kt
|
konsoletyper
| 105,533,124
| false
| null |
package com.acornui.component
interface ItemRendererRo<out E> {
/**
* The data this item renderer represents.
*/
val data: E?
}
interface ItemRenderer<E> : ItemRendererRo<E> {
/**
* The data this item renderer represents.
*/
override var data: E?
}
| 0
|
Kotlin
|
3
| 0
|
a84b559fe1d1cad01eb9223ad9af73b4d5fb5bc8
| 264
|
Acorn
|
Apache License 2.0
|
app/src/main/java/com/kirakishou/photoexchange/di/component/fregment/GalleryFragmentComponent.kt
|
K1rakishou
| 109,590,033
| false
| null |
package com.kirakishou.photoexchange.di.component.fregment
import com.kirakishou.photoexchange.di.module.fragment.GalleryFragmentModule
import com.kirakishou.photoexchange.di.scope.PerFragment
import com.kirakishou.photoexchange.ui.fragment.GalleryFragment
import dagger.Subcomponent
@PerFragment
@Subcomponent(modules = [
GalleryFragmentModule::class
])
interface GalleryFragmentComponent {
fun inject(fragment: GalleryFragment)
}
| 0
|
Kotlin
|
1
| 4
|
15f67029376a98353a01b5523dfb42d183a26bf2
| 437
|
photoexchange-android
|
Do What The F*ck You Want To Public License
|
feature-location/src/main/java/de/niklasbednarczyk/nbweather/feature/location/cards/models/overview/LocationCardOverviewAlertModel.kt
|
NiklasBednarczyk
| 529,683,941
| false
| null |
package de.niklasbednarczyk.nbweather.feature.location.cards.models.overview
import de.niklasbednarczyk.nbweather.core.common.string.NBString
import de.niklasbednarczyk.nbweather.core.ui.R
import de.niklasbednarczyk.nbweather.data.onecall.models.NationalWeatherAlertModelData
data class LocationCardOverviewAlertModel(
val text: NBString?,
val moreAlerts: NBString?
) {
companion object {
fun from(
alerts: List<NationalWeatherAlertModelData>
): LocationCardOverviewAlertModel? {
val size = alerts.size
val text = alerts.firstOrNull()?.eventName ?: return null
return when (size) {
0 -> null
1 -> LocationCardOverviewAlertModel(
text = text,
moreAlerts = null,
)
else -> {
val moreAlertsNo = size - 1
val moreAlerts = NBString.Resource(
R.string.format_plus_prefix,
moreAlertsNo
)
LocationCardOverviewAlertModel(
text = text,
moreAlerts = moreAlerts
)
}
}
}
}
}
| 22
|
Kotlin
|
0
| 0
|
b2d94e99336b908a48e784febda56a4750039cb2
| 1,283
|
NBWeather
|
MIT License
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/alexa/ask/CfnSkillOverridesPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 70198112}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.alexa.ask
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import io.cloudshiftdev.awscdkdsl.common.MapBuilder
import kotlin.Any
import kotlin.Unit
import software.amazon.awscdk.alexa.ask.CfnSkill
/**
* The `Overrides` property type provides overrides to the skill package to apply when creating or
* updating the skill.
*
* Values provided here do not modify the contents of the original skill package. Currently, only
* overriding values inside of the skill manifest component of the package is supported.
*
* `Overrides` is a property of the `Alexa::ASK::Skill SkillPackage` property type.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.alexa.ask.*;
* Object manifest;
* OverridesProperty overridesProperty = OverridesProperty.builder()
* .manifest(manifest)
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ask-skill-overrides.html)
*/
@CdkDslMarker
public class CfnSkillOverridesPropertyDsl {
private val cdkBuilder: CfnSkill.OverridesProperty.Builder =
CfnSkill.OverridesProperty.builder()
/**
* @param manifest Overrides to apply to the skill manifest inside of the skill package. The
* skill manifest contains metadata about the skill. For more information, see .
*/
public fun manifest(manifest: MapBuilder.() -> Unit = {}) {
val builder = MapBuilder()
builder.apply(manifest)
cdkBuilder.manifest(builder.map)
}
/**
* @param manifest Overrides to apply to the skill manifest inside of the skill package. The
* skill manifest contains metadata about the skill. For more information, see .
*/
public fun manifest(manifest: Any) {
cdkBuilder.manifest(manifest)
}
public fun build(): CfnSkill.OverridesProperty = cdkBuilder.build()
}
| 4
|
Kotlin
|
0
| 3
|
256ad92aebe2bcf9a4160089a02c76809dbbedba
| 2,221
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
data/src/main/java/com/pthw/data/feature/splashimage/datasource/SpPhotoNetworkDSource.kt
|
PhyoThihaWin
| 551,899,842
| false
|
{"Kotlin": 328147, "Java": 3279}
|
package com.pthw.data.feature.splashimage.datasource
import androidx.paging.PagingData
import com.pthw.data.feature.splashimage.entity.SplashPhotoEntity
import kotlinx.coroutines.flow.Flow
interface SpPhotoNetworkDSource {
fun getSearchResults(query: String): Flow<PagingData<SplashPhotoEntity>>
}
| 1
|
Kotlin
|
1
| 4
|
f64626fb6e101659693ac76d8d9ca5489ac9e821
| 304
|
MyPagingThree
|
Apache License 2.0
|
src/main/problem2/solution.kt
|
lorenzo-piersante
| 515,177,846
| false
|
{"Kotlin": 15798, "Java": 4893}
|
package problem2
import java.util.Scanner
fun sumEvenFibonacciNumber(input : Long) : Long {
val sequence = arrayListOf<Long>()
sequence.add(0, 1)
sequence.add(1, 1)
for (j in 2 until 10000) {
val element = sequence[j-2] + sequence[j-1]
if (element > input - 1) break
sequence.add(j, element)
}
var sum = 0L
for (element in sequence) {
if (element % 2 == 0L) sum += element
}
return sum
}
/**
* This solution is passing hackerrank tests, but it is an O(n) solution
* I am not sure if we can do better
*/
fun main() {
val sc = Scanner(System.`in`)
val numberOfInputs = sc.nextInt()
for (i in 0 until numberOfInputs) {
val input : Long = sc.nextLong()
val result = sumEvenFibonacciNumber(input)
println(result)
}
}
| 0
|
Kotlin
|
0
| 0
|
6159bb49cdfe94310a34edad138de2998352f1c2
| 836
|
HackerRank-ProjectEuler
|
MIT License
|
buildSrc/src/main/kotlin/Libs.kt
|
aig787
| 320,055,206
| true
|
{"Kotlin": 103776, "Dockerfile": 834}
|
object Libs {
const val kotlinLogging = "io.github.microutils:kotlin-logging:${Versions.kotlinLogging}"
const val kotlinCoroutinesCore = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.kotlinCoroutines}"
const val kotlinSerializationJson =
"org.jetbrains.kotlinx:kotlinx-serialization-json:${Versions.kotlinSerialization}"
const val kotlinSerializationCore =
"org.jetbrains.kotlinx:kotlinx-serialization-core:${Versions.kotlinSerialization}"
const val kotlinStdLib = "stdlib-jdk8"
const val awaitility = "org.awaitility:awaitility:${Versions.awaitility}"
const val hamkrest = "com.natpryce:hamkrest:${Versions.hamkrest}"
const val config4k = "io.github.config4k:config4k:${Versions.config4k}"
const val mapdb = "org.mapdb:mapdb:${Versions.mapdb}"
const val logbackCore = "ch.qos.logback:logback-core:${Versions.logback}"
const val logbackClassic = "ch.qos.logback:logback-classic:${Versions.logback}"
const val cloudbeesSyslog = "com.cloudbees:syslog-java-client:${Versions.cloudbeesSyslog}"
const val jug = "com.fasterxml.uuid:java-uuid-generator:${Versions.jug}"
const val ktorServerCore = "io.ktor:ktor-server-core:${Versions.ktor}"
const val ktorServerNetty = "io.ktor:ktor-server-netty:${Versions.ktor}"
const val ktorServerSerialization = "io.ktor:ktor-serialization:${Versions.ktor}"
const val ktorClientCore = "io.ktor:ktor-client-core:${Versions.ktor}"
const val ktorClientCIO = "io.ktor:ktor-client-cio:${Versions.ktor}"
const val mockk = "io.mockk:mockk:${Versions.mockk}"
const val kafkaClient = "org.apache.kafka:kafka-clients:${Versions.kafka}"
const val junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${Versions.junit}"
const val junitJupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${Versions.junit}"
const val junitJupiterParams = "org.junit.jupiter:junit-jupiter-params:${Versions.junit}"
const val kafkaTestContainers = "org.testcontainers:kafka:1.15.1"
const val commonsValidator = "commons-validator:commons-validator:${Versions.commonsValidator}"
val logging = listOf(
logbackCore, logbackClassic, kotlinLogging
)
}
| 3
|
Kotlin
|
0
| 0
|
9c8b4c18d7c83e839af863c75e59456079d1e1e2
| 2,197
|
feeds
|
MIT License
|
pinlog/src/main/java/com/adityaamolbavadekar/pinlog/database/ApplicationLogModel.kt
|
AdityaBavadekar
| 493,995,960
| false
|
{"Kotlin": 165624}
|
package com.adityaamolbavadekar.pinlog.database
data class ApplicationLogModel(val id: Int, var LOG: String, var LOG_LEVEL: Int)
| 0
|
Kotlin
|
0
| 1
|
6e3acd07fc0a192f77cac40b34ecedc00027d667
| 129
|
WaveAssistant
|
Apache License 2.0
|
kodein-db/src/commonMain/kotlin/com/bselzer/ktx/kodein/db/transaction/TransactionManager.kt
|
Woody230
| 388,189,330
| false
| null |
package com.bselzer.ktx.kodein.db.transaction
interface TransactionManager {
/**
* Executes the [block] within a transaction and returns its result.
*
* @param R the type of result
* @return the result of the [block]
*/
suspend fun <R> transaction(block: suspend DBTransaction.() -> R): R
/**
* Executes the [block] within a transaction with the lock and returns its result.
*
* @param R the type of result
* @return the result of the [block]
*/
suspend fun <R> lockedTransaction(block: suspend DBTransaction.() -> R): R
}
| 1
|
Kotlin
|
0
| 0
|
707e2e20c0765ab40b5951acedbb28783c4af312
| 590
|
KotlinExtensions
|
Apache License 2.0
|
app/src/main/java/com/erkindilekci/disneyanimations/domain/repository/DisneyRepository.kt
|
erkindilekci
| 645,189,286
| false
| null |
package com.erkindilekci.disneyanimations.domain.repository
import com.erkindilekci.disneyanimations.domain.model.Animation
import com.erkindilekci.disneyanimations.util.Resource
import kotlinx.coroutines.flow.Flow
interface DisneyRepository {
fun getAllAnimations(): Flow<Resource<List<Animation>>>
fun getSelectedAnimation(id: Int): Flow<Resource<Animation>>
}
| 0
|
Kotlin
|
0
| 0
|
f2f5b9c06c93705f2a0c25a753709ee2e391d089
| 374
|
DisneyAnimations
|
Apache License 2.0
|
app/src/main/java/com/g/pocketmal/domain/exception/EmptyResponseException.kt
|
glodanif
| 847,288,195
| false
|
{"Kotlin": 517413, "Java": 112995}
|
package com.g.pocketmal.domain.exception
class EmptyResponseException(message: String) : Exception(message)
| 0
|
Kotlin
|
1
| 8
|
1a7fe52c2dc59dd3bf4eaeb3d9bb64d469e10845
| 108
|
Pocket_MAL
|
MIT License
|
app/src/main/java/com/example/flixster_plus_/MovieResponse.kt
|
kcowley-21
| 728,014,424
| false
|
{"Kotlin": 5434}
|
package com.example.flixster_plus_
data class MovieResponse(val results: List<Movie>)
| 0
|
Kotlin
|
0
| 0
|
c805bb2796892cf3073bcaa3bc6997730bd13100
| 87
|
FLIXSTER_PLUS_
|
Apache License 2.0
|
app/src/main/java/com/example/starwarsapp/api/RetrofitImp.kt
|
Malekel3alamy
| 838,358,498
| false
|
{"Kotlin": 34588}
|
package com.example.starwarsapp.api
import com.example.starwarsapp.utils.Constants.Companion.BASE_URL
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
class RetrofitImp() {
companion object{
private val retrofit by lazy {
val logging = HttpLoggingInterceptor()
logging.setLevel(HttpLoggingInterceptor.Level.BODY)
val client = OkHttpClient.Builder()
.addInterceptor(logging)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.connectTimeout(10,TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build()
Retrofit.Builder()
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build()
}
val api = retrofit.create(StarWarsApi::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
6abc92dca85fa61040d5635ef71e99d30e7864e5
| 992
|
StarWarsApp
|
MIT License
|
feature/welcome/api/src/main/java/com/turtleteam/api/navigation/WelcomeNavigation.kt
|
Egor-Liadsky
| 711,194,733
| false
|
{"Kotlin": 198296}
|
package com.turtleteam.api.navigation
import com.turtleteam.core_navigation.NavigationApi
interface WelcomeNavigation : NavigationApi {
val baseRoute: String
}
| 0
|
Kotlin
|
0
| 0
|
b2dbf01030499d0e69653f7bcb4873e5407f8513
| 167
|
TurtleAppAndroid
|
Apache License 2.0
|
app/src/main/java/com/test/newsapp/presentation/MainActivity.kt
|
zenwist21
| 677,946,151
| false
| null |
package com.test.newsapp.presentation
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.test.newsapp.R
import com.test.newsapp.databinding.ActivityMainBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}
| 0
|
Kotlin
|
0
| 0
|
9a3f7c0bfce7ecf796ad3fdddf5520903904f2e8
| 770
|
NewsApp
|
MIT License
|
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Calendar2.kt
|
Tlaster
| 560,394,734
| false
|
{"Kotlin": 25133302}
|
package moe.tlaster.icons.vuesax.vuesaxicons.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
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 moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup
public val BoldGroup.Calendar2: ImageVector
get() {
if (_calendar2 != null) {
return _calendar2!!
}
_calendar2 = Builder(name = "Calendar2", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.7502f, 3.56f)
verticalLineTo(2.0f)
curveTo(16.7502f, 1.59f, 16.4102f, 1.25f, 16.0002f, 1.25f)
curveTo(15.5902f, 1.25f, 15.2502f, 1.59f, 15.2502f, 2.0f)
verticalLineTo(3.5f)
horizontalLineTo(8.7502f)
verticalLineTo(2.0f)
curveTo(8.7502f, 1.59f, 8.4102f, 1.25f, 8.0002f, 1.25f)
curveTo(7.5902f, 1.25f, 7.2502f, 1.59f, 7.2502f, 2.0f)
verticalLineTo(3.56f)
curveTo(4.5502f, 3.81f, 3.2402f, 5.42f, 3.0402f, 7.81f)
curveTo(3.0202f, 8.1f, 3.2602f, 8.34f, 3.5402f, 8.34f)
horizontalLineTo(20.4602f)
curveTo(20.7502f, 8.34f, 20.9902f, 8.09f, 20.9602f, 7.81f)
curveTo(20.7602f, 5.42f, 19.4502f, 3.81f, 16.7502f, 3.56f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(20.0f, 9.8398f)
horizontalLineTo(4.0f)
curveTo(3.45f, 9.8398f, 3.0f, 10.2898f, 3.0f, 10.8398f)
verticalLineTo(16.9998f)
curveTo(3.0f, 19.9998f, 4.5f, 21.9998f, 8.0f, 21.9998f)
horizontalLineTo(16.0f)
curveTo(19.5f, 21.9998f, 21.0f, 19.9998f, 21.0f, 16.9998f)
verticalLineTo(10.8398f)
curveTo(21.0f, 10.2898f, 20.55f, 9.8398f, 20.0f, 9.8398f)
close()
moveTo(9.21f, 18.2098f)
curveTo(9.11f, 18.2998f, 9.0f, 18.3698f, 8.88f, 18.4198f)
curveTo(8.76f, 18.4698f, 8.63f, 18.4998f, 8.5f, 18.4998f)
curveTo(8.37f, 18.4998f, 8.24f, 18.4698f, 8.12f, 18.4198f)
curveTo(8.0f, 18.3698f, 7.89f, 18.2998f, 7.79f, 18.2098f)
curveTo(7.61f, 18.0198f, 7.5f, 17.7598f, 7.5f, 17.4998f)
curveTo(7.5f, 17.2398f, 7.61f, 16.9798f, 7.79f, 16.7898f)
curveTo(7.89f, 16.6998f, 8.0f, 16.6298f, 8.12f, 16.5798f)
curveTo(8.36f, 16.4798f, 8.64f, 16.4798f, 8.88f, 16.5798f)
curveTo(9.0f, 16.6298f, 9.11f, 16.6998f, 9.21f, 16.7898f)
curveTo(9.39f, 16.9798f, 9.5f, 17.2398f, 9.5f, 17.4998f)
curveTo(9.5f, 17.7598f, 9.39f, 18.0198f, 9.21f, 18.2098f)
close()
moveTo(9.42f, 14.3798f)
curveTo(9.37f, 14.4998f, 9.3f, 14.6098f, 9.21f, 14.7098f)
curveTo(9.11f, 14.7998f, 9.0f, 14.8698f, 8.88f, 14.9198f)
curveTo(8.76f, 14.9698f, 8.63f, 14.9998f, 8.5f, 14.9998f)
curveTo(8.37f, 14.9998f, 8.24f, 14.9698f, 8.12f, 14.9198f)
curveTo(8.0f, 14.8698f, 7.89f, 14.7998f, 7.79f, 14.7098f)
curveTo(7.7f, 14.6098f, 7.63f, 14.4998f, 7.58f, 14.3798f)
curveTo(7.53f, 14.2598f, 7.5f, 14.1298f, 7.5f, 13.9998f)
curveTo(7.5f, 13.8698f, 7.53f, 13.7398f, 7.58f, 13.6198f)
curveTo(7.63f, 13.4998f, 7.7f, 13.3898f, 7.79f, 13.2898f)
curveTo(7.89f, 13.1998f, 8.0f, 13.1298f, 8.12f, 13.0798f)
curveTo(8.36f, 12.9798f, 8.64f, 12.9798f, 8.88f, 13.0798f)
curveTo(9.0f, 13.1298f, 9.11f, 13.1998f, 9.21f, 13.2898f)
curveTo(9.3f, 13.3898f, 9.37f, 13.4998f, 9.42f, 13.6198f)
curveTo(9.47f, 13.7398f, 9.5f, 13.8698f, 9.5f, 13.9998f)
curveTo(9.5f, 14.1298f, 9.47f, 14.2598f, 9.42f, 14.3798f)
close()
moveTo(12.71f, 14.7098f)
curveTo(12.61f, 14.7998f, 12.5f, 14.8698f, 12.38f, 14.9198f)
curveTo(12.26f, 14.9698f, 12.13f, 14.9998f, 12.0f, 14.9998f)
curveTo(11.87f, 14.9998f, 11.74f, 14.9698f, 11.62f, 14.9198f)
curveTo(11.5f, 14.8698f, 11.39f, 14.7998f, 11.29f, 14.7098f)
curveTo(11.11f, 14.5198f, 11.0f, 14.2598f, 11.0f, 13.9998f)
curveTo(11.0f, 13.7398f, 11.11f, 13.4798f, 11.29f, 13.2898f)
curveTo(11.39f, 13.1998f, 11.5f, 13.1298f, 11.62f, 13.0798f)
curveTo(11.86f, 12.9698f, 12.14f, 12.9698f, 12.38f, 13.0798f)
curveTo(12.5f, 13.1298f, 12.61f, 13.1998f, 12.71f, 13.2898f)
curveTo(12.89f, 13.4798f, 13.0f, 13.7398f, 13.0f, 13.9998f)
curveTo(13.0f, 14.2598f, 12.89f, 14.5198f, 12.71f, 14.7098f)
close()
}
}
.build()
return _calendar2!!
}
private var _calendar2: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
b8a8231e6637c2008f675ae76a3423b82ee53950
| 5,988
|
VuesaxIcons
|
MIT License
|
inaj-back/src/main/kotlin/org/github/dumijdev/inaj/exception/ResourceNotFoundException.kt
|
DumiJDev
| 675,451,151
| false
| null |
package org.github.dumijdev.inaj.exception
class ResourceNotFoundException(id: String) : RuntimeException("Resource not found with id=$id")
| 0
|
Kotlin
|
0
| 1
|
b35a23e7caea1f3c2f73abb3eeb6355c08adf927
| 141
|
inaj
|
MIT License
|
contract/src/main/kotlin/io/wax911/emojify/contract/serializer/IEmojiDeserializer.kt
|
AniTrend
| 98,423,653
| false
|
{"Kotlin": 122210}
|
package io.wax911.emojify.contract.serializer
import io.wax911.emojify.contract.model.AbstractEmoji
import java.io.InputStream
/**
* Interface to implement for custom deserializer.
*/
interface IEmojiDeserializer {
/**
* Decodes the given [InputStream] to an object of type List<[AbstractEmoji]>
*/
fun decodeFromStream(inputStream: InputStream): List<AbstractEmoji>
}
| 10
|
Kotlin
|
12
| 26
|
d91a63182b73b22c3a0163523c3073ee1108d57c
| 391
|
android-emojify
|
Apache License 2.0
|
shared/src/commonMain/kotlin/dev/johnoreilly/confetti/work/ConferenceSetting.kt
|
joreilly
| 436,024,503
| false
|
{"Kotlin": 890305, "Swift": 38931, "HTML": 23893, "HCL": 9137, "CSS": 8489, "Ruby": 3629}
|
package dev.johnoreilly.confetti.work
import dev.johnoreilly.confetti.ConfettiRepository
import kotlinx.coroutines.flow.Flow
open class ConferenceSetting(
val repository: ConfettiRepository
) {
open fun selectedConference(): Flow<String> {
return repository.getConferenceFlow()
}
}
| 49
|
Kotlin
|
91
| 784
|
d43e98fa3cd6eee949c3a0e57cf35d76dc49f083
| 303
|
Confetti
|
Apache License 2.0
|
tests/idling-resource/src/test/java/IdlingResourceTest.kt
|
Pitel
| 382,259,274
| true
|
{"Kotlin": 1351692, "ANTLR": 8207, "Java": 3282, "Shell": 832}
|
import com.apollographql.apollo3.mockserver.MockResponse
import com.apollographql.apollo3.mockserver.MockServer
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.android.ApolloIdlingResource
import com.apollographql.apollo3.android.withIdlingResource
import idling.resource.IdlingResourceQuery
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.single
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Test
import java.util.concurrent.Executors
class IdlingResourceTest {
@Test
fun idlingResourceSingleQuery() = runBlocking {
val mockServer = MockServer()
mockServer.enqueue(
MockResponse(
statusCode = 500,
delayMs = 500,
)
)
val idlingResource = ApolloIdlingResource("test")
val apolloClient = ApolloClient(mockServer.url())
.withIdlingResource(idlingResource)
launch(start = CoroutineStart.UNDISPATCHED) {
kotlin.runCatching {
apolloClient.query(IdlingResourceQuery())
}
}
assert(!idlingResource.isIdleNow)
delay(300)
assert(!idlingResource.isIdleNow)
delay(500)
assert(idlingResource.isIdleNow)
}
}
| 0
|
Kotlin
|
0
| 0
|
d6e74e0ca4c9029552c9b08b8898684734b994a6
| 1,527
|
apollo-android
|
MIT License
|
tests/idling-resource/src/test/java/IdlingResourceTest.kt
|
Pitel
| 382,259,274
| true
|
{"Kotlin": 1351692, "ANTLR": 8207, "Java": 3282, "Shell": 832}
|
import com.apollographql.apollo3.mockserver.MockResponse
import com.apollographql.apollo3.mockserver.MockServer
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.android.ApolloIdlingResource
import com.apollographql.apollo3.android.withIdlingResource
import idling.resource.IdlingResourceQuery
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.single
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Test
import java.util.concurrent.Executors
class IdlingResourceTest {
@Test
fun idlingResourceSingleQuery() = runBlocking {
val mockServer = MockServer()
mockServer.enqueue(
MockResponse(
statusCode = 500,
delayMs = 500,
)
)
val idlingResource = ApolloIdlingResource("test")
val apolloClient = ApolloClient(mockServer.url())
.withIdlingResource(idlingResource)
launch(start = CoroutineStart.UNDISPATCHED) {
kotlin.runCatching {
apolloClient.query(IdlingResourceQuery())
}
}
assert(!idlingResource.isIdleNow)
delay(300)
assert(!idlingResource.isIdleNow)
delay(500)
assert(idlingResource.isIdleNow)
}
}
| 0
|
Kotlin
|
0
| 0
|
d6e74e0ca4c9029552c9b08b8898684734b994a6
| 1,527
|
apollo-android
|
MIT License
|
app/src/main/java/com/iniongungroup/mobile/droid/autocheckmobile/di/modules/RemoteDataSourceModule.kt
|
IniongunIsaac
| 386,097,502
| false
| null |
package com.iniongungroup.mobile.droid.autocheckmobile.di.modules
import com.iniongungroup.mobile.droid.autocheckmobile.di.scopes.AppScope
import com.iniongungroup.mobile.droid.autocheckmobile.remotedatasource.repoimpl.inventory.InventoryRemoteDataSourceImpl
import com.iniongungroup.mobile.droid.autocheckmobile.repository.remotedatasource.inventory.IInventoryRemoteDataSource
import dagger.Binds
import dagger.Module
/**
* Created by Isaac Iniongun on 23/06/2020.
* For News App project.
*/
@Module
abstract class RemoteDataSourceModule {
@Binds
@AppScope
internal abstract fun bindInventoryRemoteDataSource(
remoteDataSource: InventoryRemoteDataSourceImpl
): IInventoryRemoteDataSource
}
| 0
|
Kotlin
|
0
| 1
|
3995cb27309321ae4ea355da7dffc2c6dec30fc5
| 722
|
Autocheck-Mobile-Android
|
The Unlicense
|
infra/src/main/kotlin/fr/sacane/jmanager/infrastructure/server/repositories/CategoryRepository.kt
|
Sacane
| 531,082,439
| false
| null |
package fr.sacane.jmanager.infrastructure.server.repositories
import fr.sacane.jmanager.infrastructure.server.entity.CategoryResource
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional
@Repository
interface CategoryRepository: JpaRepository<CategoryResource, Long>{
@Transactional
fun deleteByLabel(label: String)
}
| 0
|
Kotlin
|
0
| 0
|
7735ce372757e91ed667fdb905e8380306860b71
| 448
|
JManager
|
MIT License
|
charcoal-android-compose/src/main/java/net/pixiv/charcoal/android/compose/theme/CharcoalColorToken.kt
|
pixiv
| 580,258,047
| false
|
{"Kotlin": 120287, "JavaScript": 12005, "Java": 2332}
|
package net.pixiv.charcoal.android.compose.theme
import androidx.compose.ui.graphics.Color
data class CharcoalColorToken(
val brand: Color,
val brandDark: Color,
val assertive: Color,
val warning: Color,
val success: Color,
val like: Color,
val premium: Color,
val marker: Color,
val background1: Color,
val background2: Color,
val surface1: Color,
val surface2: Color,
val surface3: Color,
val surface4: Color,
val surface6: Color,
val surface9: Color,
val surface10: Color,
val link1: Color,
val text1: Color,
val text2: Color,
val text3: Color,
val text4: Color,
val text5: Color,
val border: Color
)
| 10
|
Kotlin
|
5
| 28
|
24c4006305aed1414d6830fe7ac4546141a46804
| 702
|
charcoal-android
|
Apache License 2.0
|
ui/src/main/java/com/pyamsoft/sleepforbreakfast/ui/icons/AutoAwesome.kt
|
pyamsoft
| 614,569,547
| false
|
{"Kotlin": 679438, "Shell": 457}
|
package com.pyamsoft.sleepforbreakfast.ui.icons
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.materialIcon
import androidx.compose.material.icons.materialPath
import androidx.compose.ui.graphics.vector.ImageVector
@Suppress("unused")
val Icons.Filled.AutoAwesome: ImageVector
get() {
if (_autoAwesome != null) {
return _autoAwesome!!
}
_autoAwesome =
materialIcon(name = "Filled.AutoAwesome") {
materialPath {
moveTo(19.0f, 9.0f)
lineToRelative(1.25f, -2.75f)
lineTo(23.0f, 5.0f)
lineToRelative(-2.75f, -1.25f)
lineTo(19.0f, 1.0f)
lineToRelative(-1.25f, 2.75f)
lineTo(15.0f, 5.0f)
lineToRelative(2.75f, 1.25f)
lineTo(19.0f, 9.0f)
close()
moveTo(11.5f, 9.5f)
lineTo(9.0f, 4.0f)
lineTo(6.5f, 9.5f)
lineTo(1.0f, 12.0f)
lineToRelative(5.5f, 2.5f)
lineTo(9.0f, 20.0f)
lineToRelative(2.5f, -5.5f)
lineTo(17.0f, 12.0f)
lineToRelative(-5.5f, -2.5f)
close()
moveTo(19.0f, 15.0f)
lineToRelative(-1.25f, 2.75f)
lineTo(15.0f, 19.0f)
lineToRelative(2.75f, 1.25f)
lineTo(19.0f, 23.0f)
lineToRelative(1.25f, -2.75f)
lineTo(23.0f, 19.0f)
lineToRelative(-2.75f, -1.25f)
lineTo(19.0f, 15.0f)
close()
}
}
return _autoAwesome!!
}
@Suppress("ObjectPropertyName") private var _autoAwesome: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
f11860f0ca6a3f0e5349ce1578300ddfb91cd2bb
| 1,651
|
sleepforbreakfast
|
Apache License 2.0
|
ui/src/main/java/com/pyamsoft/sleepforbreakfast/ui/icons/AutoAwesome.kt
|
pyamsoft
| 614,569,547
| false
|
{"Kotlin": 679438, "Shell": 457}
|
package com.pyamsoft.sleepforbreakfast.ui.icons
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.materialIcon
import androidx.compose.material.icons.materialPath
import androidx.compose.ui.graphics.vector.ImageVector
@Suppress("unused")
val Icons.Filled.AutoAwesome: ImageVector
get() {
if (_autoAwesome != null) {
return _autoAwesome!!
}
_autoAwesome =
materialIcon(name = "Filled.AutoAwesome") {
materialPath {
moveTo(19.0f, 9.0f)
lineToRelative(1.25f, -2.75f)
lineTo(23.0f, 5.0f)
lineToRelative(-2.75f, -1.25f)
lineTo(19.0f, 1.0f)
lineToRelative(-1.25f, 2.75f)
lineTo(15.0f, 5.0f)
lineToRelative(2.75f, 1.25f)
lineTo(19.0f, 9.0f)
close()
moveTo(11.5f, 9.5f)
lineTo(9.0f, 4.0f)
lineTo(6.5f, 9.5f)
lineTo(1.0f, 12.0f)
lineToRelative(5.5f, 2.5f)
lineTo(9.0f, 20.0f)
lineToRelative(2.5f, -5.5f)
lineTo(17.0f, 12.0f)
lineToRelative(-5.5f, -2.5f)
close()
moveTo(19.0f, 15.0f)
lineToRelative(-1.25f, 2.75f)
lineTo(15.0f, 19.0f)
lineToRelative(2.75f, 1.25f)
lineTo(19.0f, 23.0f)
lineToRelative(1.25f, -2.75f)
lineTo(23.0f, 19.0f)
lineToRelative(-2.75f, -1.25f)
lineTo(19.0f, 15.0f)
close()
}
}
return _autoAwesome!!
}
@Suppress("ObjectPropertyName") private var _autoAwesome: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
f11860f0ca6a3f0e5349ce1578300ddfb91cd2bb
| 1,651
|
sleepforbreakfast
|
Apache License 2.0
|
core/src/main/java/com/masscode/animesuta/core/di/CoreModule.kt
|
agustiyann
| 299,888,684
| false
| null |
package com.masscode.animesuta.core.di
import androidx.room.Room
import com.masscode.animesuta.core.data.AnimeRepository
import com.masscode.animesuta.core.data.source.local.LocalDataSource
import com.masscode.animesuta.core.data.source.local.room.AnimeDatabase
import com.masscode.animesuta.core.data.source.remote.RemoteDataSource
import com.masscode.animesuta.core.data.source.remote.network.ApiService
import com.masscode.animesuta.core.domain.repository.IAnimeRepository
import com.masscode.animesuta.core.utils.AppExecutors
import net.sqlcipher.database.SQLiteDatabase
import net.sqlcipher.database.SupportFactory
import okhttp3.CertificatePinner
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
val databaseModule = module {
factory { get<AnimeDatabase>().animeDao() }
single {
val passphrase: ByteArray = SQLiteDatabase.getBytes("masscode".toCharArray())
val factory = SupportFactory(passphrase)
Room.databaseBuilder(
androidContext(),
AnimeDatabase::class.java, "Anime.db"
).fallbackToDestructiveMigration()
.openHelperFactory(factory)
.build()
}
}
val networkModule = module {
single {
val hostname = "kitsu.io"
val certificatePinner = CertificatePinner.Builder()
.add(hostname, "sha256/mRjXIIcEJSE3kJl4YNqqfOS+COj4KG3VJPSJo6ymApk=")
.add(hostname, "sha256/FEzVOUp4dF3gI0ZVPRJhFbSJVXR+uQmMH65xhs1glH4=")
.add(hostname, "sha256/Y9mvm0exBk1JoQ57f9Vm28jKo5lFm/woKcVxrYxu80o=")
.build()
OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(120, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.certificatePinner(certificatePinner)
.build()
}
single {
val retrofit = Retrofit.Builder()
.baseUrl("https://kitsu.io/api/edge/")
.addConverterFactory(GsonConverterFactory.create())
.client(get())
.build()
retrofit.create(ApiService::class.java)
}
}
val repositoryModule = module {
single { LocalDataSource(get()) }
single { RemoteDataSource(get()) }
factory { AppExecutors() }
single<IAnimeRepository> {
AnimeRepository(
get(),
get(),
get()
)
}
}
| 0
|
Kotlin
|
10
| 55
|
0a51677ddcd69eb9f8c2f9c8da62518c894d06ce
| 2,622
|
Android-Clean-Architecture
|
Apache License 2.0
|
app/src/main/java/com/andreadev/stargazerssample/data/repository/PreferencesRepository.kt
|
battagliandrea
| 114,290,986
| false
| null |
package com.andreadev.stargazerssample.data.repository
import android.content.SharedPreferences
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by andrea on 23/04/17.
*/
@Singleton
class PreferencesRepository @Inject constructor(sp: SharedPreferences) {
private var mSharedPreferences : SharedPreferences = sp
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// STRING
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
fun put(key: String, value: String) {
mSharedPreferences.edit().putString(key, value).apply()
}
fun get(key: String, defaultValue: String): String? {
return mSharedPreferences.getString(key, defaultValue)
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// INTEGER
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
fun put(key: String, value: Int) {
mSharedPreferences.edit().putInt(key, value).apply()
}
fun get(key: String, defaultValue: Int): Int? {
return mSharedPreferences.getInt(key, defaultValue)
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// FLOAT
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
fun put(key: String, value: Float) {
mSharedPreferences.edit().putFloat(key, value).apply()
}
fun get(key: String, defaultValue: Float): Float? {
return mSharedPreferences.getFloat(key, defaultValue)
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// BOOLEAN
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
fun put(key: String, value: Boolean) {
mSharedPreferences.edit().putBoolean(key, value).apply()
}
fun get(key: String, defaultValue: Boolean): Boolean? {
return mSharedPreferences.getBoolean(key, defaultValue)
}
fun deleteSavedData(key: String) {
mSharedPreferences.edit().remove(key).apply()
}
}
| 0
|
Kotlin
|
0
| 0
|
5bb9d6e69f9163660c26de386c9b5cd64d4afbc2
| 2,672
|
StargazersSample
|
Apache License 2.0
|
plugins/analysis/kotlin-plugin/src/test/kotlin/arrow/meta/plugins/Utils.kt
|
arrow-kt
| 217,378,939
| false
| null |
package arrow.meta.plugins
import arrow.meta.plugin.testing.CompilerPlugin
import arrow.meta.plugin.testing.Config
import arrow.meta.plugin.testing.ConfigSyntax
import arrow.meta.plugin.testing.Dependency
fun ConfigSyntax.newMetaDependencies(): List<Config> {
val currentVersion = System.getProperty("CURRENT_VERSION")
val analysisPlugin =
CompilerPlugin(
"AnalysisPlugin",
listOf(Dependency("arrow-analysis-kotlin-plugin:$currentVersion"))
)
return metaDependencies +
addCompilerPlugins(analysisPlugin) +
addDependencies(analysisLib(currentVersion))
}
| 97
|
Kotlin
|
40
| 316
|
8d2a80cf3a1275a752c18baceed74cb61aa13b4d
| 589
|
arrow-meta
|
Apache License 2.0
|
iminling-core/src/main/kotlin/com/iminling/core/config/mybatis/SqlInterceptor.kt
|
konghanghang
| 340,850,176
| false
| null |
package com.iminling.core.config.mybatis
import org.apache.ibatis.cache.CacheKey
import org.apache.ibatis.executor.Executor
import org.apache.ibatis.mapping.BoundSql
import org.apache.ibatis.mapping.MappedStatement
import org.apache.ibatis.plugin.Interceptor
import org.apache.ibatis.plugin.Intercepts
import org.apache.ibatis.plugin.Invocation
import org.apache.ibatis.plugin.Signature
import org.apache.ibatis.session.Configuration
import org.apache.ibatis.session.ResultHandler
import org.apache.ibatis.session.RowBounds
import org.slf4j.LoggerFactory
/**
*
* @author <EMAIL>
* @since 2021/12/4
*/
@Intercepts(
Signature(type = Executor::class, method = "update", args = [MappedStatement::class, Object::class]),
Signature(type = Executor::class, method = "query", args = [MappedStatement::class, Object::class,
RowBounds::class, ResultHandler::class, CacheKey::class, BoundSql::class]),
Signature(type = Executor::class, method = "query", args = [MappedStatement::class, Object::class, RowBounds::class,
ResultHandler::class])
)
class SqlInterceptor: Interceptor {
private val logger = LoggerFactory.getLogger(SqlInterceptor::class.java)
override fun intercept(invocation: Invocation): Any {
// 耗时开始时间
val startTime = System.currentTimeMillis()
var mappedStatement = invocation.args[0] as MappedStatement
var parameter: Any? = null;
if (invocation.args.size > 1) {
//获得查询方法的参数,比如selectById(Integer id,String name),那么就可以获取到四个参数分别是:
//{id:1,name:"user1",param1:1,param2:"user1"}
parameter = invocation.args[1];
}
// 获取sql
var boundSql = mappedStatement.getBoundSql(parameter)
var sql = boundSql.sql.replace("[\\s\n ]+".toRegex(), " ")
// val sql: String = showSql(mappedStatement.configuration, mappedStatement.getBoundSql(parameterObject))
var params = getParams(mappedStatement.configuration, boundSql)
// 获取执行sql方法
val sqlId = mappedStatement.id
// 执行sql
val result = invocation.proceed()
// 计算总耗时
val cost = System.currentTimeMillis() - startTime
logger.info(" ======> SQL方法 : {} , SQL语句 : {}, 总耗时 : {}毫秒, 参数 :{}", sqlId, sql, cost, params)
return result
}
private fun getParams(configuration: Configuration, boundSql: BoundSql): String {
// 获取参数
val parameterObject = boundSql.parameterObject ?: return ""
val parameterMappings = boundSql.parameterMappings
// 获取类型处理器注册器,类型处理器的功能是进行java类型和数据库类型的转换
val typeHandlerRegistry = configuration.typeHandlerRegistry
var sb = StringBuilder()
if (typeHandlerRegistry.hasTypeHandler(parameterObject.javaClass)) {
sb.append(parameterObject).append(",")
} else {
// MetaObject主要是封装了originalObject对象,提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
val metaObject = configuration.newMetaObject(parameterObject)
for (parameterMapping in parameterMappings) {
val propertyName = parameterMapping.property
if (metaObject.hasGetter(propertyName)) {
val obj: Any = metaObject.getValue(propertyName)
sb.append(obj).append(",")
} else if (boundSql.hasAdditionalParameter(propertyName)) {
// 该分支是动态sql
val obj = boundSql.getAdditionalParameter(propertyName)
sb.append(obj).append(",")
} else {
// 打印出缺失,提醒该参数缺失并防止错位
sb.append("缺失").append(",")
}
}
}
if (sb.length > 1) {
sb.deleteCharAt(sb.length - 1)
}
return sb.toString()
}
/*private static String showSql(Configuration configuration, BoundSql boundSql) {
// 获取参数
Object parameterObject = boundSql.getParameterObject();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
// sql语句中多个空格都用一个空格代替
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
if (CollectionUtils.isNotEmpty(parameterMappings) && parameterObject != null) {
// 获取类型处理器注册器,类型处理器的功能是进行java类型和数据库类型的转换
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
// 如果根据parameterObject.getClass()可以找到对应的类型,则替换
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
} else {
// MetaObject主要是封装了originalObject对象,提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
MetaObject metaObject = configuration.newMetaObject(parameterObject);
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
} else if (boundSql.hasAdditionalParameter(propertyName)) {
// 该分支是动态sql
Object obj = boundSql.getAdditionalParameter(propertyName);
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
} else {
// 打印出缺失,提醒该参数缺失并防止错位
sql = sql.replaceFirst("\\?", "缺失");
}
}
}
}
return sql;
}
private static String getParameterValue(Object obj) {
String value;
if (obj instanceof String) {
value = "'" + obj.toString() + "'";
}
else if (obj instanceof Date) {
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
value = "'" + formatter.format(new Date()) + "'";
}
else {
if (obj != null) {
value = obj.toString();
} else {
value = "";
}
}
return value;
}*/
}
| 0
|
Kotlin
|
0
| 1
|
9f2cb7d85ad7364ff3aa92bfd5eb15db9b23809a
| 6,420
|
base-iminling-core
|
MIT License
|
browser-kotlin/src/jsMain/kotlin/web/idb/IDBCursorDirection.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6630901}
|
// Automatically generated - do not modify!
@file:Suppress(
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.idb
import seskar.js.JsValue
import seskar.js.JsVirtual
@JsVirtual
sealed external interface IDBCursorDirection {
companion object {
@JsValue("next")
val next: IDBCursorDirection
@JsValue("nextunique")
val nextunique: IDBCursorDirection
@JsValue("prev")
val prev: IDBCursorDirection
@JsValue("prevunique")
val prevunique: IDBCursorDirection
}
}
| 0
|
Kotlin
|
6
| 28
|
664781d7bdaf5f4aca206e11990b1d304fd45212
| 540
|
types-kotlin
|
Apache License 2.0
|
app/src/main/java/com/ruthvikbr/starbucksindiacompose/ui/utils/LandingScreenBottomSheet.kt
|
Ruthvikbr
| 519,740,797
| false
|
{"Kotlin": 261703}
|
package com.ruthvikbr.starbucksindiacompose.ui.utils
sealed class LandingScreenBottomSheet {
object LoginSheet : LandingScreenBottomSheet()
object GetHelpSheet : LandingScreenBottomSheet()
}
| 2
|
Kotlin
|
1
| 11
|
0147c79cfc70c3fe1b95443baedb49d2ebd6f05c
| 200
|
Starbucks-India-Compose
|
Apache License 2.0
|
zipline-loader/src/jvmTest/kotlin/app/cash/zipline/loader/ZiplineLoaderTest.kt
|
cashapp
| 41,445,081
| false
| null |
/*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.zipline.loader
import app.cash.zipline.QuickJs
import app.cash.zipline.Zipline
import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okio.Buffer
import okio.ByteString
import okio.ByteString.Companion.encodeUtf8
import okio.ByteString.Companion.toByteString
import okio.FileSystem
import okio.Path.Companion.toPath
import okio.fakefilesystem.FakeFileSystem
@Suppress("UnstableApiUsage")
@ExperimentalCoroutinesApi
class ZiplineLoaderTest {
private val httpClient = FakeZiplineHttpClient()
private val dispatcher = TestCoroutineDispatcher()
private val driver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY)
private val cacheSize = 1024 * 1024
private var nowMillis = 1_000L
private lateinit var loader: ZiplineLoader
private lateinit var fileSystem: FileSystem
private lateinit var resourceFileSystem: FileSystem
private val resourceDirectory = "/zipline".toPath()
private lateinit var quickJs: QuickJs
@BeforeTest
fun setUp() {
quickJs = QuickJs.create()
fileSystem = FakeFileSystem()
resourceFileSystem = FakeFileSystem()
loader = ZiplineLoader(
dispatcher = dispatcher,
httpClient = httpClient,
fileSystem = fileSystem,
resourceFileSystem = resourceFileSystem,
resourceDirectory = resourceDirectory,
cacheDbDriver = driver,
cacheDirectory = "/zipline/cache".toPath(),
nowMs = { nowMillis },
cacheMaxSizeInBytes = cacheSize
)
}
@AfterTest
fun tearDown() {
quickJs.close()
driver.close()
}
@Test
fun happyPath(): Unit = runBlocking(dispatcher) {
httpClient.filePathToByteString = mapOf(
alphaFilePath to alphaBytecode(quickJs),
bravoFilePath to bravoBytecode(quickJs)
)
val zipline = Zipline.create(dispatcher)
loader.load(zipline, manifest(quickJs))
assertEquals(
zipline.quickJs.evaluate("globalThis.log", "assert.js"),
"""
|alpha loaded
|bravo loaded
|""".trimMargin()
)
}
@Test
fun loadManifestFromUrl(): Unit = runBlocking(dispatcher) {
httpClient.filePathToByteString = mapOf(
manifestPath to Json.encodeToString(manifest(quickJs)).encodeUtf8(),
alphaFilePath to alphaBytecode(quickJs),
bravoFilePath to bravoBytecode(quickJs)
)
val zipline = Zipline.create(dispatcher)
loader.load(zipline, manifestPath)
assertEquals(
zipline.quickJs.evaluate("globalThis.log", "assert.js"),
"""
|alpha loaded
|bravo loaded
|""".trimMargin()
)
}
@Test
fun loaderUsesCache(): Unit = runBlocking(dispatcher) {
// load, no cache hit, download
httpClient.filePathToByteString = mapOf(
manifestPath to Json.encodeToString(manifest(quickJs)).encodeUtf8(),
alphaFilePath to alphaBytecode(quickJs),
bravoFilePath to bravoBytecode(quickJs)
)
val ziplineColdCache = Zipline.create(dispatcher)
loader.load(ziplineColdCache, manifestPath)
assertEquals(
ziplineColdCache.quickJs.evaluate("globalThis.log", "assert.js"),
"""
|alpha loaded
|bravo loaded
|""".trimMargin()
)
// load, cache hit, no download
httpClient.filePathToByteString = mapOf(
manifestPath to Json.encodeToString(manifest(quickJs)).encodeUtf8(),
// Note no actual alpha/bravo files are available on the network
)
val ziplineWarmedCache = Zipline.create(dispatcher)
loader.load(ziplineWarmedCache, manifestPath)
assertEquals(
ziplineWarmedCache.quickJs.evaluate("globalThis.log", "assert.js"),
"""
|alpha loaded
|bravo loaded
|""".trimMargin()
)
}
// TODO check resources for manifest too, not only network
@Test
fun loaderUsesResourcesBeforeCache(): Unit = runBlocking(dispatcher) {
// seed the resources FS with zipline files
resourceFileSystem.createDirectories(resourceDirectory)
resourceFileSystem.write(resourceDirectory / alphaBytecode(quickJs).sha256()) {
write(alphaBytecode(quickJs))
}
resourceFileSystem.write(resourceDirectory / bravoBytecode(quickJs).sha256()) {
write(bravoBytecode(quickJs))
}
// load, resources hit, no download via cache
httpClient.filePathToByteString = mapOf(
manifestPath to Json.encodeToString(manifest(quickJs)).encodeUtf8(),
// Note no actual alpha/bravo files are available on the cache / network
)
val ziplineWarmedCache = Zipline.create(dispatcher)
loader.load(ziplineWarmedCache, manifestPath)
assertEquals(
ziplineWarmedCache.quickJs.evaluate("globalThis.log", "assert.js"),
"""
|alpha loaded
|bravo loaded
|""".trimMargin()
)
}
companion object {
private val alphaJs = """
|globalThis.log = globalThis.log || "";
|globalThis.log += "alpha loaded\n"
|""".trimMargin()
private fun alphaBytecode(quickJs: QuickJs) = ziplineFile(quickJs, alphaJs, "alpha.js")
private const val alphaFilePath = "/alpha.zipline"
private val bravoJs = """
|globalThis.log = globalThis.log || "";
|globalThis.log += "bravo loaded\n"
|""".trimMargin()
private fun bravoBytecode(quickJs: QuickJs) = ziplineFile(quickJs, bravoJs, "bravo.js")
private const val bravoFilePath = "/bravo.zipline"
private const val manifestPath = "/manifest.zipline.json"
private fun manifest(quickJs: QuickJs) = ZiplineManifest.create(
modules = mapOf(
"bravo" to ZiplineModule(
url = bravoFilePath,
sha256 = bravoBytecode(quickJs).sha256(),
dependsOnIds = listOf("alpha"),
),
"alpha" to ZiplineModule(
url = alphaFilePath,
sha256 = alphaBytecode(quickJs).sha256(),
dependsOnIds = listOf(),
),
)
)
private fun ziplineFile(quickJs: QuickJs, javaScript: String, fileName: String): ByteString {
val ziplineFile = ZiplineFile(
CURRENT_ZIPLINE_VERSION,
quickJs.compile(javaScript, fileName).toByteString()
)
val buffer = Buffer()
ziplineFile.writeTo(buffer)
return buffer.readByteString()
}
}
}
| 30
|
C
|
101
| 1,153
|
74ea2906d3553e79ddd777989d2f3434e64c321d
| 7,090
|
duktape-android
|
Apache License 2.0
|
checkout-core/src/main/java/com/adyen/checkout/core/util/ParcelUtils.kt
|
leandromagnabosco
| 533,836,687
| false
| null |
/*
* Copyright (c) 2020 <NAME>.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by caiof on 17/12/2020.
*/
package com.adyen.checkout.core.util
import android.os.Parcel
object ParcelUtils {
private const val BOOLEAN_TRUE_VALUE = 1
private const val BOOLEAN_FALSE_VALUE = 0
/**
* Write boolean in to Parcel.
*/
@JvmStatic
fun writeBoolean(dest: Parcel, value: Boolean) {
dest.writeInt(if (value) BOOLEAN_TRUE_VALUE else BOOLEAN_FALSE_VALUE)
}
/**
* Read boolean from Parcel.
*/
@JvmStatic
fun readBoolean(input: Parcel): Boolean {
return input.readInt() == BOOLEAN_TRUE_VALUE
}
}
| 2
|
Kotlin
|
0
| 0
|
c154e989a08f1dc76cf90f6949878621cbbfa644
| 731
|
testsonarcloud
|
MIT License
|
app/src/main/java/com/example/viredapp/adapters/RequestBoundaryCallBack.kt
|
Dilip23
| 148,002,535
| false
| null |
package com.example.viredapp.adapters
import android.arch.paging.PagedList
import com.example.viredapp.database.RequestLocalCache
import com.example.viredapp.db.Request
import com.example.viredapp.model.RequestResult
import com.example.viredapp.utilities.ApiClient
import com.example.viredapp.utilities.UserClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
class RequestBoundaryCallBack(
private val cache: RequestLocalCache
): PagedList.BoundaryCallback<Request>(){
companion object {
private const val NETWORK_PAGE_SIZE = 50
private val apiClient = ApiClient.getApiClient().create(UserClient::class.java)
}
override fun onZeroItemsLoaded() {
requestAndSaveData(0)
}
override fun onItemAtEndLoaded(itemAtEnd: Request) {
requestAndSaveData(itemAtEnd.auto_id)
}
private fun requestAndSaveData(offset:Int){
val call: Call<RequestResult> = apiClient.getRequests(NETWORK_PAGE_SIZE,offset)
call.enqueue(object :Callback<RequestResult>{
override fun onFailure(call: Call<RequestResult>?, t: Throwable?) {
Timber.d(t?.message)
}
override fun onResponse(call: Call<RequestResult>?, response: Response<RequestResult>?) {
val res = response?.body()?.results
if (res != null){
cache.insert(res)
}
}
})
}
}
| 0
|
Kotlin
|
3
| 6
|
6f6c15340fb3e0738e49f61071d3b233f8ffe371
| 1,487
|
ViredApp
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.