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
hero/ui-heroDetail/src/main/kotlin/com/mitch/ui_herodetail/ui/HeroDetail.kt
AlekseevArtem
400,860,573
false
null
package com.mitch.ui_herodetail.ui import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import coil.ImageLoader import coil.annotation.ExperimentalCoilApi import coil.compose.rememberImagePainter import com.mitch.hero_domain.Hero import com.mitch.hero_domain.maxAttackDmg import com.mitch.hero_domain.minAttackDmg import com.mitch.ui_herodetail.R import kotlin.math.round @ExperimentalCoilApi @Composable fun HeroDetail( state: HeroDetailState, imageLoader: ImageLoader, ) { LazyColumn( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colors.background) ) { state.hero?.let { hero -> item { val painter = rememberImagePainter( data = hero.img, imageLoader = imageLoader, builder = { placeholder(if (isSystemInDarkTheme()) R.drawable.black_background else R.drawable.white_background) } ) Image( modifier = Modifier .fillMaxWidth() .defaultMinSize(minHeight = 200.dp), painter = painter, contentDescription = hero.localizedName, contentScale = ContentScale.Crop, ) Column( modifier = Modifier .fillMaxSize() .padding(all = 12.dp) ) { Row( modifier = Modifier .fillMaxWidth() .padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = hero.localizedName, style = MaterialTheme.typography.h1 ) val iconPainter = rememberImagePainter( data = state.hero.icon, imageLoader = imageLoader, builder = { placeholder(if (isSystemInDarkTheme()) R.drawable.black_background else R.drawable.white_background) }, ) Image( modifier = Modifier .height(30.dp) .width(30.dp), painter = iconPainter, contentDescription = hero.localizedName, contentScale = ContentScale.Crop, ) } Text( modifier = Modifier .padding(bottom = 4.dp), text = hero.primaryAttribute.uiValue, style = MaterialTheme.typography.subtitle1, ) Text( modifier = Modifier .padding(bottom = 12.dp), text = hero.attackType.uiValue, style = MaterialTheme.typography.caption ) HeroBaseStats( hero = hero, padding = 10.dp, ) Spacer(modifier = Modifier.height(12.dp)) WinPercentages(hero = hero) } } } } } @Composable fun WinPercentages( hero: Hero, ) { Row( modifier = Modifier.fillMaxWidth() ) { Column( modifier = Modifier.fillMaxWidth(.5f), horizontalAlignment = Alignment.CenterHorizontally, ) { val proWinPercentage = remember { round(hero.proWins.toDouble() / hero.proPick.toDouble() * 100).toInt() } Text( modifier = Modifier .padding(bottom = 8.dp) .align(Alignment.CenterHorizontally), text = "Pro Wins", style = MaterialTheme.typography.h2, ) Text( modifier = Modifier .padding(bottom = 8.dp) .align(Alignment.CenterHorizontally), text = "$proWinPercentage %", style = MaterialTheme.typography.h2, color = if (proWinPercentage > 50) Color(0xFF009a34) else MaterialTheme.colors.error ) } Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, ) { val turboWinPercentage = remember { round(hero.turboWins.toDouble() / hero.turboPicks.toDouble() * 100).toInt() } Text( modifier = Modifier .padding(bottom = 8.dp) .align(Alignment.CenterHorizontally), text = "Turbo Wins", style = MaterialTheme.typography.h2, ) Text( modifier = Modifier .padding(bottom = 8.dp) .align(Alignment.CenterHorizontally), text = "$turboWinPercentage %", style = MaterialTheme.typography.h2, color = if (turboWinPercentage > 50) Color(0xFF009a34) else MaterialTheme.colors.error ) } } } @Composable fun HeroBaseStats( hero: Hero, padding: Dp, ) { Surface( modifier = Modifier .fillMaxWidth(), elevation = 8.dp, shape = MaterialTheme.shapes.medium ) { Column( modifier = Modifier .fillMaxWidth() .padding(padding), ) { Text( modifier = Modifier .fillMaxWidth() .padding(bottom = 8.dp), text = "Base Stats", style = MaterialTheme.typography.h4 ) Row { Column( modifier = Modifier .fillMaxWidth(0.5f) .padding(end = 20.dp) ) { HolderForStat( name = stringResource(R.string.strength), firstValue = hero.baseStr.toString(), between = "+", secondValue = hero.strGain.toString() ) HolderForStat( name = stringResource(R.string.agility), firstValue = hero.baseAgi.toString(), between = "+", secondValue = hero.agiGain.toString() ) HolderForStat( name = stringResource(R.string.intelligence), firstValue = hero.baseInt.toString(), between = "+", secondValue = hero.intGain.toString() ) val health = remember { round(hero.baseHealth + hero.baseStr * 20).toInt() } HolderForStat( name = stringResource(R.string.health), firstValue = health.toString(), ) } Column { HolderForStat( name = stringResource(R.string.attack_range), firstValue = hero.attackRange.toString(), ) HolderForStat( name = stringResource(R.string.projectile_speed), firstValue = hero.projectileSpeed.toString(), ) HolderForStat( name = stringResource(R.string.move_speed), firstValue = hero.moveSpeed.toString(), ) HolderForStat( name = stringResource(R.string.attack_dmg), firstValue = "${hero.minAttackDmg()} - ${hero.maxAttackDmg()}", ) } } } } } @Composable fun HolderForStat( name: String, firstValue: String, between: String? = null, secondValue: String? = null, ) { Row( modifier = Modifier .fillMaxWidth() .padding(bottom = 8.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "$name:", style = MaterialTheme.typography.body2, ) Row( verticalAlignment = Alignment.Bottom ) { Text( text = firstValue, style = MaterialTheme.typography.body2, ) if (between != null && secondValue != null) { Text( text = " $between ", style = MaterialTheme.typography.caption, ) Text( text = secondValue, style = MaterialTheme.typography.caption, ) } } } }
0
Kotlin
0
0
4707e885a931dc4a46382a29e74d687943452ac8
10,094
Dota2Heroes
Apache License 2.0
app/src/main/java/com/yuchen/howyo/plan/findlocation/FindLocationFragment.kt
ione0213
418,168,888
false
null
package com.yuchen.howyo.plan.findlocation import android.location.Geocoder import android.os.Bundle import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.yuchen.howyo.HowYoApplication import com.yuchen.howyo.R import com.yuchen.howyo.databinding.FragmentFindLocationBinding import com.yuchen.howyo.ext.getVmFactory class FindLocationFragment : Fragment(), OnMapReadyCallback { private var googleMap: GoogleMap? = null private lateinit var mFusedLocationProviderClient: FusedLocationProviderClient private lateinit var binding: FragmentFindLocationBinding val viewModel by viewModels<FindLocationViewModel> { getVmFactory() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentFindLocationBinding.inflate(inflater, container, false) binding.lifecycleOwner = this binding.viewModel = viewModel binding.recyclerFindLocationDays.adapter = FindLocationDaysAdapter(viewModel) binding.edittextFindLocationSearch.setOnEditorActionListener { _, actionId, event -> when { actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.action == KeyEvent.ACTION_DOWN || event.action == KeyEvent.KEYCODE_ENTER -> { geoLocate() } } false } // Map mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient( HowYoApplication.instance ) val mapFragment = childFragmentManager.findFragmentById(R.id.map_find_location_destination) as SupportMapFragment mapFragment.getMapAsync(this) return binding.root } override fun onMapReady(map: GoogleMap) { this.googleMap = map } private fun geoLocate() { val geocoder = Geocoder(requireContext()) geocoder.getFromLocationName(binding.edittextFindLocationSearch.text.toString(), 1) } }
0
Kotlin
0
0
b63a8c79f881923bb049ada5081fdde63280639f
2,559
HowYo
MIT License
app/src/main/java/sample/kanda/burn/fact/states/Success.kt
jcaiqueoliveira
123,600,821
false
null
package sample.kanda.burn.fact.states import android.support.v7.widget.LinearLayoutManager import android.view.ViewGroup import kotlinx.android.synthetic.main.fact_success_state.view.* import sample.kanda.app.structure.ViewController import sample.kanda.burn.fact.FactView import sample.kanda.burn.widget.LceContainer /** * Created by caique on 3/15/18. */ class Success(private val facts: List<FactView>, private val container: ViewGroup) : ViewController { private val lceView: LceContainer = LceContainer(container.context) init { lceView.setUpView(ViewByState.SUCCESS_STATE) container.addView(lceView) startActions() } override fun startActions() { setUpView() } override fun dispose() { container.removeView(lceView) } private fun setUpView() { val manager = LinearLayoutManager(container.context) lceView.rootView.listFacts.apply { setHasFixedSize(true) layoutManager = manager adapter = SuccessAdapter(facts, onClickListener()) } } private fun onClickListener(): ClickListener { return object : ClickListener { override fun onClick(item: FactView) { //todo } } } }
0
Kotlin
0
2
e71755ffcaffaa1b00c5b1afd4a1b64baef644a6
1,281
finger-burn
MIT License
app/src/main/java/com/example/meliexample/ui/ProductDetailFragment.kt
yampyer
638,024,469
false
null
package com.example.meliexample.ui import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import coil.load import com.example.meliexample.R import com.example.meliexample.data.Resource import com.example.meliexample.databinding.FragmentProductDetailBinding import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ProductDetailFragment : Fragment() { private var _binding: FragmentProductDetailBinding? = null private val binding get() = _binding!! private val viewModel by viewModels<ProductDetailViewModel>() private val args: ProductDetailFragmentArgs by navArgs() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.getProduct(args.itemId) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentProductDetailBinding.inflate(inflater, container, false) setupUI() return binding.root } private fun setupUI() { with(binding) { viewModel.product.observe(viewLifecycleOwner) { response -> when (response.status) { Resource.Status.SUCCESS -> { loading.isGone = true toolbarImage.load(response.data?.pictures?.firstOrNull()?.secureUrl) toolbarLayout.title = response.data?.title productName.text = response.data?.title productPrice.text = String.format(getString(R.string.currency_format), (response.data?.salePrice ?: response.data?.price)) response.data?.discounts?.let { productDiscount.text = String.format(getString(R.string.discount_format), it) } response.data?.availableQuantity?.let { productQuantityAvailable.run { if (it == 0) setTextColor(ContextCompat.getColor(context, R.color.red)) text = resources.getQuantityString(R.plurals.available_quantity, it, it) } } response.data?.soldQuantity?.let { productQuantitySold.run { isVisible = it > 0 text = resources.getQuantityString(R.plurals.sold_quantity, it, it) } } productShipping.isVisible = response.data?.shipping?.freeShipping == true fabBuyNow.setOnClickListener { val intent = Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(response.data?.permalink) } startActivity(intent) } if (response.data?.attributes?.isNotEmpty() == true) { val stringBuilder = StringBuilder() response.data.attributes.forEach { attr -> stringBuilder.append(attr.name).append(": ").appendLine(attr.value) } productFeatures.text = stringBuilder.toString() } else { productFeaturesLbl.isGone = true } } Resource.Status.ERROR -> { loading.isGone = true Snackbar.make(root, response.message.toString(), Snackbar.LENGTH_LONG).show() } Resource.Status.LOADING -> { loading.isVisible = true } } } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
688d952a33ed4707cee08ffbb0fa7d17fa2a523e
4,397
marketplace
Apache License 2.0
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/dccreissuance/DccReissuanceUiModule.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.dccreissuance import dagger.Module import dagger.android.ContributesAndroidInjector import de.rki.coronawarnapp.dccreissuance.ui.consent.DccReissuanceConsentFragment import de.rki.coronawarnapp.dccreissuance.ui.consent.DccReissuanceConsentFragmentModule import de.rki.coronawarnapp.dccreissuance.ui.consent.acccerts.DccReissuanceAccCertsFragment import de.rki.coronawarnapp.dccreissuance.ui.consent.acccerts.DccReissuanceAccCertsFragmentModule @Module abstract class DccReissuanceUiModule { @ContributesAndroidInjector(modules = [DccReissuanceConsentFragmentModule::class]) abstract fun dccReissuanceConsentFragment(): DccReissuanceConsentFragment @ContributesAndroidInjector(modules = [DccReissuanceAccCertsFragmentModule::class]) abstract fun dccReissuanceAccCertsFragment(): DccReissuanceAccCertsFragment }
6
null
514
2,495
d3833a212bd4c84e38a1fad23b282836d70ab8d5
859
cwa-app-android
Apache License 2.0
data/src/main/java/com/nawrot/mateusz/campaignapp/data/campaign/repository/WestwingCampaignsRepository.kt
mateusz-nawrot
113,742,433
false
null
package com.nawrot.mateusz.campaignapp.data.campaign.repository import com.nawrot.mateusz.campaignapp.data.campaign.api.CampaignsApi import com.nawrot.mateusz.campaignapp.data.campaign.model.GetCampaignsResponse import com.nawrot.mateusz.campaignapp.domain.campaign.model.Campaign import com.nawrot.mateusz.campaignapp.domain.campaign.repository.CampaignsRepository import io.reactivex.Single import retrofit2.Retrofit import javax.inject.Inject class WestwingCampaignsRepository @Inject constructor(private val retrofit: Retrofit) : CampaignsRepository { override fun getCampaigns(): Single<List<Campaign>> { return retrofit.create(CampaignsApi::class.java) .getCampaigns().map { mapResponse(it) } } private fun mapResponse(response: GetCampaignsResponse): List<Campaign> { return response.metadata.data.map { Campaign(it.name, it.description, it.image.url) } } }
0
Kotlin
0
0
bace991cd778be2cbdb9e97e9b02099afa096eb9
918
campaignapp
Apache License 2.0
app/src/main/java/com/revosleap/sample/MainActivity.kt
Kevin-Kip
217,555,280
false
null
package com.revosleap.sample import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.revosleap.mobilesasa.MobileSasa import com.revosleap.mobilesasa.models.MobileSasaResponse class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val m = MobileSasa( userName = "KevinKiprotich", API_KEY = <KEY>" ) // m.sendSMS("0725778511","Hello. Library test") // m.sendMultipleSMS(listOf("0725778511","0724963950"),"Hello. Android Library test") } }
0
Kotlin
0
1
9425dd9e4d5807e714644dd1ad634ba8209e081a
661
MobileSasaAPI
MIT License
tony-boot-demo/tony-dto/src/main/kotlin/com/tony/dto/enums/ModuleType.kt
beingEggache
312,472,927
false
{"Java": 1825396, "HTML": 354682, "Kotlin": 287327, "Dockerfile": 2745, "Shell": 2105, "CSS": 1466}
package com.tony.dto.enums import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.tony.core.enums.EnumCreator import com.tony.core.enums.EnumIntValue /** * * @author tangli * @since 2020-11-04 14:54 */ enum class ModuleType( override val value: Int ) : EnumIntValue { API(1), ROUTE(2), COMPONENT(3), @JsonEnumDefaultValue UNUSED(EnumCreator.defaultIntValue); companion object : EnumCreator<ModuleType, Int>(ModuleType::class.java) { @JsonCreator @JvmStatic override fun create(value: Int) = super.create(value) } }
1
null
1
1
1c2991364067f3c28e7f99cd46df3e8f4000b18c
661
tony-boot
MIT License
src/test/resources/examples/nestedPolymorphicModels/models/RootType.kt
cjbooms
229,844,927
false
{"Kotlin": 874094, "Handlebars": 4874}
package examples.nestedPolymorphicModels.models import com.fasterxml.jackson.`annotation`.JsonSubTypes import com.fasterxml.jackson.`annotation`.JsonTypeInfo import kotlin.Boolean import kotlin.String @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "rootDiscriminator", visible = true, ) @JsonSubTypes(JsonSubTypes.Type(value = FirstLevelChild::class, name = "firstLevelChild")) public sealed class RootType( public open val rootField1: String, public open val rootField2: Boolean? = null, ) { public abstract val rootDiscriminator: RootDiscriminator }
33
Kotlin
41
154
b95cb5bd8bb81e59eca71e467118cd61a1848b3f
620
fabrikt
Apache License 2.0
app/src/main/java/ru/tinkoff/news/list/adapter/NewsAdapter.kt
nikitosbobin
185,379,960
false
null
package ru.tinkoff.news.list.adapter import android.widget.TextView import com.hannesdorfmann.adapterdelegates3.ListDelegationAdapter import ru.tinkoff.news.list.ListItem import ru.tinkoff.news.model.NewsItemTitle class NewsAdapter( onNewsItemClickListener: (NewsItemTitle, TextView) -> Unit ) : ListDelegationAdapter<List<ListItem>>() { init { delegatesManager.addDelegate(HewsTimeDividerDelegate()) delegatesManager.addDelegate(NewsItemTitleDelegate(onNewsItemClickListener)) } }
0
Kotlin
0
0
aff0d4858776d4363a44f5fbdc1fd1b51200cf52
513
tinkoff-news
Apache License 2.0
app/src/main/java/com/eneskayiklik/word_diary/feature/settings/presentation/about/component/AboutTextButton.kt
Enes-Kayiklik
651,794,521
false
null
package com.eneskayiklik.word_diary.feature.settings.presentation.about.component import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp @Composable fun AboutTextButton( modifier: Modifier = Modifier, icon: Painter? = null, imageVector: ImageVector? = null, contentDescription: String? = null, title: String, onClick: () -> Unit ) { TextButton(onClick = onClick, modifier = modifier) { if (icon != null) Icon( painter = icon, contentDescription = contentDescription, modifier = Modifier.size(16.dp) ) else if (imageVector != null) Icon( imageVector = imageVector, contentDescription = contentDescription, modifier = Modifier.size(16.dp) ) Text( text = title, modifier = Modifier.padding(start = if (icon != null || imageVector != null) 8.dp else 0.dp) ) } }
0
Kotlin
0
3
c40d2b7fe1ce9b8926b660dcbbaa088fbca05f11
1,313
WordDiary
MIT License
app/src/main/java/com/eneskayiklik/word_diary/feature/settings/presentation/about/component/AboutTextButton.kt
Enes-Kayiklik
651,794,521
false
null
package com.eneskayiklik.word_diary.feature.settings.presentation.about.component import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp @Composable fun AboutTextButton( modifier: Modifier = Modifier, icon: Painter? = null, imageVector: ImageVector? = null, contentDescription: String? = null, title: String, onClick: () -> Unit ) { TextButton(onClick = onClick, modifier = modifier) { if (icon != null) Icon( painter = icon, contentDescription = contentDescription, modifier = Modifier.size(16.dp) ) else if (imageVector != null) Icon( imageVector = imageVector, contentDescription = contentDescription, modifier = Modifier.size(16.dp) ) Text( text = title, modifier = Modifier.padding(start = if (icon != null || imageVector != null) 8.dp else 0.dp) ) } }
0
Kotlin
0
3
c40d2b7fe1ce9b8926b660dcbbaa088fbca05f11
1,313
WordDiary
MIT License
app-core/src/main/kotlin/ru/micron/rest/FavouriteController.kt
m1cron
326,198,639
false
null
package ru.micron.rest import org.slf4j.LoggerFactory import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.* import ru.micron.dto.BasicResponse import ru.micron.dto.FavouriteDto import ru.micron.dto.PageableResponse import ru.micron.dto.omdb.FilmResponseDto import ru.micron.service.FavouriteService import java.util.* import javax.validation.constraints.Max import javax.validation.constraints.Min @CrossOrigin(origins = ["*"], maxAge = 3600) @Validated @RestController @RequestMapping("/api/v1/favourite") class FavouriteController( private val favouriteService: FavouriteService ) { private val log = LoggerFactory.getLogger(this.javaClass) @GetMapping fun getFavouriteByUserUuid( @RequestParam uuid: UUID?, @RequestParam(defaultValue = "1") pageNum: @Min(1) Int, @RequestParam(defaultValue = "12") pageSize: @Min(1) @Max(500) Int ): BasicResponse<PageableResponse<FilmResponseDto>> { log.debug( "getFavouriteByUserUuid uuid:{} pageNum:{} pageSize:{}", uuid, pageNum, pageSize ) return BasicResponse(favouriteService.getUserFilmsByUserUuid(uuid, pageNum, pageSize)) } @PostMapping("/checkIsFavourite") fun checkIsFavourite(@RequestBody dto: FavouriteDto): BasicResponse<Boolean> { log.debug("checkIsFavourite {}", dto) return BasicResponse(favouriteService.checkIsFavourite(dto), true) } @PostMapping("/add") fun addFavourite(@RequestBody dto: FavouriteDto): BasicResponse<Void> { log.debug("addFavourite {}", dto) favouriteService.addFavourite(dto) return BasicResponse() } @PostMapping("/remove") fun removeFromFavourite(@RequestBody dto: FavouriteDto): BasicResponse<Void> { log.debug("removeFromFavourite {}", dto) favouriteService.removeFavourite(dto) return BasicResponse() } }
0
Kotlin
1
4
dde2817edbe5e20f539804d1e9ccbec7c27330d3
1,965
films_catalog
MIT License
common/src/commonMain/kotlin/org/kryptonmc/nbt/EndTag.kt
KryptonMC
388,819,410
false
null
/* * This file is part of Krypton NBT, licensed under the MIT license. * * Copyright (C) 2021 KryptonMC and contributors * * This project is licensed under the terms of the MIT license. * For more details, please reference the LICENSE file in the top-level directory. */ package org.kryptonmc.nbt import okio.BufferedSink import okio.BufferedSource import org.kryptonmc.nbt.io.TagReader import org.kryptonmc.nbt.io.TagWriter import kotlin.jvm.JvmField /** * The tag representing the end of a compound tag. */ public object EndTag : Tag { public const val ID: Int = 0 @JvmField public val TYPE: TagType = TagType("TAG_End", true) @JvmField public val READER: TagReader<EndTag> = object : TagReader<EndTag> { override fun read(input: BufferedSource, depth: Int) = EndTag } @JvmField public val WRITER: TagWriter<EndTag> = object : TagWriter<EndTag> { override fun write(output: BufferedSink, value: EndTag) = Unit } override val id: Int = ID override val type: TagType = TYPE override fun write(output: BufferedSink): Unit = Unit override fun <T> examine(examiner: TagExaminer<T>): Unit = examiner.examineEnd(this) override fun copy(): EndTag = this override fun toString(): String = "EndTag" }
0
Kotlin
0
3
9492e7d8983354acde6d734a56d28a3437ef4599
1,288
nbt
MIT License
buildSrc/src/main/kotlin/com/github/turansky/yfiles/vsdx/FakeInterfaces.kt
turansky
80,245,850
false
null
package com.github.turansky.yfiles.vsdx import com.github.turansky.yfiles.IENUMERABLE import com.github.turansky.yfiles.ILIST_ENUMERABLE import com.github.turansky.yfiles.Interface import com.github.turansky.yfiles.correction.ID import com.github.turansky.yfiles.correction.METHODS import com.github.turansky.yfiles.correction.NAME import com.github.turansky.yfiles.json.jObject internal fun fakeVsdxInterfaces(): List<Interface> { return listOf( fakeVsdxInterface( id = IENUMERABLE, methodNames = setOf("getEnumerator") ), fakeVsdxInterface( id = ILIST_ENUMERABLE, methodNames = setOf("getEnumerator", "get") ) ) } private fun fakeVsdxInterface(id: String, methodNames: Set<String>): Interface { return Interface( jObject( ID to id, NAME to id, METHODS to methodNames.map { jObject( NAME to it ) } ) ) }
0
Kotlin
1
20
2f99a85a9c531eeb04f885aead4f6de28d1bda89
1,020
yfiles-kotlin
Apache License 2.0
app/src/main/java/com/zhangke/notionlight/config/NotionPageRoom.kt
0xZhangKe
468,651,930
false
{"Kotlin": 207160, "HTML": 1745}
package com.zhangke.notionlight.config import android.content.Context import androidx.room.* import com.zhangke.framework.utils.appContext import com.zhangke.notionlib.data.NotionBlock import kotlinx.coroutines.flow.Flow private const val DB_NAME = "notion_page.db" private const val DB_VERSION = 1 private const val CONFIG_TABLE_NAME = "notion_page_config" private const val BLOCK_TABLE_NAME = "notion_page_block" @Entity(tableName = CONFIG_TABLE_NAME) data class NotionPageConfig( @PrimaryKey val id: String, val title: String, val lastEditTime: Long, val url: String ) @Entity(tableName = BLOCK_TABLE_NAME) data class NotionBlockInPage( @PrimaryKey val id: String, val pageId: String, val editTimestamp: Long, val notionBlock: NotionBlock, ) @Dao interface NotionPageConfigDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insetConfig(config: List<NotionPageConfig>) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insetConfig(config: NotionPageConfig) @Query("SELECT * FROM $CONFIG_TABLE_NAME") fun queryAllConfig(): Flow<List<NotionPageConfig>> @Delete suspend fun deletePage(config: List<NotionPageConfig>) @Query("DELETE FROM $CONFIG_TABLE_NAME") suspend fun nukeTable() } @Dao interface NotionBlockInPageDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insetOrUpdateBlocks(block: List<NotionBlockInPage>) @Query("SELECT * FROM $BLOCK_TABLE_NAME WHERE id == :blockId") suspend fun queryBlock(blockId: String): NotionBlockInPage? @Query("SELECT * FROM $BLOCK_TABLE_NAME WHERE pageId == :pageId") fun queryBlockWithPageId(pageId: String): Flow<List<NotionBlockInPage>> @Query("SELECT * FROM $BLOCK_TABLE_NAME WHERE pageId == :pageId ORDER BY editTimestamp DESC LIMIT :count OFFSET 0") suspend fun queryLatestBlockWithPageIdByTime( pageId: String, count: Int ): List<NotionBlockInPage> @Query("DELETE FROM $BLOCK_TABLE_NAME WHERE pageId == :pageId") suspend fun deletePageAllBlock(pageId: String) @Query("DELETE FROM $BLOCK_TABLE_NAME") suspend fun nukeTable() } @TypeConverters(NotionPageRoomConverters::class) @Database(entities = [NotionPageConfig::class, NotionBlockInPage::class], version = DB_VERSION) abstract class NotionPageDataBase : RoomDatabase() { abstract fun pageConfigDao(): NotionPageConfigDao abstract fun blockInPageDao(): NotionBlockInPageDao companion object { val instance: NotionPageDataBase by lazy { createInstance(appContext) } private fun createInstance(context: Context): NotionPageDataBase { return Room.databaseBuilder(context, NotionPageDataBase::class.java, DB_NAME) .build() } } }
0
Kotlin
11
94
f5ba12c5f80cfd192a5667e488ccd86c00b6a65b
2,797
NotionLight
Apache License 2.0
src/main/kotlin/zielinskin/kotlinsample/data/SampleEntity.kt
zielinskin
515,733,191
false
{"Kotlin": 6671}
package zielinskin.kotlinsample.data import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id @Entity data class SampleEntity( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Int? = null, var name: String )
0
Kotlin
0
0
e426aa47c6d0fa2346b52c120f2ccb1225078337
322
kotlin-boot-sample
The Unlicense
domain/usecase/src/main/java/com/cupcake/usecase/validation/ValidationResult.kt
The-Cupcake-team
646,926,125
false
null
package com.cupcake.usecase.validation data class ValidationResult( val successful: Boolean, val errorMessage: String? = null )
5
Kotlin
0
0
f215bc977d9f5288d2a4cd8d4a625371a964b2f7
138
Jobs-finder
MIT License
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/preferences/fragments/NotificationsPreferencesFragment.kt
alxsey
164,690,528
true
{"Kotlin": 445682, "Java": 2719}
/* * VoIP.ms SMS * Copyright (C) 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 net.kourlas.voipms_sms.preferences.fragments import android.content.SharedPreferences import android.media.RingtoneManager import android.net.Uri import android.os.Bundle import android.support.v7.preference.Preference import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.takisoft.fix.support.v7.preference.PreferenceFragmentCompatDividers import com.takisoft.fix.support.v7.preference.RingtonePreference import net.kourlas.voipms_sms.R import net.kourlas.voipms_sms.preferences.getNotificationSound class NotificationsPreferencesFragment : PreferenceFragmentCompatDividers(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) { // Add preferences addPreferencesFromResource(R.xml.preferences_notifications) // Add listener for preference changes preferenceScreen.sharedPreferences .registerOnSharedPreferenceChangeListener(this) updateSummaries() } override fun onResume() { super.onResume() updateSummaries() } /** * Updates the summary text for all preferences. */ fun updateSummaries() { if (preferenceScreen != null) { for (i in 0 until preferenceScreen.preferenceCount) { val subPreference = preferenceScreen.getPreference(i) updateSummaryTextForPreference(subPreference) } } } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { // It's not clear why onSharedPreferenceChanged is called before the // fragment is actually added to the activity, but it apparently is; // this check is therefore required to prevent a crash if (isAdded) { // Update summary text for changed preference updateSummaryTextForPreference(findPreference(key)) } } /** * Updates the summary text for the specified preference. * * @param preference The specified preference. */ private fun updateSummaryTextForPreference(preference: Preference?) { val context = context ?: return if (preference is RingtonePreference) { // Display selected notification sound as summary text for // notification setting @Suppress("DEPRECATION") val notificationSound = getNotificationSound( context) if (notificationSound == "") { preference.summary = "None" } else { try { val ringtone = RingtoneManager.getRingtone( activity, Uri.parse(notificationSound)) if (ringtone != null) { preference.summary = ringtone.getTitle( activity) } else { preference.summary = getString( R.string.preferences_notifications_sound_unknown) } } catch (ex: SecurityException) { preference.summary = getString( R.string.preferences_notifications_sound_unknown_perm) } } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { try { return super.onCreateView(inflater, container, savedInstanceState) } finally { setDividerPreferences(DIVIDER_NONE) } } }
0
Kotlin
0
0
70307fb7487217062e0df78ca75522fa413df761
4,353
voipms-sms-client
Apache License 2.0
src/main/kotlin/io/neoold/dynamic_object/DynamicJsonValue.kt
NatanielBR
533,759,914
false
null
package io.neoold.dynamic_object import io.neoold.dynamic_object.DynamicList.Companion.toDynamic import io.neoold.dynamic_object.DynamicObject.Companion.toDynamicJsonObject import kotlinx.serialization.json.* class DynamicJsonValue( valueJson: JsonElement ) : DynamicValue(valueJson) { init { // try to convert to object runCatching { val obj = valueJson.jsonObject value = obj.map { it.key to it.value }.toMap().toDynamicJsonObject() }.onFailure { // try to convert to list runCatching { val list = valueJson.jsonArray value = list.toList().map { it.toDynamicJsonValue() }.toDynamic() }.onFailure { // do primitive value = castJsonPrimitive(valueJson.jsonPrimitive) } } } companion object { /** * Cast a JsonPrimitive to a primitive type */ private fun castJsonPrimitive(primitive: JsonPrimitive): Any? { return if (primitive.isString) primitive.content else primitive.intOrNull ?: primitive.longOrNull ?: primitive.doubleOrNull ?: primitive.floatOrNull ?: primitive.booleanOrNull } /** * Convert a String Json to a DynamicValue. */ fun String.jsonToDynamicObject(): DynamicValue { return DynamicJsonValue( Json.decodeFromString<JsonElement>(this) ) } /** * Convert a JsonElement to a DynamicValue. */ private fun JsonElement.toDynamicJsonValue(): DynamicValue { return DynamicJsonValue(this) } } }
0
Kotlin
0
0
cde1a1e2baaef7684cb59e735c909de56bcfb6b1
1,748
DynamicObject
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/WindowFrameOpen.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.filled 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.Filled.WindowFrameOpen: ImageVector get() { if (_windowFrameOpen != null) { return _windowFrameOpen!! } _windowFrameOpen = Builder(name = "WindowFrameOpen", 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(23.0f, 22.0f) horizontalLineToRelative(-1.0f) verticalLineToRelative(-8.0f) curveToRelative(0.0f, -0.552f, -0.447f, -1.0f, -1.0f, -1.0f) lineTo(3.0f, 13.0f) curveToRelative(-0.552f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f) verticalLineToRelative(8.0f) horizontalLineToRelative(-1.0f) curveToRelative(-0.552f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f) reflectiveCurveToRelative(0.448f, 1.0f, 1.0f, 1.0f) horizontalLineToRelative(22.0f) curveToRelative(0.553f, 0.0f, 1.0f, -0.448f, 1.0f, -1.0f) reflectiveCurveToRelative(-0.447f, -1.0f, -1.0f, -1.0f) close() moveTo(11.0f, 11.0f) lineTo(3.0f, 11.0f) curveToRelative(-0.552f, 0.0f, -1.0f, -0.448f, -1.0f, -1.0f) verticalLineToRelative(-5.5f) curveTo(2.0f, 2.015f, 4.015f, 0.0f, 6.5f, 0.0f) horizontalLineToRelative(4.5f) verticalLineToRelative(11.0f) close() moveTo(22.0f, 4.5f) verticalLineToRelative(5.5f) curveToRelative(0.0f, 0.552f, -0.448f, 1.0f, -1.0f, 1.0f) horizontalLineToRelative(-8.0f) lineTo(13.0f, 0.0f) horizontalLineToRelative(4.5f) curveToRelative(2.485f, 0.0f, 4.5f, 2.015f, 4.5f, 4.5f) close() } } .build() return _windowFrameOpen!! } private var _windowFrameOpen: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,795
icons
MIT License
feature4/src/main/java/com/example/feature4/Feature4ActivityViewModel.kt
ChicK00o
194,475,938
false
null
package com.example.feature4 import android.arch.lifecycle.LiveData import android.arch.lifecycle.ViewModel import javax.inject.Inject class Feature4ActivityViewModel @Inject constructor( private val feature4Repository: Feature4Repository) : ViewModel() { var mainText : LiveData<String> = feature4Repository.mainText fun setText(value : String) { feature4Repository.mainText.value = value } }
0
Kotlin
0
1
83626707c0559443c90d60afb009d9dd5ba29b5f
421
android-multi-module-playground
MIT License
rest/src/main/kotlin/builder/stage/StageInstanceCreateBuilder.kt
jombidev
507,000,315
false
{"Kotlin": 2022642, "Java": 87103}
package dev.jombi.kordsb.rest.builder.stage import dev.jombi.kordsb.common.annotation.KordDsl import dev.jombi.kordsb.common.entity.Snowflake import dev.jombi.kordsb.common.entity.StageInstancePrivacyLevel import dev.jombi.kordsb.common.entity.StageInstancePrivacyLevel.GuildOnly import dev.jombi.kordsb.common.entity.optional.Optional import dev.jombi.kordsb.common.entity.optional.OptionalBoolean import dev.jombi.kordsb.common.entity.optional.delegate.delegate import dev.jombi.kordsb.rest.builder.AuditRequestBuilder import dev.jombi.kordsb.rest.json.request.StageInstanceCreateRequest @KordDsl public class StageInstanceCreateBuilder( /** The id of the Stage channel. */ public var channelId: Snowflake, /** The topic of the Stage instance (1-120 characters). */ public var topic: String, ) : AuditRequestBuilder<StageInstanceCreateRequest> { override var reason: String? = null private var _privacyLevel: Optional<StageInstancePrivacyLevel> = Optional.Missing() /** The [privacy level][StageInstancePrivacyLevel] of the Stage instance (default [GuildOnly]). */ public var privacyLevel: StageInstancePrivacyLevel? by ::_privacyLevel.delegate() private var _sendStartNotification: OptionalBoolean = OptionalBoolean.Missing /** Notify @everyone that a Stage instance has started. */ public var sendStartNotification: Boolean? by ::_sendStartNotification.delegate() override fun toRequest(): StageInstanceCreateRequest = StageInstanceCreateRequest( channelId, topic, _privacyLevel, _sendStartNotification, ) }
0
Kotlin
0
4
7e4eba1e65e5454e5c9400da83bd2de883acf96d
1,604
kord-selfbot
MIT License
src/main/kotlin/br/com/zup/b1gvini/pix/grpc/remove/RemoveExtension.kt
b1gvini
385,366,765
true
{"Kotlin": 62931}
package br.com.zup.b1gvini.pix.grpc.remove import br.com.zup.b1gvini.RemovePixRequest fun RemovePixRequest.toRemovePixDTO(): RemovePixDto{ return RemovePixDto( pixId = this.pixId, clientId = this.clientId ) }
0
Kotlin
0
0
8f8472d6340ffa8724b22440f77e40fa5d47551c
235
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/org/oppia/android/app/help/thirdparty/ThirdPartyDependencyItemViewModel.kt
oppia
148,093,817
false
{"Kotlin": 13302271, "Starlark": 693163, "Java": 34760, "Shell": 18872}
package org.oppia.android.app.help.thirdparty import androidx.appcompat.app.AppCompatActivity import org.oppia.android.app.help.LoadLicenseListFragmentListener import org.oppia.android.app.viewmodel.ObservableViewModel /** * Content view model for the recycler view in [ThirdPartyDependencyListFragment]. It contains * the name and version of the dependency which is displayed in the RecyclerView. */ class ThirdPartyDependencyItemViewModel( private val activity: AppCompatActivity, val dependencyName: String, val dependencyVersion: String, val dependencyIndex: Int, val isMultipane: Boolean ) : ObservableViewModel() { /** Starts [LicenseListActivity] upon clicking on an item of the third-party dependency list. */ fun clickOnThirdPartyDependencyItem() { if (isMultipane) { val loadLicenseListFragmentListener = activity as LoadLicenseListFragmentListener loadLicenseListFragmentListener.loadLicenseListFragment(dependencyIndex) } else { val routeToLicenseListListener = activity as RouteToLicenseListListener routeToLicenseListListener.onRouteToLicenseList(dependencyIndex) } } }
508
Kotlin
517
315
95699f922321f49a3503783187a14ad1cef0d5d3
1,142
oppia-android
Apache License 2.0
app/src/main/java/it/unibs/mp/horace/backend/room/daos/AreasDao.kt
H3isenb3rg
604,173,455
false
null
package it.unibs.mp.horace.backend.room.daos import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import it.unibs.mp.horace.backend.room.models.LocalArea import kotlinx.coroutines.flow.Flow @Dao interface AreasDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(area: LocalArea): Long @Update suspend fun update(area: LocalArea) @Delete suspend fun delete(area: LocalArea) @Query("SELECT * from areas WHERE id = :id") fun get(id: Long): Flow<LocalArea> @Query("SELECT * from areas ORDER BY name ASC") fun getAll(): Flow<List<LocalArea>> }
9
Kotlin
0
0
35359457e0bdc8f8b7cb9600e4c5e4defbfe3fad
729
MobileProgramming2023
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/quicksight/PieChartFieldWellsPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.quicksight import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.quicksight.CfnTemplate @Generated public fun buildPieChartFieldWellsProperty(initializer: @AwsCdkDsl CfnTemplate.PieChartFieldWellsProperty.Builder.() -> Unit): CfnTemplate.PieChartFieldWellsProperty = CfnTemplate.PieChartFieldWellsProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
483
aws-cdk-kt
Apache License 2.0
src/main/kotlin/com/kingchampion36/simple/authentication/and/authorisation/repository/EmployeeRepository.kt
KingChampion36
755,490,666
false
{"Kotlin": 11924}
package com.kingchampion36.simple.authentication.and.authorisation.repository import com.kingchampion36.simple.authentication.and.authorisation.model.Employee interface EmployeeRepository { fun save(employee: Employee) fun delete(employeeId: Int) fun get(employeeId: Int): Employee? fun getAll(): List<Employee> }
0
Kotlin
0
0
c812c3bf282a7ef24fabde1b67f322b15e8a5336
324
simple-authentication-and-authorisation
MIT License
AC_2_MOBILE/AC02/app/src/main/java/br/com/prgtapp/MainActivity.kt
Impacta-Michel
348,701,725
true
{"Python": 368027, "JavaScript": 234950, "CSS": 167944, "HTML": 88954, "Kotlin": 10796, "Shell": 3082, "PowerShell": 1755, "Batchfile": 1566, "Xonsh": 1173, "PHP": 1116}
package br.com.prgtapp import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import kotlinx.android.synthetic.main.login.* class MainActivity : DebugActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.login) register.setOnClickListener { Toast.makeText(this, "Registre-se no site", Toast.LENGTH_LONG).show() } botao_login.setOnClickListener { val nome_usuario = campo_usuario.text.toString() val senha_usuario = campo_senha.text.toString() val intent = Intent(this, TelaInicialActivity::class.java) if (nome_usuario == "aluno" && senha_usuario == "<PASSWORD>"){ val params = Bundle() params.putString("nome", nome_usuario) intent.putExtras(params) startActivity(intent) } else { Toast.makeText(this, "Usuário ou senha incorretos", Toast.LENGTH_LONG).show() } } } }
0
Python
0
0
ddc1708fb0fe6a62dbfa5ffa1a3d30a4f1c9f002
1,149
PRGT
Apache License 2.0
app/src/main/java/com/example/tbilisi_parking_final_exm/data/service/parking/active_parking/GetActiveParkingService.kt
Lasha-Ilashvili
749,926,592
false
{"Kotlin": 373909}
package com.example.tbilisi_parking_final_exm.data.service.parking.active_parking import com.example.tbilisi_parking_final_exm.data.model.parking.active_parking.ActiveParkingDto import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Path interface GetActiveParkingService { @GET("parking/user/{userId}") suspend fun getActiveParking( @Path("userId") userId :Int ): Response<List<ActiveParkingDto>> }
0
Kotlin
1
0
20653c5077a4fa61e2c9616ddd986a82faf040dd
441
Tbilisi_Parking_FINAL_EXM
Apache License 2.0
app/src/test/java/com/openwallet/ui/activity/fragment/register/model/RegisterVerifyEmailSmsResponseTest.kt
hsbc
742,467,592
false
{"Kotlin": 502702, "Java": 40426}
package com.openwallet.ui.activity.fragment.register.model import junit.framework.TestCase import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class RegisterVerifyEmailSmsResponseTest : TestCase() { @Before public override fun setUp() { super.setUp() } @Test fun test_RegisterVerifyEmailSmsResponse() { val expectedData = RegisterVerifyEmailSmsData("token","111111") val registerVerifyEmailSmsData = RegisterVerifyEmailSmsData("token","111111") registerVerifyEmailSmsData.captcha registerVerifyEmailSmsData.token assertEquals(expectedData.token,registerVerifyEmailSmsData.token) val expectedResponseData = RegisterVerifyEmailSmsResponse(false,"message",registerVerifyEmailSmsData) val registerVerifyEmailSmsResponseData = RegisterVerifyEmailSmsResponse(false,"message",registerVerifyEmailSmsData) registerVerifyEmailSmsResponseData.message registerVerifyEmailSmsResponseData.status registerVerifyEmailSmsResponseData.data assertEquals(expectedResponseData.data,registerVerifyEmailSmsResponseData.data) } }
0
Kotlin
0
1
b72ac403ce1e38139ab42548967e08e6db347ddd
1,235
OpenWallet-aOS
Apache License 2.0
app/src/main/java/com/hongwei/coroutines_demo/util/RateUtil.kt
hongwei-bai
345,956,226
false
null
package com.hongwei.coroutines_demo.util import java.text.DecimalFormat object RateUtil { fun toDisplay(name: String, content: String, rate: Double) = "Hi $name,\n${content.replace("{rate}", formatRate(rate), false)}" fun toDisplay(content: String, rate: Double) = content.replace("{rate}", formatRate(rate), false) private fun formatRate(rate: Double): String { val decimalFormat = DecimalFormat("#,###.##") val display = decimalFormat.format(rate) return display } }
0
Kotlin
0
0
0cc9dd65a6a69dfd653ed1b2a36a87ba798ac00f
520
coroutines-demo
Apache License 2.0
Kotlin/SelectionSort.kt
shauryam-exe
412,424,939
true
{"Java": 54671, "C++": 46151, "C": 27439, "Python": 27284, "JavaScript": 19473, "Kotlin": 14848, "C#": 5916, "Go": 4305}
fun main(args: Array<String>) { //Input the array in the format num1 num2 num3 num4 etc print("Enter the elements for the Array: ") var inputArray = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray() var sortedArray = selectionSort(inputArray) println(sortedArray.contentToString()) } fun selectionSort(arr: IntArray): IntArray { for (i in arr.lastIndex downTo 0) { var max = arr[0] var maxIndex = 0 for (j in 0..i) { if (arr[maxIndex]<arr[j]) maxIndex = j } val temp = arr[maxIndex] arr[maxIndex] = arr[i] arr[i] = temp } return arr } //Sample //Input: Enter the elements for the Array: 64 23 -12 -5 0 2 89 20 100 32 650 -230 130 //Output: [-230, -12, -5, 0, 2, 20, 23, 32, 64, 89, 100, 130, 650] //Time Complexity: Worst Case: O(n^2) Best Case: O(n^2) //Space Complexity: O(1)
0
Java
0
0
3a247451ade57138c3255dbbd27bfb0610f9f02e
924
DS-Algo-Zone
MIT License
src/jsMain/kotlin/domain/use_case/chat/ChatGetAllUseCase.kt
Tanexc
667,134,735
false
null
package domain.use_case.chat import domain.model.Chat import domain.repository.ChatRepository import kotlinx.coroutines.flow.Flow import org.koin.core.component.KoinComponent import org.koin.core.component.inject import util.State class ChatGetAllUseCase: KoinComponent { private val repository: ChatRepository by inject() operator fun invoke(token: String): Flow<State<List<Chat>>> = repository.getAll(token) }
0
Kotlin
0
3
27bc23f5ab9dbc8ec7da5fc7812555bbbcaeb0a7
424
ComposeWebCakes
Apache License 2.0
music/player/src/main/kotlin/dev/schlaubi/mikmusic/core/settings/UserSettings.kt
DRSchlaubi
409,332,765
false
{"Kotlin": 367107, "Java": 5153, "Dockerfile": 392, "Shell": 205, "PowerShell": 104}
package dev.schlaubi.mikmusic.core.settings import dev.kord.common.entity.Snowflake import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class UserSettings( @SerialName("_id") val id: Snowflake, val defaultSchedulerSettings: SchedulerSettings? = null )
12
Kotlin
11
36
7023a740f1019eba14ae667ba63b049743e7f502
315
mikbot
MIT License
magicpen-workflow-core/src/main/kotlin/io/github/liqiha0/magicpen/workflow/action/math/Divide.kt
magicpenproject
418,622,750
false
{"Kotlin": 41398, "Java": 377}
package io.github.liqiha0.magicpen.workflow.action.math import io.github.liqiha0.magicpen.workflow.* import io.github.liqiha0.magicpen.workflow.data.Number import java.math.BigDecimal val DIVIDE_DESCRIPTION = ActionDescription( "除", "divide", listOf( ActionParameterDescription("值1", "operand1"), ActionParameterDescription("值2", "operand2") ), listOf(ActionResultDescription("结果", "result", "number")) ) object Divide : Action { override fun execute(context: ActionContext): Map<String, Data>? { val operand1: Number = context.getArgument("operand1") ?: throw UnexpectedDataTypeException() val operand2: Number? = context.getArgument("operand2") return mapOf("result" to Number(operand1.value / (operand2?.value ?: BigDecimal.ZERO))) } }
0
Kotlin
0
3
deb643242f2ef5565aabc1f9e507d7530627efa4
806
magicpen-workflow
Apache License 2.0
ComicX/src/main/java/com/qiuchenly/comicparse/Modules/MainActivity/Activity/MainActivityUI.kt
MyGhost233
203,593,656
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Proguard": 2, "Java": 128, "XML": 116, "Kotlin": 93}
package com.qiuchenly.comicparse.Modules.MainActivity.Activity import android.os.Bundle import android.view.KeyEvent import com.qiuchenly.comicparse.BaseImp.BaseApp import com.qiuchenly.comicparse.Modules.MainActivity.ViewModel.MainActivityViewModel import com.qiuchenly.comicparse.R import kotlinx.android.synthetic.main.navigation_main.* class MainActivityUI : BaseApp() { override fun getLayoutID(): Int { return R.layout.activity_switch_main } private var mViewModel: MainActivityViewModel? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //viewModel处理UI mViewModel = MainActivityViewModel(this) mUpdateInfo.setOnRefreshListener { mViewModel?.getWeathers() } mViewModel?.getWeathers() //TODO 此处启动后台下载服务暂时不写 //startService(Intent(this, DownloadService::class.java)) } override fun onDestroy() { super.onDestroy() if (mViewModel != null) { mViewModel!!.cancel() mViewModel = null System.gc() } } override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { return if (!mViewModel!!.canExit(keyCode)) false else super.onKeyUp(keyCode, event) } fun updateInfo() { mViewModel!!.notifyData() } }
1
null
1
1
057406d81e685aeb272df22450e40cfc64a535bb
1,362
iComic
MIT License
quickstep/tests/src/com/android/quickstep/HotseatWidthCalculationTest.kt
ItsLynix
576,464,965
false
{"Java Properties": 1, "Markdown": 6, "Makefile": 3, "Shell": 1, "Batchfile": 1, "Python": 5, "Proguard": 1, "Java": 697, "Kotlin": 321, "INI": 1}
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.quickstep import android.graphics.Rect import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.android.launcher3.DeviceProfileBaseTest import com.android.launcher3.util.WindowBounds import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) class HotseatWidthCalculationTest : DeviceProfileBaseTest() { /** * This is a case when after setting the hotseat, the space needs to be recalculated * but it doesn't need to change QSB width or remove icons */ @Test fun distribute_border_space_when_space_is_enough_portrait() { initializeVarsForTablet(isGestureMode = false) windowBounds = WindowBounds(Rect(0, 0, 1800, 2560), Rect(0, 104, 0, 0)) val dp = newDP() dp.isTaskbarPresentInApps = true assertThat(dp.hotseatBarEndOffset).isEqualTo(558) assertThat(dp.numShownHotseatIcons).isEqualTo(6) assertThat(dp.hotseatBorderSpace).isEqualTo(69) assertThat(dp.getHotseatLayoutPadding(context).left).isEqualTo(176) assertThat(dp.getHotseatLayoutPadding(context).right).isEqualTo(558) assertThat(dp.isQsbInline).isFalse() assertThat(dp.hotseatQsbWidth).isEqualTo(1445) } /** * This is a case when after setting the hotseat, and recalculating spaces * it still needs to remove icons for everything to fit */ @Test fun decrease_num_of_icons_when_not_enough_space_portrait() { initializeVarsForTablet(isGestureMode = false) windowBounds = WindowBounds(Rect(0, 0, 1300, 2560), Rect(0, 104, 0, 0)) val dp = newDP() dp.isTaskbarPresentInApps = true assertThat(dp.hotseatBarEndOffset).isEqualTo(558) assertThat(dp.numShownHotseatIcons).isEqualTo(4) assertThat(dp.hotseatBorderSpace).isEqualTo(76) assertThat(dp.getHotseatLayoutPadding(context).left).isEqualTo(122) assertThat(dp.getHotseatLayoutPadding(context).right).isEqualTo(558) assertThat(dp.isQsbInline).isFalse() assertThat(dp.hotseatQsbWidth).isEqualTo(1058) } /** * This is a case when after setting the hotseat, the space needs to be recalculated * but it doesn't need to change QSB width or remove icons */ @Test fun distribute_border_space_when_space_is_enough_landscape() { initializeVarsForTwoPanel(isGestureMode = false, isLandscape = true) val dp = newDP() dp.isTaskbarPresentInApps = true assertThat(dp.hotseatBarEndOffset).isEqualTo(744) assertThat(dp.numShownHotseatIcons).isEqualTo(6) assertThat(dp.hotseatBorderSpace).isEqualTo(83) assertThat(dp.getHotseatLayoutPadding(context).left).isEqualTo(106) assertThat(dp.getHotseatLayoutPadding(context).right).isEqualTo(744) assertThat(dp.isQsbInline).isFalse() assertThat(dp.hotseatQsbWidth).isEqualTo(1467) } /** * This is a case when the hotseat spans a certain amount of columns * and the nav buttons push the hotseat to the side, but not enough to change the border space. */ @Test fun nav_buttons_dont_interfere_with_required_hotseat_width() { initializeVarsForTablet(isGestureMode = false, isLandscape = true) inv?.apply { hotseatColumnSpan = IntArray(4) { 4 } inlineQsb = BooleanArray(4) { false } } val dp = newDP() dp.isTaskbarPresentInApps = true assertThat(dp.hotseatBarEndOffset).isEqualTo(705) assertThat(dp.numShownHotseatIcons).isEqualTo(6) assertThat(dp.hotseatBorderSpace).isEqualTo(108) assertThat(dp.getHotseatLayoutPadding(context).left).isEqualTo(631) assertThat(dp.getHotseatLayoutPadding(context).right).isEqualTo(705) assertThat(dp.isQsbInline).isFalse() assertThat(dp.hotseatQsbWidth).isEqualTo(1227) } /** * This is a case when after setting the hotseat, the QSB width needs to be changed to fit */ @Test fun decrease_qsb_when_not_enough_space_landscape() { initializeVarsForTablet(isGestureMode = false, isLandscape = true) windowBounds = WindowBounds(Rect(0, 0, 2460, 1600), Rect(0, 104, 0, 0)) val dp = newDP() dp.isTaskbarPresentInApps = true assertThat(dp.hotseatBarEndOffset).isEqualTo(705) assertThat(dp.numShownHotseatIcons).isEqualTo(6) assertThat(dp.hotseatBorderSpace).isEqualTo(36) assertThat(dp.getHotseatLayoutPadding(context).left).isEqualTo(884) assertThat(dp.getHotseatLayoutPadding(context).right).isEqualTo(705) assertThat(dp.isQsbInline).isTrue() assertThat(dp.hotseatQsbWidth).isEqualTo(559) } /** * This is a case when after setting the hotseat, changing QSB width, and recalculating spaces * it still needs to remove icons for everything to fit */ @Test fun decrease_num_of_icons_when_not_enough_space_landscape() { initializeVarsForTablet(isGestureMode = false, isLandscape = true) windowBounds = WindowBounds(Rect(0, 0, 2260, 1600), Rect(0, 104, 0, 0)) val dp = newDP() dp.isTaskbarPresentInApps = true assertThat(dp.hotseatBarEndOffset).isEqualTo(705) assertThat(dp.numShownHotseatIcons).isEqualTo(5) assertThat(dp.hotseatBorderSpace).isEqualTo(56) assertThat(dp.getHotseatLayoutPadding(context).left).isEqualTo(801) assertThat(dp.getHotseatLayoutPadding(context).right).isEqualTo(705) assertThat(dp.isQsbInline).isTrue() assertThat(dp.hotseatQsbWidth).isEqualTo(480) } }
1
null
1
1
32df3fcf5d0824f7148346f23441acf93ac7e319
6,353
lawnchair
Apache License 2.0
app/sepuling-kotlin/src/it/kotlin/smecalculus/bezmen/storage/SepulkaDaoMyBatisPostgresIT.kt
smecalculus
481,685,166
false
{"Maven POM": 15, "Text": 4, "Ignore List": 3, "AsciiDoc": 10, "Java": 102, "INI": 9, "PlantUML": 1, "Dockerfile": 10, "Jinja": 7, "YAML": 46, "Kotlin": 20, "SQL": 7, "XML": 2}
package smecalculus.bezmen.storage import org.springframework.test.context.ContextConfiguration import smecalculus.bezmen.construction.SepulkaDaoBeans import smecalculus.bezmen.construction.StoragePropsBeans @ContextConfiguration(classes = [StoragePropsBeans.MyBatisPostgres::class, SepulkaDaoBeans.MyBatis::class]) class SepulkaDaoMyBatisPostgresIT : SepulkaDaoIT()
11
Java
0
0
c39dfa4126a55f2b01dbab7448d6e9c09f2f4fc5
369
bezmen
MIT License
app/shared/ui/core/public/src/commonMain/kotlin/build/wallet/statemachine/core/ComposableRenderedModel.kt
proto-at-block
761,306,853
false
{"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.statemachine.core import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import kotlin.native.HiddenFromObjC /** * Applied to any Presentation Model that is capable of * being rendered directly from the Model instance. */ interface ComposableRenderedModel { val key: String /** * Render the Model's Composable content. */ @HiddenFromObjC @Composable fun render(modifier: Modifier) }
3
C
16
113
694c152387c1fdb2b6be01ba35e0a9c092a81879
450
bitkey
MIT License
common/src/commonMain/kotlin/dev/zwander/common/model/adapters/SimData.kt
zacharee
641,202,797
false
null
package dev.zwander.common.model.adapters import kotlinx.serialization.Serializable @Serializable data class SimDataRoot( val sim: SimData? = null, ) @Serializable data class SimData( val iccId: String? = null, val imei: String? = null, val imsi: String? = null, val msisdn: String? = null, val status: Boolean? = null, )
14
null
4
91
3d958ae0b2581815d4e496b0fef69186cc3a8c4f
349
ArcadyanKVD21Control
MIT License
ExoPlayerPoc2/app/src/main/java/in_/co/innerpeacetech/exoplayerpoc/AudioCache.kt
PembaTamang
360,779,713
true
{"Text": 1, "Ignore List": 3, "Markdown": 1, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "Kotlin": 12, "XML": 111, "Java": 1}
package in_.co.innerpeacetech.exoplayerpoc import android.content.Context import com.google.android.exoplayer2.database.ExoDatabaseProvider import com.google.android.exoplayer2.upstream.cache.NoOpCacheEvictor import com.google.android.exoplayer2.upstream.cache.SimpleCache import java.io.File class AudioCache { companion object{ private var sDownloadCache: SimpleCache? = null fun getInstance(context: Context): SimpleCache? { if (sDownloadCache == null) sDownloadCache = SimpleCache( File(context.cacheDir, "exoCache"), NoOpCacheEvictor(), ExoDatabaseProvider(context) ) return sDownloadCache } } }
0
Kotlin
0
0
eb59db9feb6a42819f728841e782024606c2987f
724
Poc
Apache License 2.0
equinox-core/src/test/java/com/caco3/equinox/core/argument/ModelAttributeRenderMethodArgumentResolverTest.kt
cac03
178,065,985
false
{"Java": 20740, "Kotlin": 19820}
package com.caco3.equinox.core.argument import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.springframework.core.annotation.SynthesizingMethodParameter import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpServletResponse import org.springframework.web.bind.annotation.ModelAttribute import kotlin.reflect.jvm.javaMethod class ModelAttributeRenderMethodArgumentResolverTest { private fun renderFunction( @ModelAttribute("myAttribute") string: String ) { } private val argumentResolver = ModelAttributeRenderMethodArgumentResolver() private fun getMethodParameterForRenderFunction() = SynthesizingMethodParameter(::renderFunction.javaMethod!!, 0) @Test fun `argument with @ModelAttribute is supported`() { val methodParameter = getMethodParameterForRenderFunction() assertTrue(argumentResolver.supportsArgument(methodParameter), "$argumentResolver should support parameters with @ModelAttribute") } @Test fun `argument should be resolved`() { val methodParameter = getMethodParameterForRenderFunction() val model = mapOf<String, Any>("myAttribute" to "myValue") val resolvedArgument = argumentResolver.resolveArgument(methodParameter, model, MockHttpServletRequest(), MockHttpServletResponse()) assertEquals("myValue", resolvedArgument) { "$argumentResolver should resolve argument from $model" } } }
1
Java
1
1
ee752bf46d1b79b2d38bc9879451ce7a9ea13c99
1,623
equinox
Apache License 2.0
mordant/src/commonMain/kotlin/com/github/ajalt/mordant/table/TableDsl.kt
suminb
360,435,521
true
{"Kotlin": 381831, "Python": 5334}
package com.github.ajalt.mordant.table import com.github.ajalt.colormath.Color import com.github.ajalt.mordant.internal.DEFAULT_STYLE import com.github.ajalt.mordant.rendering.* import com.github.ajalt.mordant.widgets.Caption import com.github.ajalt.mordant.widgets.Padding import com.github.ajalt.mordant.widgets.Text interface CellStyleBuilder { var padding: Padding? var style: TextStyle? var borders: Borders? var align: TextAlign? var verticalAlign: VerticalAlign? var overflowWrap: OverflowWrap? fun style( color: Color? = null, bgColor: Color? = null, bold: Boolean = false, italic: Boolean = false, underline: Boolean = false, dim: Boolean = false, inverse: Boolean = false, strikethrough: Boolean = false, hyperlink: String? = null, ) { style = TextStyle(color, bgColor, bold, italic, underline, dim, inverse, strikethrough, hyperlink) } fun padding(all: Int) { padding = Padding(all) } fun padding(vertical: Int, horizontal: Int) { padding = Padding(vertical, horizontal, vertical, horizontal) } fun padding(top: Int, horizontal: Int, bottom: Int) { padding = Padding(top, horizontal, bottom, horizontal) } fun padding(top: Int, right: Int, bottom: Int, left: Int) { padding = Padding(top, right, bottom, left) } } private class CellStyleBuilderMixin : CellStyleBuilder { override var padding: Padding? = null override var style: TextStyle? = null override var borders: Borders? = null override var align: TextAlign? = null override var verticalAlign: VerticalAlign? = null override var overflowWrap: OverflowWrap? = null } sealed class ColumnWidth { /** The column will fit to the size of its content */ object Auto : ColumnWidth() /** The column will have a fixed [width] */ class Fixed(val width: Int) : ColumnWidth() { init { require(width > 0) { "width must be greater than zero" } } } /** * The column will expand to fill the available terminal width. * * If there are multiple expanding columns, the available width will be divided among them * proportional to their [weight]s. */ class Expand(val weight: Float = 1f) : ColumnWidth() { init { require(weight > 0) { "weight must be greater than zero" } } constructor(weight: Int) : this(weight.toFloat()) } } @DslMarker annotation class MordantDsl @MordantDsl class ColumnBuilder internal constructor() : CellStyleBuilder by CellStyleBuilderMixin() { /** Set the width for this column */ var width: ColumnWidth = ColumnWidth.Auto } @MordantDsl class TableBuilder internal constructor() : CellStyleBuilder by CellStyleBuilderMixin() { var borderStyle: BorderStyle = BorderStyle.SQUARE var borderTextStyle: TextStyle = DEFAULT_STYLE var outerBorder: Boolean = true internal val columns = mutableMapOf<Int, ColumnBuilder>() internal val headerSection = SectionBuilder() internal val bodySection = SectionBuilder() internal val footerSection = SectionBuilder() internal var captionTop: Widget? = null internal var captionBottom: Widget? = null /** Add a [widget] as a caption oto the top of this table. */ fun captionTop(widget: Widget) { captionTop = widget } /** Add [text] as a caption to the top of this table. */ fun captionTop(text: String, align: TextAlign = TextAlign.CENTER) { captionTop(Text(text, align = align)) } /** Add a [widget] as a caption to the bottom of this table. */ fun captionBottom(widget: Widget) { captionBottom = widget } /** Add [text] as a caption to the bottom of this table. */ fun captionBottom(text: String, align: TextAlign = TextAlign.CENTER) { captionBottom(Text(text, align = align)) } /** Configure a single column, which the first column at index 0. */ fun column(i: Int, init: ColumnBuilder.() -> Unit) = initColumn(columns, i, ColumnBuilder(), init) /** Configure the header section. */ fun header(init: SectionBuilder.() -> Unit) { headerSection.init() } /** Configure the body section. */ fun body(init: SectionBuilder.() -> Unit) { bodySection.init() } /** Configure the footer section. */ fun footer(init: SectionBuilder.() -> Unit) { footerSection.init() } } @MordantDsl class SectionBuilder internal constructor() : CellStyleBuilder by CellStyleBuilderMixin() { internal val rows = mutableListOf<RowBuilder>() internal val columns = mutableMapOf<Int, CellStyleBuilder>() internal var rowStyles = listOf<TextStyle>() /** Configure a single column, which the first column at index 0. */ fun column(i: Int, init: CellStyleBuilder.() -> Unit) = initColumn(columns, i, ColumnBuilder(), init) /** Add styles to alternating rows. If there are more rows than styles, the styles will loop. */ fun rowStyles(style1: TextStyle, style2: TextStyle, vararg styles: TextStyle) { rowStyles = listOf(style1, style2) + styles.asList() } /** * Add all [cells] from an iterable. */ fun rowFrom(cells: Iterable<Any?>, init: RowBuilder.() -> Unit = {}) { val cellBuilders = cells.mapTo(mutableListOf()) { CellBuilder(getWidget(it)) } rows += RowBuilder(cellBuilders).apply(init) } /** * Add a row with one or more cells. */ fun row(vararg cells: Any?, init: RowBuilder.() -> Unit = {}) { rowFrom(cells.asList(), init) } /** * Add a row. */ fun row(init: RowBuilder.() -> Unit) { rows += RowBuilder(mutableListOf()).apply(init) } } @MordantDsl class GridBuilder internal constructor(private val section: SectionBuilder) : CellStyleBuilder by section { internal val columns = mutableMapOf<Int, ColumnBuilder>() /** Configure a single column, with the first column at index 0. */ fun column(i: Int, init: ColumnBuilder.() -> Unit) = initColumn(columns, i, ColumnBuilder(), init) /** Add styles to alternating rows. If there are more rows than styles, the styles will loop. */ fun rowStyles(style1: TextStyle, style2: TextStyle, vararg styles: TextStyle) { section.rowStyles(style1, style2, *styles) } /** * Add all [cells] from an iterable. */ fun rowFrom(cells: Iterable<Any?>, init: RowBuilder.() -> Unit = {}) { section.rowFrom(cells, init) } /** * Add a row with one or more cells. */ fun row(vararg cells: Any?, init: RowBuilder.() -> Unit = {}) { section.row(*cells, init = init) } /** * Add a row. */ fun row(init: RowBuilder.() -> Unit) { section.row(init) } } @MordantDsl class RowBuilder internal constructor( internal val cells: MutableList<CellBuilder>, ) : CellStyleBuilder by CellStyleBuilderMixin() { /** Add multiple cells to this row */ fun cells(cell1: Any?, cell2: Any?, vararg cells: Any?, init: CellBuilder.() -> Unit = {}) { cell(cell1, init) cell(cell2, init) cellsFrom(cells.asList(), init) } /** Add all [cells] from an iterable to this row */ fun cellsFrom(cells: Iterable<Any?>, init: CellBuilder.() -> Unit = {}) { cells.mapTo(this.cells) { CellBuilder(getWidget(it)).apply(init) } } /** Add a cell to this row. * * The [content] can be a [Widget] to render, or any other type of object which will be * converted to a string. */ fun cell(content: Any?, init: CellBuilder.() -> Unit = {}) { cells += CellBuilder(getWidget(content)).apply(init) } } @MordantDsl class CellBuilder internal constructor( internal val content: Widget = Text(""), ) : CellStyleBuilder by CellStyleBuilderMixin() { /** * Set the number of columns that this cell should span. The value will be truncated to the width of the table. */ var columnSpan = 1 set(value) { require(value > 0) { "Column span must be greater than 0" } field = value } /** * Set the number of rows that this cell should span. */ var rowSpan = 1 set(value) { require(value > 0) { "Row span must be greater than 0" } field = value } } /** * Build a table widget. * * Tables have three optional sections: the [header][TableBuilder.header], the * [body][TableBuilder.body], and the [footer][TableBuilder.footer]. * * Within each section, you can add entire [rows][SectionBuilder.row] of cells at once, or one at a * time with the [cell][RowBuilder.cell] builder. * * You can customize the table's styles at a number of levels, with more specific styles overriding * less specific styles. The places you can customize are, from least-specific to most-specific: * * 1. Table, applies to every cell * 2. Section, applies to all cells in the header, body, or footer * 3. Table Column, applies to all cells in a column * 4. Section Column, applies to all cells in a column for a single section * 5. Row, applies to all cells in a row * 6. Cell, applies to a single cell */ fun table(init: TableBuilder.() -> Unit): Table { val tableBuilder = TableBuilder().apply(init) val table = TableLayout(tableBuilder).buildTable() return when { tableBuilder.captionTop != null || tableBuilder.captionBottom != null -> { TableWithCaption( table, Caption(table, tableBuilder.captionTop, tableBuilder.captionBottom), ) } else -> table } } /** * Build a grid widget that can be used to lay out text and other widgets. * * This builder functions like a [table] builder, but has no sections and no borders. * * By default, there is one space between cells in a row. You can increase this by adding * [padding][TableBuilder.padding], or remove it by setting [borders][TableBuilder.borders] to * [NONE][Borders.NONE]. */ fun grid(init: GridBuilder.() -> Unit): Widget { return table { borders = Borders.LEFT_RIGHT outerBorder = false borderStyle = BorderStyle.BLANK padding = Padding.none() val gb = GridBuilder(bodySection) gb.init() columns.putAll(gb.columns) } } private fun getWidget(content: Any?): Widget { if (content is Widget) return content return when (val string = content.toString()) { "" -> EmptyWidget else -> Text(string) } } private fun <T : CellStyleBuilder> initColumn(columns: MutableMap<Int, T>, i: Int, def: T, init: T.() -> Unit) { require(i >= 0) { "column index cannot be negative" } var v = columns[i] if (v == null) { v = def columns[i] = v } v.init() }
0
null
0
0
da920ffee27d09e37331ac4dca3e41449811ee93
10,909
mordant
Apache License 2.0
src/main/kotlin/kool/fake constructors.kt
Wicpar
232,605,267
false
null
package kool import org.lwjgl.PointerBuffer import org.lwjgl.system.MemoryStack import org.lwjgl.system.MemoryUtil import org.lwjgl.system.Pointer import java.nio.* // typealias fun Buffer(size: Int): ByteBuffer = MemoryUtil.memCalloc(size) inline fun Buffer(size: Int, init: (Int) -> Byte) = Buffer(size).also { for (i in 0 until size) it[i] = init(i) } fun ByteBuffer(size: Int): ByteBuffer = MemoryUtil.memCalloc(size) inline fun ByteBuffer(size: Int, init: (Int) -> Byte) = ByteBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun ShortBuffer(size: Int): ShortBuffer = MemoryUtil.memCallocShort(size) inline fun ShortBuffer(size: Int, init: (Int) -> Short) = ShortBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun IntBuffer(size: Int): IntBuffer = MemoryUtil.memCallocInt(size) inline fun IntBuffer(size: Int, init: (Int) -> Int) = IntBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun LongBuffer(size: Int): LongBuffer = MemoryUtil.memCallocLong(size) inline fun LongBuffer(size: Int, init: (Int) -> Long) = LongBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun FloatBuffer(size: Int): FloatBuffer = MemoryUtil.memCallocFloat(size) inline fun FloatBuffer(size: Int, init: (Int) -> Float) = FloatBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun DoubleBuffer(size: Int): DoubleBuffer = MemoryUtil.memCallocDouble(size) inline fun DoubleBuffer(size: Int, init: (Int) -> Double) = DoubleBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun PointerBuffer(size: Int): PointerBuffer = MemoryUtil.memCallocPointer(size) inline fun PointerBuffer(size: Int, init: (Int) -> Adr) = PointerBuffer(size).also { for (i in 0 until size) it[i] = init(i) } // MemoryStack version fun MemoryStack.Buffer(size: Int): ByteBuffer = calloc(size) inline fun MemoryStack.Buffer(size: Int, init: (Int) -> Byte) = Buffer(size).also { for (i in 0 until size) it[i] = init(i) } fun MemoryStack.ByteBuffer(size: Int): ByteBuffer = calloc(size) inline fun MemoryStack.ByteBuffer(size: Int, init: (Int) -> Byte) = ByteBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun MemoryStack.ShortBuffer(size: Int): ShortBuffer = callocShort(size) inline fun MemoryStack.ShortBuffer(size: Int, init: (Int) -> Short) = ShortBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun MemoryStack.IntBuffer(size: Int): IntBuffer = callocInt(size) inline fun MemoryStack.IntBuffer(size: Int, init: (Int) -> Int)= IntBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun MemoryStack.LongBuffer(size: Int): LongBuffer = mallocLong(size) inline fun MemoryStack.LongBuffer(size: Int, init: (Int) -> Long)= LongBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun MemoryStack.FloatBuffer(size: Int): FloatBuffer = callocFloat(size) inline fun MemoryStack.FloatBuffer(size: Int, init: (Int) -> Float) = FloatBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun MemoryStack.DoubleBuffer(size: Int): DoubleBuffer = callocDouble(size) inline fun MemoryStack.DoubleBuffer(size: Int, init: (Int) -> Double)= DoubleBuffer(size).also { for (i in 0 until size) it[i] = init(i) } fun MemoryStack.PointerBuffer(size: Int): PointerBuffer = callocPointer(size) inline fun MemoryStack.PointerBuffer(size: Int, init: (Int) -> Adr)= PointerBuffer(size).also { for (i in 0 until size) it[i] = init(i) } inline fun MemoryStack.PointerBufferP(size: Int, init: (Int) -> Pointer)= PointerBuffer(size).also { for (i in 0 until size) it[i] = init(i) } inline fun MemoryStack.PointerBufferB(size: Int, init: (Int) -> Buffer)= PointerBuffer(size).also { for (i in 0 until size) it[i] = init(i) } @JvmName("PointerBufferSafe") fun MemoryStack.PointerBuffer(strings: Collection<String>?): PointerBuffer? = strings?.let { PointerBuffer(it) } fun MemoryStack.PointerBuffer(strings: Collection<String>): PointerBuffer = PointerBuffer(strings.size) { i -> val string = strings.elementAt(i) val length = MemoryUtil.memLengthUTF8(string, true) nmalloc(1, length).also { encodeUTF8(string, true, it) } } @JvmName("PointerAdrSafe") fun MemoryStack.PointerAdr(strings: Collection<String>?): Adr = strings?.let { PointerAdr(it) } ?: MemoryUtil.NULL fun MemoryStack.PointerAdr(strings: Collection<String>): Adr = PointerAdr(strings.size) { i -> val string = strings.elementAt(i) val length = MemoryUtil.memLengthUTF8(string, true) nmalloc(1, length).also { encodeUTF8(string, true, it) } } inline fun MemoryStack.PointerAdr(size: Int, init: (Int) -> Adr): Adr { val bytes = size * Pointer.POINTER_SIZE val address = nmalloc(Pointer.POINTER_SIZE, bytes) MemoryUtil.memSet(address, 0, bytes.toLong()) for (i in 0 until size) MemoryUtil.memPutAddress(address + i * Pointer.POINTER_SIZE, init(i)) return address }
1
null
1
1
346450ea62aa3bb4dc397f23b538f2f08aa4139f
4,939
kool
MIT License
features/utils/src/main/kotlin/br/com/mob1st/features/utils/observability/TrackEventSideEffect.kt
mob1st
526,655,668
false
{"Kotlin": 616109, "Shell": 1558}
package br.com.mob1st.features.utils.observability import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import br.com.mob1st.core.observability.events.AnalyticsEvent /** * Allows event tracking inside a composable context. * It wraps the event report into a side effect to avoid triggering after recompositions. * @param event The event to be tracked. */ @Composable fun TrackEventSideEffect( event: AnalyticsEvent, ) { val analyticsReporter = LocalAnalyticsReporter.current SideEffect { analyticsReporter.report(event) } }
11
Kotlin
0
3
d3f7e689dec83b4417bc39458c99981ad9d4d86f
587
bet-app-android
Apache License 2.0
archive/src/main/kotlin/org/openrs2/archive/key/KeyReader.kt
openrs2
315,027,372
false
null
package org.openrs2.archive.key import org.openrs2.crypto.XteaKey import java.io.InputStream public interface KeyReader { public fun read(input: InputStream): Sequence<XteaKey> }
0
Kotlin
2
8
12eba96055ba13e8a8e3ec0ad3be7d93b3dd5b1b
185
openrs2
ISC License
form/src/main/java/com/thejuki/kformmaster/model/FormPickerMultiCheckBoxElement.kt
uiiang
136,555,330
true
{"Kotlin": 361772, "Java": 12108}
package com.thejuki.kformmaster.model import android.content.Context import android.support.v7.app.AlertDialog import android.support.v7.widget.AppCompatEditText import android.view.View import com.thejuki.kformmaster.R import com.thejuki.kformmaster.helper.FormBuildHelper /** * Form Picker MultiCheckBox Element * * Form element for AppCompatEditText (which on click opens a MultiCheckBox dialog) * * @author **TheJuki** ([GitHub](https://github.com/TheJuki)) * @version 1.0 */ class FormPickerMultiCheckBoxElement<T : List<*>>(tag: Int = -1) : FormPickerElement<T>(tag) { override val isValid: Boolean get() = !required || (value != null && value?.isEmpty() == false) override fun clear() { super.clear() reInitDialog() } /** * Form Element Options */ var options: T? = null set(value) { field = value reInitDialog() } /** * Alert Dialog Builder * Used to call reInitDialog without needing context again. */ private var alertDialogBuilder: AlertDialog.Builder? = null /** * Options builder setter */ fun setOptions(options: T): BaseFormElement<T> { this.options = options return this } /** * Alert Dialog Title * (optional - uses R.string.form_master_pick_one_or_more) */ var dialogTitle: String? = null /** * dialogTitle builder setter */ fun setDialogTitle(dialogTitle: String?): FormPickerMultiCheckBoxElement<T> { this.dialogTitle = dialogTitle return this } /** * Re-initializes the dialog * Should be called after the options list changes */ fun reInitDialog(context: Context? = null, formBuilder: FormBuildHelper? = null) { // reformat the options in format needed val options = arrayOfNulls<CharSequence>(this.options?.size ?: 0) val optionsSelected = BooleanArray(this.options?.size ?: 0) val mSelectedItems = ArrayList<Int>() this.options?.let { for (i in it.indices) { val obj = it[i] options[i] = obj.toString() optionsSelected[i] = false if (this.value?.contains(obj) == true) { optionsSelected[i] = true mSelectedItems.add(i) } } } var selectedItems = "" for (i in mSelectedItems.indices) { selectedItems += options[mSelectedItems[i]] if (i < mSelectedItems.size - 1) { selectedItems += ", " } } val editTextView = this.editView as? AppCompatEditText editTextView?.setText(getSelectedItemsText()) if (alertDialogBuilder == null && context != null) { alertDialogBuilder = AlertDialog.Builder(context) if (this.dialogTitle == null) { this.dialogTitle = context.getString(R.string.form_master_pick_one_or_more) } } alertDialogBuilder?.let { it.setTitle(this.dialogTitle) .setMultiChoiceItems(options, optionsSelected) { _, which, isChecked -> if (isChecked) { // If the user checked the item, add it to the selected items mSelectedItems.add(which) } else if (mSelectedItems.contains(which)) { // Else, if the item is already in the array, remove it mSelectedItems.remove(which) } } // Set the action buttons .setPositiveButton(android.R.string.ok) { _, _ -> this.options?.let { val selectedOptions = mSelectedItems.indices .map { mSelectedItems[it] } .map { x -> it[x] } this.setValue(selectedOptions) this.error = null formBuilder?.onValueChanged(this) editTextView?.setText(getSelectedItemsText()) } } .setNegativeButton(android.R.string.cancel) { _, _ -> } val alertDialog = it.create() // display the dialog on click val listener = View.OnClickListener { alertDialog.show() } itemView?.setOnClickListener(listener) editTextView?.setOnClickListener(listener) } } private fun getSelectedItemsText(): String { val options = arrayOfNulls<CharSequence>(this.options?.size ?: 0) val optionsSelected = BooleanArray(this.options?.size ?: 0) val mSelectedItems = ArrayList<Int>() this.options?.let { for (i in it.indices) { val obj = it[i] options[i] = obj.toString() optionsSelected[i] = false if (this.value?.contains(obj) == true) { optionsSelected[i] = true mSelectedItems.add(i) } } } var selectedItems = "" for (i in mSelectedItems.indices) { selectedItems += options[mSelectedItems[i]] if (i < mSelectedItems.size - 1) { selectedItems += ", " } } return selectedItems } }
0
Kotlin
0
1
3b2c828e4fd07af8dc7cd756d5430956d2a0977b
5,576
KFormMaster
Apache License 2.0
app/src/main/java/com/ead/project/dreamer/app/data/util/system/ElementsExtensions.kt
darkryh
490,353,600
false
{"Kotlin": 770587, "Java": 2316}
package com.ead.project.dreamer.app.data.util.system import org.jsoup.nodes.Element import org.jsoup.select.Elements fun Elements.getCatch(index : Int) : Element { return try { this[index] } catch (e : IndexOutOfBoundsException) { Element("null") } }
0
Kotlin
1
2
663d95183b771f7ab7da8d54793314ad5d5811b4
280
Dreamer
MIT License
server/src/main/kotlin/fi/vauhtijuoksu/vauhtijuoksuapi/server/impl/base/DeleteRouter.kt
Vauhtijuoksu
394,707,727
false
{"Kotlin": 374473, "Smarty": 2566, "Dockerfile": 173, "Shell": 106}
package fi.vauhtijuoksu.vauhtijuoksuapi.server.impl.base import fi.vauhtijuoksu.vauhtijuoksuapi.database.api.VauhtijuoksuDatabase import fi.vauhtijuoksu.vauhtijuoksuapi.exceptions.UserError import fi.vauhtijuoksu.vauhtijuoksuapi.models.Model import fi.vauhtijuoksu.vauhtijuoksuapi.server.ApiConstants import fi.vauhtijuoksu.vauhtijuoksuapi.server.api.PartialRouter import io.vertx.ext.web.Router import io.vertx.ext.web.handler.AuthenticationHandler import io.vertx.ext.web.handler.AuthorizationHandler import io.vertx.ext.web.handler.CorsHandler import java.util.UUID open class DeleteRouter<M : Model>( private val authenticationHandler: AuthenticationHandler, private val adminRequired: AuthorizationHandler, private val authenticatedEndpointCorsHandler: CorsHandler, private val db: VauhtijuoksuDatabase<M>, ) : PartialRouter { override fun configure(router: Router, basepath: String) { router.delete("$basepath/:id") .handler(authenticatedEndpointCorsHandler) .handler(authenticationHandler) .handler(adminRequired) .handler { ctx -> val id: UUID try { id = UUID.fromString(ctx.pathParam("id")) } catch (_: IllegalArgumentException) { throw UserError("Not UUID: ${ctx.pathParam("id")}") } db.delete(id) .onFailure(ctx::fail) .onSuccess { ctx.response().setStatusCode(ApiConstants.NO_CONTENT).end() } } } }
8
Kotlin
0
3
177cd5f19794fc3b7fbff8439070762753896168
1,565
vauhtijuoksu-api
MIT License
app/src/main/java/io/github/takusan23/Kaisendon/TootCardView.kt
takusan23
161,504,060
false
null
package io.github.takusan23.Kaisendon import android.Manifest import android.app.DatePickerDialog import android.app.TimePickerDialog import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.graphics.PorterDuff import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.net.Uri import android.os.BatteryManager import android.os.Build import android.provider.MediaStore import android.text.Editable import android.text.Html import android.text.TextWatcher import android.view.* import android.view.animation.Animation import android.view.animation.AnimationUtils import android.view.inputmethod.InputMethodManager import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.menu.MenuBuilder import androidx.appcompat.view.menu.MenuPopupHelper import androidx.cardview.widget.CardView import androidx.core.content.ContextCompat import androidx.interpolator.view.animation.FastOutSlowInInterpolator import androidx.interpolator.view.animation.LinearOutSlowInInterpolator import androidx.preference.PreferenceManager import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.google.android.material.snackbar.Snackbar import com.squareup.picasso.Picasso import com.sys1yagi.mastodon4j.api.entity.Card import io.github.takusan23.Kaisendon.APIJSONParse.GlideSupport import io.github.takusan23.Kaisendon.CustomMenu.CustomMenuTimeLine import io.github.takusan23.Kaisendon.CustomMenu.Dialog.AccountChangeBottomSheetFragment import io.github.takusan23.Kaisendon.CustomMenu.Dialog.MisskeyDriveBottomDialog import io.github.takusan23.Kaisendon.CustomMenu.UriToByte import io.github.takusan23.Kaisendon.Omake.ShinchokuLayout import io.github.takusan23.Kaisendon.PaintPOST.PaintPOSTActivity import kotlinx.android.synthetic.main.activity_toot.view.* import kotlinx.android.synthetic.main.carview_toot_layout.view.* import kotlinx.android.synthetic.main.toot_vote_layout.view.* import okhttp3.* import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.io.File import java.io.IOException import java.net.URI import java.util.* import kotlin.concurrent.timerTask class TootCardView(val context: Context, val isMisskey: Boolean) { val linearLayout = LinearLayout(context) lateinit var cardView: CardView val pref_setting = PreferenceManager.getDefaultSharedPreferences(context) //添付画像 val attachMediaList = arrayListOf<Uri>() //画像アップロードして出来たIDを入れる配列 val postMediaList = arrayListOf<String>() //公開範囲 var mastodonVisibility = "public" var misskeyVisibility = "public" //予約投稿 var isScheduledPOST = false var scheduledDate = "" var scheduledTime = "" //アンケート var isVotePOST = false lateinit var tootEditText: TextView var isShow = false //オマケ機能 val shinchokuLayout = ShinchokuLayout(context) init { init() } fun init() { //初期化 val laytoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater laytoutInflater.inflate(R.layout.carview_toot_layout, linearLayout) tootEditText = linearLayout.toot_card_textinput cardView = linearLayout.toot_card_parent_cardview cardView.visibility = View.GONE setClickEvent() //Misskey/Mastodon if (isMisskey) { getMisskeyAccount() linearLayout.toot_card_vote_button.visibility = View.GONE linearLayout.toot_card_time_button.visibility = View.GONE linearLayout.toot_card_misskey_drive.visibility = View.VISIBLE } else { getAccount() linearLayout.toot_card_misskey_drive.visibility = View.GONE linearLayout.toot_card_vote_button.visibility = View.VISIBLE linearLayout.toot_card_time_button.visibility = View.VISIBLE } setTextLengthCount() setOmake() } //アカウント切り替えボタン。デスクトップモード利用時に投稿できないので fun showAccountChangeBottomFragment() { val accountChangeBottomSheetFragment = AccountChangeBottomSheetFragment() accountChangeBottomSheetFragment.show((context as AppCompatActivity).supportFragmentManager, "account_change") } //おまけきのう private fun setOmake() { if (pref_setting.getBoolean("life_mode", false) && !isMisskey) { val sinchokuLL = shinchokuLayout.layout linearLayout.toot_cardview_progress.removeAllViews() linearLayout.toot_cardview_progress.addView(sinchokuLL) } } fun cardViewShow() { //表示アニメーションつける val showAnimation = AnimationUtils.loadAnimation(context, R.anim.tootcard_show_animation); //Visibility変更 showAnimation.interpolator = FastOutSlowInInterpolator() cardView.startAnimation(showAnimation) cardView.visibility = View.VISIBLE isShow = true } fun cardViewHide() { //非表示アニメーションつける val hideAnimation = AnimationUtils.loadAnimation(context, R.anim.tootcard_hide_animation); hideAnimation.interpolator = LinearOutSlowInInterpolator() cardView.startAnimation(hideAnimation) Timer().schedule(timerTask { cardView.post { cardView.visibility = View.GONE } this.cancel() }, 500) //非表示 isShow = false } fun setClickEvent() { linearLayout.toot_card_attach_image.setOnClickListener { setAttachImage() } linearLayout.toot_card_device_button.setOnClickListener { showDeviceInfo() } linearLayout.toot_card_visibility_button.setOnClickListener { showVisibility() } linearLayout.toot_card_vote_button.setOnClickListener { showVote() } linearLayout.toot_card_time_button.setOnClickListener { showScheduled() } linearLayout.toot_card_paint_post_button.setOnClickListener { showPaint() } linearLayout.toot_card_post_button.setOnClickListener { postStatus() } linearLayout.toot_card_account_change_button.setOnClickListener { showAccountChangeBottomFragment() } //Misskeyドライブ linearLayout.toot_card_misskey_drive.setOnClickListener { showMisskeyDrive() } } //文字数カウント fun setTextLengthCount() { linearLayout.toot_card_textinput.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) { } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { //文字数 if (p0?.length ?: 0 < 0) { val text = "${p0?.length ?: 0}/500 ${context.getString(R.string.toot_text)}" linearLayout.toot_card_post_button.text = text } else { linearLayout.toot_card_post_button.text = context.getString(R.string.toot_text) } } }) } private fun showMisskeyDrive() { //Misskey Drive API を叩く val dialogFragment = MisskeyDriveBottomDialog() dialogFragment.show((context as AppCompatActivity).supportFragmentManager, "misskey_drive_dialog") } fun setAttachImage() { //キーボード隠す closeKeyboard() val REQUEST_PERMISSION = 1000 //onActivityResultで受け取れる val photoPickerIntent = Intent(Intent.ACTION_PICK) photoPickerIntent.type = "image/*" (context as AppCompatActivity).startActivityForResult(photoPickerIntent, 1) } fun showVisibility() { if (isMisskey) { showMisskeyVisibilityMenu() } else { showMastodonVisibilityMenu() } } fun showDeviceInfo() { val view = linearLayout.toot_card_device_button //ポップアップメニュー作成 val device_menuBuilder = MenuBuilder(context) val device_inflater = MenuInflater(context) device_inflater.inflate(R.menu.device_info_menu, device_menuBuilder) val device_optionsMenu = MenuPopupHelper(context, device_menuBuilder, view) device_optionsMenu.setForceShowIcon(true) //コードネーム変換(手動 var codeName = "" when (Build.VERSION.SDK_INT) { Build.VERSION_CODES.N -> { codeName = "Nougat" } Build.VERSION_CODES.O -> { codeName = "Oreo" } Build.VERSION_CODES.P -> { codeName = "Pie" } Build.VERSION_CODES.Q -> { codeName = "10" } } device_optionsMenu.show() val bm = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager device_menuBuilder.setCallback(object : MenuBuilder.Callback { override fun onMenuItemSelected(menuBuilder: MenuBuilder, menuItem: MenuItem): Boolean { //名前 if (menuItem.title.toString().contains(context.getString(R.string.device_name))) { tootEditText.append(Build.MODEL) tootEditText.append("\r\n") } //Androidバージョン if (menuItem.title.toString().contains(context.getString(R.string.android_version))) { tootEditText.append(Build.VERSION.RELEASE) tootEditText.append("\r\n") } //めーかー if (menuItem.title.toString().contains(context.getString(R.string.maker))) { tootEditText.append(Build.BRAND) tootEditText.append("\r\n") } //SDKバージョン if (menuItem.title.toString().contains(context.getString(R.string.sdk_version))) { tootEditText.append(Build.VERSION.SDK_INT.toString()) tootEditText.append("\r\n") } //コードネーム if (menuItem.title.toString().contains(context.getString(R.string.codename))) { tootEditText.append(codeName) tootEditText.append("\r\n") } //バッテリーレベル if (menuItem.title.toString().contains(context.getString(R.string.battery_level))) { tootEditText.append(bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).toString() + "%") tootEditText.append("\r\n") } return false } override fun onMenuModeChange(menuBuilder: MenuBuilder) { } }) } fun showScheduled() { if (linearLayout.toot_card_scheduled_linearlayout.visibility == View.GONE) { isScheduledPOST = true linearLayout.toot_card_scheduled_linearlayout.visibility = View.VISIBLE } else { isScheduledPOST = false linearLayout.toot_card_scheduled_linearlayout.visibility = View.GONE } linearLayout.toot_card_scheduled_time_button.setOnClickListener { //時間ピッカー showTimePicker(linearLayout.toot_card_scheduled_time_textview) } linearLayout.toot_card_scheduled_date_button.setOnClickListener { //日付ピッカー showDatePicker(linearLayout.toot_card_scheduled_date_textview) } } fun showVote() { if (linearLayout.toot_card_vote_linearlayout.visibility == View.GONE) { isVotePOST = true linearLayout.toot_card_vote_linearlayout.visibility = View.VISIBLE } else { isVotePOST = false linearLayout.toot_card_vote_linearlayout.visibility = View.GONE } } fun showPaint() { //キーボード隠す closeKeyboard() //開発中メッセージ val dialog = AlertDialog.Builder(context) .setTitle(context.getString(R.string.paintPost)) .setMessage(context.getString(R.string.paint_post_description)) .setPositiveButton(context.getString(R.string.open_painit_post)) { dialogInterface, i -> //お絵かきアクティビティへ移動 val intent = Intent(context, PaintPOSTActivity::class.java) context.startActivity(intent) } .setNegativeButton(context.getString(R.string.cancel), null) .show() //https://stackoverflow.com/questions/9467026/changing-position-of-the-dialog-on-screen-android val window = dialog.window val layoutParams = window?.attributes layoutParams?.gravity = Gravity.BOTTOM layoutParams?.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND window?.attributes = layoutParams } fun postStatus() { //感触フィードバックをつける? if (pref_setting.getBoolean("pref_post_haptics", false)) { linearLayout.toot_card_paint_post_button.performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK) } if (attachMediaList.isEmpty()) { //画像投稿無し //文字数チェック if (linearLayout.toot_card_textinput.text?.length ?: 0 > 0) { //時間指定投稿 val message: String if (isScheduledPOST) { message = context.getString(R.string.time_post_post_button) } else { message = context.getString(R.string.note_create_message) } //Tootする //確認SnackBer Snackbar.make(linearLayout.toot_card_textinput, message, Snackbar.LENGTH_SHORT).setAction(R.string.toot_text) { //Mastodon / Misskey if (isMisskey) { misskeyNoteCreatePOST() } else { mastodonStatusesPOST() } }.setAnchorView(linearLayout.toot_card_post_button).show() } } else { //画像アップロードから attachMediaList.forEach { if (isMisskey) { uploadDrivePhoto(it) } else { uploadMastodonPhoto(it) } } } } /** * Mastodon 画像POST */ private fun uploadMastodonPhoto(uri: Uri) { val AccessToken = pref_setting.getString("main_token", "") val Instance = pref_setting.getString("main_instance", "") //えんどぽいんと val url = "https://$Instance/api/v1/media/" //ぱらめーたー val requestBody = MultipartBody.Builder() requestBody.setType(MultipartBody.FORM) //requestBody.addFormDataPart("file", file_post.getName(), RequestBody.create(MediaType.parse("image/" + file_extn_post), file_post)); requestBody.addFormDataPart("access_token", AccessToken!!) //くるくる SnackberProgress.showProgressSnackber(linearLayout.toot_card_textinput, context, context.getString(R.string.loading) + "\n" + url) //Android Qで動かないのでUriからバイトに変換してPOSTしてます //重いから非同期処理 Thread(Runnable { val uri_byte = UriToByte(context); try { // file:// と content:// でわける if (uri.scheme?.contains("file") == true) { val file_name = getFileSchemeFileName(uri) val extn = getFileSchemeFileExtension(uri) requestBody.addFormDataPart("file", file_name, RequestBody.create(MediaType.parse("image/" + extn!!), uri_byte.getByte(uri))) } else { val file_name = getFileNameUri(uri) val extn = context.contentResolver.getType(uri) requestBody.addFormDataPart("file", file_name, RequestBody.create(MediaType.parse("image/" + extn!!), uri_byte.getByte(uri))) } } catch (e: IOException) { e.printStackTrace() } //じゅんび val request = Request.Builder() .url(url) .post(requestBody.build()) .build() //画像Upload val okHttpClient = OkHttpClient() //POST実行 okHttpClient.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { //失敗 e.printStackTrace() (context as AppCompatActivity).runOnUiThread { Toast.makeText(context, context.getString(R.string.error), Toast.LENGTH_SHORT).show() } } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() //System.out.println("画像POST : " + response_string); if (!response.isSuccessful) { //失敗 (context as AppCompatActivity).runOnUiThread { Toast.makeText(context, context.getString(R.string.error) + "\n" + response.code().toString(), Toast.LENGTH_SHORT).show() } } else { try { val jsonObject = JSONObject(response_string) val media_id_long = jsonObject.getString("id") //配列に格納 postMediaList.add(media_id_long) //確認SnackBer //数確認 if (postMediaList.size == attachMediaList.size) { Snackbar.make(linearLayout.toot_card_textinput, R.string.note_create_message, Snackbar.LENGTH_INDEFINITE).setAction(R.string.toot_text) { mastodonStatusesPOST() }.show() } } catch (e: JSONException) { e.printStackTrace() } } } }) }).start() } /** * Misskey 画像POST */ private fun uploadDrivePhoto(uri: Uri) { val instance = pref_setting.getString("misskey_main_instance", "") val token = pref_setting.getString("misskey_main_token", "") val username = pref_setting.getString("misskey_main_username", "") val url = "https://$instance/api/drive/files/create" //くるくる SnackberProgress.showProgressSnackber(linearLayout.toot_card_textinput, context, context.getString(R.string.loading) + "\n" + url) //ぱらめーたー val requestBody = MultipartBody.Builder() requestBody.setType(MultipartBody.FORM) //requestBody.addFormDataPart("file", file_post.getName(), RequestBody.create(MediaType.parse("image/" + file_extn_post), file_post)); requestBody.addFormDataPart("i", token!!) requestBody.addFormDataPart("force", "true") //Android Qで動かないのでUriからBitmap変換してそれをバイトに変換してPOSTしてます //お絵かき投稿Misskey対応? //重いから非同期処理 Thread(Runnable { val uri_byte = UriToByte(context); try { // file:// と content:// でわける if (uri.scheme?.contains("file") == true) { val file_name = getFileSchemeFileName(uri) val extn = getFileSchemeFileExtension(uri) requestBody.addFormDataPart("file", file_name, RequestBody.create(MediaType.parse("image/" + extn!!), uri_byte.getByte(uri))) } else { val file_name = getFileNameUri(uri) val extn = context.contentResolver.getType(uri) requestBody.addFormDataPart("file", file_name, RequestBody.create(MediaType.parse("image/" + extn!!), uri_byte.getByte(uri))) } } catch (e: IOException) { e.printStackTrace() } //じゅんび val request = Request.Builder() .url(url) .post(requestBody.build()) .build() //画像Upload val okHttpClient = OkHttpClient() //POST実行 okHttpClient.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { //失敗 e.printStackTrace() (context as AppCompatActivity).runOnUiThread { Toast.makeText(context, context.getString(R.string.error), Toast.LENGTH_SHORT).show() } } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() //System.out.println("画像POST : " + response_string); if (!response.isSuccessful) { //失敗 (context as AppCompatActivity).runOnUiThread { Toast.makeText(context, context.getString(R.string.error) + "\n" + response.code().toString(), Toast.LENGTH_SHORT).show() } } else { try { val jsonObject = JSONObject(response_string) val media_id_long = jsonObject.getString("id") //配列に格納 postMediaList.add(media_id_long) //確認SnackBer //数確認 if (postMediaList.size == attachMediaList.size) { Snackbar.make(linearLayout.toot_card_textinput, R.string.note_create_message, Snackbar.LENGTH_INDEFINITE).setAction(R.string.toot_text) { misskeyNoteCreatePOST() }.show() } } catch (e: JSONException) { e.printStackTrace() } } } }) }).start() } /** * Uri→FileName */ private fun getFileNameUri(uri: Uri): String? { var file_name: String? = null val projection = arrayOf(MediaStore.MediaColumns.DISPLAY_NAME) val cursor = context.contentResolver.query(uri, projection, null, null, null) if (cursor != null) { if (cursor.moveToFirst()) { file_name = cursor.getString(0) } } return file_name } /* * Uri→FileName * Fileスキーム限定 * */ fun getFileSchemeFileName(uri: Uri): String? { //file://なので使える val file = File(uri.path) return file.name } /* * Uri→Extension * 拡張子取得。Kotlinだと楽だね! * */ fun getFileSchemeFileExtension(uri: Uri): String? { val file = File(uri.path) return file.extension } private fun mastodonStatusesPOST() { val AccessToken = pref_setting.getString("main_token", "") val Instance = pref_setting.getString("main_instance", "") val url = "https://$Instance/api/v1/statuses/?access_token=$AccessToken" val jsonObject = JSONObject() try { jsonObject.put("status", linearLayout.toot_card_textinput.text.toString()) jsonObject.put("visibility", mastodonVisibility) //時間指定 if (linearLayout.toot_card_scheduled_switch.isChecked) { //System.out.println(post_date + "/" + post_time); //nullCheck if (scheduledDate.isNotEmpty() && scheduledTime.isNotEmpty()) { jsonObject.put("scheduled_at", scheduledDate + scheduledTime) } } //画像 if (postMediaList.size != 0) { val media = JSONArray() for (i in postMediaList) { media.put(i) } jsonObject.put("media_ids", media) } //投票機能 if (isVotePOST) { jsonObject.put("poll", createMastodonVote()) } } catch (e: JSONException) { e.printStackTrace() } val requestBody_json = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString()) val request = Request.Builder() .url(url) .post(requestBody_json) .build() //POST val client = OkHttpClient() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() (context as AppCompatActivity).runOnUiThread { Toast.makeText(context, context.getString(R.string.error), Toast.LENGTH_SHORT).show() } } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() if (!response.isSuccessful) { //失敗 (context as AppCompatActivity).runOnUiThread { Toast.makeText(context, context.getString(R.string.error) + "\n" + response.code().toString(), Toast.LENGTH_SHORT).show() } } else { (context as AppCompatActivity).runOnUiThread { //予約投稿・通常投稿でトースト切り替え if (linearLayout.toot_card_scheduled_switch.isChecked) { linearLayout.toot_card_scheduled_switch.isChecked = false Toast.makeText(context, context.getString(R.string.time_post_ok), Toast.LENGTH_SHORT).show() //予約投稿を無効化 isScheduledPOST = false } else { Toast.makeText(context, context.getString(R.string.toot_ok), Toast.LENGTH_SHORT).show() } //投票 if (isVotePOST) { isVotePOST = false linearLayout.toot_card_vote_use_switch.isChecked = false } //EditTextを空にする linearLayout.toot_card_textinput.setText("") //tootTextCount = 0 //TootCard閉じる cardViewHide() //共有ちぇっく if (context is Home) { attachMediaList.forEach { (context as Home).tmpOkekakiList.add(it.path ?: "") } val intent = (context as Home).intent val action_string = intent.action if (Intent.ACTION_SEND == action_string) { val extras = intent.extras if (extras != null) { //URL var text = extras.getCharSequence(Intent.EXTRA_TEXT) context.shareText = text.toString() } } } //配列を空にする attachMediaList.clear() Home.post_media_id.clear() linearLayout.toot_card_attach_linearlayout.removeAllViews() //目標更新 shinchokuLayout.setTootChallenge() //JSONParseしてトゥート数変更する val jsonObject = JSONObject(response_string) if (jsonObject.has("account")) { val toot_count = jsonObject.getJSONObject("account").getInt("statuses_count").toString() shinchokuLayout.setStatusProgress(toot_count) } } } } }) } private fun misskeyNoteCreatePOST() { val instance = pref_setting.getString("misskey_main_instance", "") val token = pref_setting.getString("misskey_main_token", "") val username = pref_setting.getString("misskey_main_username", "") val url = "https://$instance/api/notes/create" val jsonObject = JSONObject() try { jsonObject.put("i", token) jsonObject.put("visibility", misskeyVisibility) jsonObject.put("text", linearLayout.toot_card_textinput.text.toString()) jsonObject.put("viaMobile", true)//スマホからなので一応 //添付メディア if (postMediaList.size >= 1) { val jsonArray = JSONArray() for (i in postMediaList) { jsonArray.put(i) } jsonObject.put("fileIds", jsonArray) } } catch (e: JSONException) { e.printStackTrace() } //System.out.println(jsonObject.toString()); val requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString()) //作成 val request = Request.Builder() .url(url) .post(requestBody) .build() //GETリクエスト val client = OkHttpClient() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() (context as AppCompatActivity).runOnUiThread { Toast.makeText(context, context.getString(R.string.error), Toast.LENGTH_SHORT).show() } } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() //System.out.println(response_string); if (!response.isSuccessful) { //失敗 (context as AppCompatActivity).runOnUiThread { Toast.makeText(context, context.getString(R.string.error) + "\n" + response.code().toString(), Toast.LENGTH_SHORT).show() } } else { (context as AppCompatActivity).runOnUiThread { //EditTextを空にする linearLayout.toot_card_textinput.setText("") //tootTextCount = 0 //TootCard閉じる cardView.visibility = View.GONE //配列を空にする //共有ちぇっく if (context is Home) { attachMediaList.forEach { (context as Home).tmpOkekakiList.add(it.path ?: "") } } attachMediaList.clear() postMediaList.clear() linearLayout.toot_card_attach_linearlayout.removeAllViews() } } } }) } /** * DatePicker */ private fun showDatePicker(textView: TextView) { val date = arrayOf("") val calendar = Calendar.getInstance() val dateBuilder = DatePickerDialog(context, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth -> var month = month var month_string = "" var day_string = "" //1-9月は前に0を入れる if (month++ <= 9) { month_string = "0" + month++.toString() } else { month_string = month++.toString() } //1-9日も前に0を入れる if (dayOfMonth <= 9) { day_string = "0$dayOfMonth" } else { day_string = dayOfMonth.toString() } scheduledDate = year.toString() + month_string + day_string + "T" textView.text = year.toString() + month_string + day_string + "T" }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) ) dateBuilder.show() } /** * TimePicker */ private fun showTimePicker(textView: TextView) { val calendar = Calendar.getInstance() val hour = calendar.get(Calendar.HOUR_OF_DAY) val minute = calendar.get(Calendar.MINUTE) val dialog = TimePickerDialog(context, TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute -> var hourOfDay = hourOfDay var hour_string = "" var minute_string = "" //1-9月は前に0を入れる if (hourOfDay <= 9) { hour_string = "0" + hourOfDay++.toString() } else { hour_string = hourOfDay++.toString() } //1-9日も前に0を入れる if (minute <= 9) { minute_string = "0$minute" } else { minute_string = minute.toString() } scheduledTime = hour_string + minute_string + "00" + "+0900" textView.text = hour_string + minute_string + "00" + "+0900" }, hour, minute, true) dialog.show() } fun closeKeyboard() { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if ((context as AppCompatActivity).currentFocus != null) { imm.hideSoftInputFromWindow(context.currentFocus!!.windowToken, 0) } } fun showMastodonVisibilityMenu() { //ポップアップメニュー作成 val menuBuilder = MenuBuilder(context) val inflater = MenuInflater(context) inflater.inflate(R.menu.toot_area_menu, menuBuilder) val optionsMenu = MenuPopupHelper(context, menuBuilder, linearLayout.toot_card_visibility_button) optionsMenu.setForceShowIcon(true) //ポップアップメニューを展開する //表示 optionsMenu.show() //押したときの反応 menuBuilder.setCallback(object : MenuBuilder.Callback { override fun onMenuItemSelected(menuBuilder: MenuBuilder, menuItem: MenuItem): Boolean { //公開(全て) if (menuItem.title.toString().contains(context.getString(R.string.visibility_public))) { mastodonVisibility = "public" linearLayout.toot_card_visibility_button.setImageDrawable(context.getDrawable(R.drawable.ic_public_black_24dp)) } //未収載(TL公開なし・誰でも見れる) if (menuItem.title.toString().contains(context.getString(R.string.visibility_unlisted))) { mastodonVisibility = "unlisted" linearLayout.toot_card_visibility_button.setImageDrawable(context.getDrawable(R.drawable.ic_done_all_black_24dp)) } //非公開(フォロワー限定) if (menuItem.title.toString().contains(context.getString(R.string.visibility_private))) { mastodonVisibility = "private" linearLayout.toot_card_visibility_button.setImageDrawable(context.getDrawable(R.drawable.ic_lock_open_black_24dp)) } //ダイレクト(指定したアカウントと自分) if (menuItem.title.toString().contains(context.getString(R.string.visibility_direct))) { mastodonVisibility = "direct" linearLayout.toot_card_visibility_button.setImageDrawable(context.getDrawable(R.drawable.ic_assignment_ind_black_24dp)) } return false } override fun onMenuModeChange(menuBuilder: MenuBuilder) { } }) } fun showMisskeyVisibilityMenu() { //ポップアップメニュー作成 val menuBuilder = MenuBuilder(context) val inflater = MenuInflater(context) inflater.inflate(R.menu.misskey_visibility_menu, menuBuilder) val optionsMenu = MenuPopupHelper(context, menuBuilder, linearLayout.toot_card_visibility_button) optionsMenu.setForceShowIcon(true) //ポップアップメニューを展開する //表示 optionsMenu.show() //押したときの反応 menuBuilder.setCallback(object : MenuBuilder.Callback { override fun onMenuItemSelected(menuBuilder: MenuBuilder, menuItem: MenuItem): Boolean { //公開(全て) if (menuItem.title.toString().contains(context.getString(R.string.misskey_public))) { misskeyVisibility = "public" linearLayout.toot_card_visibility_button.setImageDrawable(context.getDrawable(R.drawable.ic_public_black_24dp)) } //ホーム if (menuItem.title.toString().contains(context.getString(R.string.misskey_home))) { misskeyVisibility = "home" linearLayout.toot_card_visibility_button.setImageDrawable(context.getDrawable(R.drawable.ic_home_black_24dp)) } //フォロワー限定 if (menuItem.title.toString().contains(context.getString(R.string.misskey_followers))) { misskeyVisibility = "followers" linearLayout.toot_card_visibility_button.setImageDrawable(context.getDrawable(R.drawable.ic_person_add_black_24dp)) } //ダイレクト(指定したアカウントと自分) if (menuItem.title.toString().contains(context.getString(R.string.misskey_specified))) { misskeyVisibility = "specified" linearLayout.toot_card_visibility_button.setImageDrawable(context.getDrawable(R.drawable.ic_assignment_ind_black_24dp)) } //公開(ローカルのみ) if (menuItem.title.toString().contains(context.getString(R.string.misskey_private))) { misskeyVisibility = "private" linearLayout.toot_card_visibility_button.setImageDrawable(context.getDrawable(R.drawable.ic_public_black_24dp)) } return false } override fun onMenuModeChange(menuBuilder: MenuBuilder) { } }) } fun createMastodonVote(): JSONObject { val `object` = JSONObject() try { //配列 val jsonArray = JSONArray() if (linearLayout.toot_card_vote_editText_1.text.toString() != null) { jsonArray.put(linearLayout.toot_card_vote_editText_1.text.toString()) } if (linearLayout.toot_card_vote_editText_2.text.toString() != null) { jsonArray.put(linearLayout.toot_card_vote_editText_2.text.toString()) } if (linearLayout.toot_card_vote_editText_3.text.toString() != null) { jsonArray.put(linearLayout.toot_card_vote_editText_3.text.toString()) } if (linearLayout.toot_card_vote_editText_4.text.toString() != null) { jsonArray.put(linearLayout.toot_card_vote_editText_4.text.toString()) } `object`.put("options", jsonArray) `object`.put("expires_in", linearLayout.toot_card_vote_editText_time.text.toString()) `object`.put("multiple", linearLayout.toot_card_vote_multi_switch.isChecked) `object`.put("hide_totals", linearLayout.toot_card_vote_hide_switch.isChecked); } catch (e: JSONException) { e.printStackTrace() } return `object` } //自分の情報を手に入れる private fun getAccount() { //Wi-Fi接続状況確認 val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) //カスタム絵文字有効/無効 var isEmojiShow = false if (pref_setting.getBoolean("pref_custom_emoji", true)) { if (pref_setting.getBoolean("pref_avater_wifi", true)) { //WIFIのみ表示有効時 //ネットワーク未接続時はnullか出る if (networkCapabilities != null) { if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { //WIFI isEmojiShow = true } } } else { //WIFI/MOBILE DATA 関係なく表示 isEmojiShow = true } } //通信量節約 val setting_avater_hidden = pref_setting.getBoolean("pref_drawer_avater", false) //Wi-Fi接続時は有効? val setting_avater_wifi = pref_setting.getBoolean("pref_avater_wifi", true) //GIFを再生するか? val setting_avater_gif = pref_setting.getBoolean("pref_avater_gif", false) val AccessToken = pref_setting.getString("main_token", "") val Instance = pref_setting.getString("main_instance", "") val glideSupport = GlideSupport() val url = "https://$Instance/api/v1/accounts/verify_credentials/?access_token=$AccessToken" //作成 val request = Request.Builder() .url(url) .get() .build() //GETリクエスト val client_1 = OkHttpClient() client_1.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() try { val jsonObject = JSONObject(response_string) var display_name = jsonObject.getString("display_name") val user_id = jsonObject.getString("acct") val toot_count = jsonObject.getString("statuses_count") //カスタム絵文字適用 if (isEmojiShow) { //他のところでは一旦配列に入れてるけど今回はここでしか使ってないから省くね val emojis = jsonObject.getJSONArray("emojis") for (i in 0 until emojis.length()) { val emojiObject = emojis.getJSONObject(i) val emoji_name = emojiObject.getString("shortcode") val emoji_url = emojiObject.getString("url") val custom_emoji_src = "<img src=\'$emoji_url\'>" //display_name if (display_name.contains(emoji_name)) { //あったよ display_name = display_name.replace(":$emoji_name:", custom_emoji_src) } } if (!jsonObject.isNull("profile_emojis")) { val profile_emojis = jsonObject.getJSONArray("profile_emojis") for (i in 0 until profile_emojis.length()) { val emojiObject = profile_emojis.getJSONObject(i) val emoji_name = emojiObject.getString("shortcode") val emoji_url = emojiObject.getString("url") val custom_emoji_src = "<img src=\'$emoji_url\'>" //display_name if (display_name.contains(emoji_name)) { //あったよ display_name = display_name.replace(":$emoji_name:", custom_emoji_src) } } } } val accountText = "@$user_id@$Instance" val snackber_Avatar = jsonObject.getString("avatar") val snackber_Avatar_notGif = jsonObject.getString("avatar_static") //UIスレッド (context as AppCompatActivity).runOnUiThread { //画像を入れる //表示設定 if (setting_avater_hidden) { linearLayout.toot_card_account_imageview.setImageResource(R.drawable.ic_person_black_24dp) } //GIF再生するか var url = snackber_Avatar if (setting_avater_gif) { //再生しない url = snackber_Avatar_notGif } //読み込む if (setting_avater_wifi && networkCapabilities != null) { if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { //角丸設定込み glideSupport.loadGlide(url, linearLayout.toot_card_account_imageview) } else { //キャッシュで読み込む glideSupport.loadGlideReadFromCache(url, linearLayout.toot_card_account_imageview) } } else { //キャッシュで読み込む glideSupport.loadGlideReadFromCache(url, linearLayout.toot_card_account_imageview) } //テキストビューに入れる val imageGetter = PicassoImageGetter(linearLayout.toot_card_account_textview) linearLayout.toot_card_account_textview.text = Html.fromHtml(display_name, Html.FROM_HTML_MODE_LEGACY, imageGetter, null) linearLayout.toot_card_account_textview.append("\n" + accountText) //裏機能? shinchokuLayout.setStatusProgress(toot_count) } } catch (e: JSONException) { e.printStackTrace() } } }) } //添付画像を消せるようにする fun setAttachImageLinearLayout() { linearLayout.toot_card_attach_linearlayout.removeAllViews() //取得 attachMediaList.forEach { val uri = it val pos = attachMediaList.indexOf(it) val imageView = ImageView(context) val params = ViewGroup.LayoutParams(200, 200) imageView.layoutParams = params imageView.tag = pos imageView.setImageURI(it) //長押ししたら削除 imageView.setOnClickListener { Toast.makeText(context, "長押しで削除できます。", Toast.LENGTH_SHORT).show() } imageView.setOnLongClickListener { //削除 val pos = imageView.tag as Int if (attachMediaList.contains(uri)) { //けす attachMediaList.removeAt(pos) //添付画像のLinearLayout作り直す setAttachImageLinearLayout() } true } //追加 //println(attachMediaList) linearLayout.toot_card_attach_linearlayout.addView(imageView) } } //自分の情報を手に入れる Misskey版 private fun getMisskeyAccount() { //Wi-Fi接続状況確認 val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) //カスタム絵文字有効/無効 var isEmojiShow = false if (pref_setting.getBoolean("pref_custom_emoji", true)) { if (pref_setting.getBoolean("pref_avater_wifi", true)) { //WIFIのみ表示有効時 //ネットワーク未接続時はnullか出る if (networkCapabilities != null) { if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { //WIFI isEmojiShow = true } } } else { //WIFI/MOBILE DATA 関係なく表示 isEmojiShow = true } } val glideSupport = GlideSupport() //通信量節約 val setting_avater_hidden = pref_setting.getBoolean("pref_drawer_avater", false) //Wi-Fi接続時は有効? val setting_avater_wifi = pref_setting.getBoolean("pref_avater_wifi", true) //GIFを再生するか? val setting_avater_gif = pref_setting.getBoolean("pref_avater_gif", false) val instance = pref_setting.getString("misskey_main_instance", "") val token = pref_setting.getString("misskey_main_token", "") val username = pref_setting.getString("misskey_main_username", "") val url = "https://$instance/api/i" val jsonObject = JSONObject() try { jsonObject.put("i", token) } catch (e: JSONException) { e.printStackTrace() } val requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString()) //作成 val request = Request.Builder() .url(url) .post(requestBody) .build() //GETリクエスト val client_1 = OkHttpClient() client_1.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() try { val jsonObject = JSONObject(response_string) val display_name = jsonObject.getString("name") //toot_count = jsonObject.getString("notesCount") val user_id = jsonObject.getString("username") var snackber_DisplayName = display_name //カスタム絵文字適用 if (isEmojiShow) { //他のところでは一旦配列に入れてるけど今回はここでしか使ってないから省くね val emojis = jsonObject.getJSONArray("emojis") for (i in 0 until emojis.length()) { val emojiObject = emojis.getJSONObject(i) val emoji_name = emojiObject.getString("name") val emoji_url = emojiObject.getString("url") val custom_emoji_src = "<img src=\'$emoji_url\'>" //display_name if (snackber_DisplayName.contains(emoji_name)) { //あったよ snackber_DisplayName = snackber_DisplayName.replace(":$emoji_name:", custom_emoji_src) } } if (!jsonObject.isNull("profile_emojis")) { val profile_emojis = jsonObject.getJSONArray("profile_emojis") for (i in 0 until profile_emojis.length()) { val emojiObject = profile_emojis.getJSONObject(i) val emoji_name = emojiObject.getString("name") val emoji_url = emojiObject.getString("url") val custom_emoji_src = "<img src=\'$emoji_url\'>" //display_name if (snackber_DisplayName.contains(emoji_name)) { //あったよ snackber_DisplayName = snackber_DisplayName.replace(":$emoji_name:", custom_emoji_src) } } } } val snackber_Name = "@$username@$instance" val snackber_Avatar = jsonObject.getString("avatarUrl") //UIスレッド (context as AppCompatActivity).runOnUiThread { //画像を入れる //表示設定 if (setting_avater_hidden) { linearLayout.toot_card_account_imageview.setImageResource(R.drawable.ic_person_black_24dp) //linearLayout.toot_card_account_imageview.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) } /* Misskeyのときは静止画像は取れないっぽい? //GIF再生するか var url = snackber_Avatar if (setting_avater_gif) { //再生しない url = snackber_Avatar_notGif } */ //読み込む if (setting_avater_wifi && networkCapabilities != null) { if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { //角丸設定込み glideSupport.loadGlide(snackber_Avatar, linearLayout.toot_card_account_imageview) } else { //キャッシュで読み込む glideSupport.loadGlideReadFromCache(snackber_Avatar, linearLayout.toot_card_account_imageview) } } else { //キャッシュで読み込む glideSupport.loadGlideReadFromCache(snackber_Avatar, linearLayout.toot_card_account_imageview) } //テキストビューに入れる val imageGetter = PicassoImageGetter(linearLayout.toot_card_account_textview) linearLayout.toot_card_account_textview.text = Html.fromHtml(snackber_DisplayName, Html.FROM_HTML_MODE_LEGACY, imageGetter, null) linearLayout.toot_card_account_textview.append("\n" + user_id) } } catch (e: JSONException) { e.printStackTrace() } } }) } }
1
null
1
1
98f8dd88deb68d749a5c44a7fca8bce6e8f3af39
54,226
Kaisendon
Apache License 2.0
stream/src/commonMain/kotlin/org/kryptonmc/nbt/stream/BinaryNBTWriter.kt
KryptonMC
388,819,410
false
null
/* * This file is part of Krypton NBT, licensed under the MIT license. * * Copyright (C) 2021 KryptonMC and contributors * * This project is licensed under the terms of the MIT license. * For more details, please reference the LICENSE file in the top-level directory. */ package org.kryptonmc.nbt.stream import okio.BufferedSink import okio.utf8Size import org.kryptonmc.nbt.ByteArrayTag import org.kryptonmc.nbt.ByteTag import org.kryptonmc.nbt.CompoundTag import org.kryptonmc.nbt.DoubleTag import org.kryptonmc.nbt.EndTag import org.kryptonmc.nbt.FloatTag import org.kryptonmc.nbt.IntArrayTag import org.kryptonmc.nbt.IntTag import org.kryptonmc.nbt.ListTag import org.kryptonmc.nbt.LongArrayTag import org.kryptonmc.nbt.LongTag import org.kryptonmc.nbt.ShortTag import org.kryptonmc.nbt.StringTag import org.kryptonmc.nbt.Tag import org.kryptonmc.nbt.util.UUID public class BinaryNBTWriter(private val sink: BufferedSink) : NBTWriter { private var stackSize = 1 private var scopes = IntArray(32) { -1 }.apply { this[0] = NBTScope.COMPOUND } private var deferredName: String? = null override fun beginByteArray(size: Int) { require(size >= 0) { "Cannot write a byte array with a size less than 0!" } writeNameAndType(ByteArrayTag.ID) open(NBTScope.BYTE_ARRAY) sink.writeInt(size) } override fun endByteArray() { close(NBTScope.BYTE_ARRAY) } override fun beginIntArray(size: Int) { require(size >= 0) { "Cannot write an integer array with a size less than 0!" } writeNameAndType(IntArrayTag.ID) open(NBTScope.INT_ARRAY) sink.writeInt(size) } override fun endIntArray() { close(NBTScope.INT_ARRAY) } override fun beginLongArray(size: Int) { require(size >= 0) { "Cannot write a long array with a size less than 0!" } writeNameAndType(LongArrayTag.ID) open(NBTScope.LONG_ARRAY) sink.writeInt(size) } override fun endLongArray() { close(NBTScope.LONG_ARRAY) } override fun beginList(elementType: Int, size: Int) { require(size >= 0) { "Cannot write a list with a size less than 0!" } check(elementType != 0 || size != 0) { "Invalid list! Element type must not be 0 for non-empty lists!" } writeNameAndType(ListTag.ID) open(NBTScope.LIST) sink.writeByte(elementType) sink.writeInt(size) } override fun endList() { close(NBTScope.LIST) } override fun beginCompound() { writeNameAndType(CompoundTag.ID) open(NBTScope.COMPOUND) } override fun endCompound() { close(NBTScope.COMPOUND) end() } override fun name(name: String) { val context = peekScope() check(context == NBTScope.COMPOUND) { "Nesting problem!" } deferredName = name } override fun value(value: String) { writeNameAndType(StringTag.ID) sink.writeShort(value.utf8Size().toInt()) sink.writeUtf8(value) } override fun value(value: Byte) { writeNameAndType(ByteTag.ID) sink.writeByte(value.toInt()) } override fun value(value: Short) { writeNameAndType(ShortTag.ID) sink.writeShort(value.toInt()) } override fun value(value: Int) { writeNameAndType(IntTag.ID) sink.writeInt(value) } override fun value(value: Long) { writeNameAndType(LongTag.ID) sink.writeLong(value) } override fun value(value: Float) { writeNameAndType(FloatTag.ID) sink.writeInt(value.toBits()) } override fun value(value: Double) { writeNameAndType(DoubleTag.ID) sink.writeLong(value.toBits()) } override fun value(value: Boolean) { writeNameAndType(ByteTag.ID) sink.writeByte(if (value) 1 else 0) } override fun value(value: UUID) { beginIntArray(4) sink.writeInt((value.mostSignificantBits shr 32).toInt()) sink.writeInt(value.mostSignificantBits.toInt()) sink.writeInt((value.leastSignificantBits shr 32).toInt()) sink.writeInt(value.leastSignificantBits.toInt()) endIntArray() } override fun end() { sink.writeByte(EndTag.ID) } override fun close() { sink.close() } private fun peekScope(): Int { check(stackSize != 0) { "Writer closed!" } return scopes[stackSize - 1] } private fun checkStack(): Boolean { if (stackSize != scopes.size) return false if (stackSize == 512) error("Depth too high! Maximum depth is 512!") scopes = scopes.copyOf(scopes.size * 2) return true } private fun pushScope(newTop: Int) { scopes[stackSize++] = newTop } private fun open(scope: Int) { checkStack() pushScope(scope) } private fun close(scope: Int) { val context = peekScope() check(context == scope) { "Nesting problem!" } check(deferredName == null) { "Dangling name: $deferredName!" } stackSize-- } // Only writes the type and the name if the current scope is not a list private fun writeNameAndType(type: Int) { if (peekScope() != NBTScope.COMPOUND) return val name = requireNotNull(deferredName) { "All binary tags must be named!" } sink.writeByte(type) sink.writeShort(name.length) sink.writeUtf8(name) deferredName = null } }
0
Kotlin
0
3
9492e7d8983354acde6d734a56d28a3437ef4599
5,510
nbt
MIT License
app/src/main/java/org/stepik/android/remote/course_revenue/model/CourseBenefitSummariesResponse.kt
StepicOrg
42,045,161
false
{"Kotlin": 4281147, "Java": 1001895, "CSS": 5482, "Shell": 618}
package org.stepik.android.remote.course_revenue.model import com.google.gson.annotations.SerializedName import org.stepik.android.domain.course_revenue.model.CourseBenefitSummary import org.stepik.android.model.Meta import org.stepik.android.remote.base.model.MetaResponse class CourseBenefitSummariesResponse( @SerializedName("meta") override val meta: Meta, @SerializedName("course-benefit-summaries") val courseBenefitSummaries: List<CourseBenefitSummary> ) : MetaResponse
13
Kotlin
54
189
dd12cb96811a6fc2a7addcd969381570e335aca7
494
stepik-android
Apache License 2.0
altchain-sdk/src/main/kotlin/org/veriblock/sdk/alt/model/SecurityInheritingBlock.kt
xagau
257,342,239
true
{"Java": 1795880, "Kotlin": 769750, "Groovy": 4290, "Dockerfile": 949}
package org.veriblock.sdk.alt.model data class SecurityInheritingBlock( val hash: String, val height: Int, val previousHash: String, val confirmations: Int, val version: Short, val nonce: Int, val merkleRoot: String, val difficulty: Double, val coinbaseTransactionId: String, val transactionIds: List<String>, // Previous keystone references val previousKeystone: String? = null, val secondPreviousKeystone: String? = null )
0
null
0
0
9940affa317ecf8e9254d8ed053b511283920619
479
nodecore
MIT License
failgood/jvm/src/failgood/junit/exp/PlaygroundEngine.kt
failgood
323,114,755
false
{"Kotlin": 324179, "Java": 130}
package failgood.junit.exp import failgood.junit.next.DynamicTestDescriptor import failgood.junit.next.TestPlanNode import org.junit.platform.engine.EngineDiscoveryRequest import org.junit.platform.engine.ExecutionRequest import org.junit.platform.engine.TestDescriptor import org.junit.platform.engine.TestEngine import org.junit.platform.engine.TestExecutionResult import org.junit.platform.engine.TestSource import org.junit.platform.engine.TestTag import org.junit.platform.engine.UniqueId import java.util.Optional /** * this is just to play around with the junit engines api to see how dynamic tests work */ class PlaygroundEngine : TestEngine { override fun getId(): String { return "failgood-playground" } override fun discover(discoveryRequest: EngineDiscoveryRequest?, uniqueId: UniqueId): TestDescriptor { return MyTestDescriptor(TestPlanNode.Container("root"), uniqueId, null) } override fun execute(request: ExecutionRequest) { val root = request.rootTestDescriptor if (root !is MyTestDescriptor) return val l = request.engineExecutionListener l.executionStarted(root) val container = TestPlanNode.Container("container") val containerDescriptor = DynamicTestDescriptor(container, root) l.dynamicTestRegistered(containerDescriptor) val container1 = TestPlanNode.Container("container1") val container1Descriptor = DynamicTestDescriptor(container1, containerDescriptor) l.dynamicTestRegistered(container1Descriptor) val container2Descriptor = DynamicTestDescriptor( TestPlanNode.Container("container2"), container1Descriptor ) val test2Descriptor = DynamicTestDescriptor(TestPlanNode.Test("Test2"), container2Descriptor) container2Descriptor.addChild(test2Descriptor) l.executionStarted(containerDescriptor) l.executionStarted(container1Descriptor) l.dynamicTestRegistered(container2Descriptor) l.dynamicTestRegistered(test2Descriptor) l.executionStarted(container2Descriptor) l.executionStarted(test2Descriptor) l.executionFinished(test2Descriptor, TestExecutionResult.successful()) l.executionFinished(container2Descriptor, TestExecutionResult.successful()) l.executionStarted(container1Descriptor) l.executionFinished(container1Descriptor, TestExecutionResult.successful()) l.executionFinished(containerDescriptor, TestExecutionResult.successful()) l.executionFinished(root, TestExecutionResult.successful()) } } class MyTestDescriptor(val test: TestPlanNode, private val uniqueId: UniqueId, private var parent: TestDescriptor?) : TestDescriptor { private val children = mutableSetOf<TestDescriptor>() override fun getUniqueId(): UniqueId = uniqueId override fun getDisplayName(): String = test.name override fun getTags(): MutableSet<TestTag> = mutableSetOf() override fun getSource(): Optional<TestSource> = Optional.empty() override fun getParent(): Optional<TestDescriptor> = Optional.ofNullable(parent) override fun setParent(parent: TestDescriptor?) { TODO("Not yet implemented") } override fun getChildren(): MutableSet<out TestDescriptor> = children override fun addChild(descriptor: TestDescriptor) { children.add(descriptor) } override fun removeChild(descriptor: TestDescriptor?) { TODO("Not yet implemented") } override fun removeFromHierarchy() { parent = null } override fun getType(): TestDescriptor.Type { return when (test) { is TestPlanNode.Container -> TestDescriptor.Type.CONTAINER is TestPlanNode.Test -> TestDescriptor.Type.TEST } } override fun findByUniqueId(uniqueId: UniqueId?): Optional<out TestDescriptor> { TODO("Not yet implemented") } }
36
Kotlin
5
19
eb317593dcc1c37f883f9554c78a729ceeebcfc1
4,099
failgood
MIT License
src/main/kotlin/cc/suffro/bpmanalyzer/bpmanalyzing/BpmAnalyzingModule.kt
xsoophx
579,535,622
false
{"Kotlin": 92032}
package cc.suffro.bpmanalyzer.bpmanalyzing import cc.suffro.bpmanalyzer.bpmanalyzing.analyzers.BpmAnalyzer import cc.suffro.bpmanalyzer.bpmanalyzing.analyzers.CombFilterAnalyzer import org.koin.core.module.dsl.bind import org.koin.core.module.dsl.singleOf import org.koin.dsl.module val bpmAnalyzingModule = module { singleOf(::CombFilterAnalyzer) { bind<BpmAnalyzer>() } }
0
Kotlin
0
0
e945864aa5fab9ec2e1abe485ca3dd3f8cdd5c6e
392
BPM-Analyzer
MIT License
app/weather/src/test/java/jp/co/mixi/androidtraining/weather/ui/WeatherViewModelTest.kt
mixigroup
776,812,769
false
{"Kotlin": 31815}
package jp.co.mixi.androidtraining.weather.ui import jp.co.mixi.androidtraining.weather.data.repository.FakeWeatherRepository import jp.co.mixi.androidtraining.weather.utils.MainDispatcherRule import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test class WeatherViewModelTest { @get:Rule val dispatcherRule = MainDispatcherRule() private val viewModel = WeatherViewModel(FakeWeatherRepository()) @Test fun testGetWeather() = runTest { assertEquals("", viewModel.uiState.weather) viewModel.getWeather() advanceUntilIdle() assertEquals("晴れ", viewModel.uiState.weather) } }
12
Kotlin
0
0
1b65fd0a4f7667e21fa41f68eca12b26c70d8276
744
2024AndroidTraining
Apache License 2.0
devtools/android/src/main/kotlin/com/maximbircu/devtools/android/presentation/tools/group/GroupToolLayout.kt
maximbircu
247,318,697
false
null
package com.maximbircu.devtools.android.presentation.tools.group import android.annotation.SuppressLint import android.content.Context import android.widget.PopupMenu import com.maximbircu.devtools.android.R import com.maximbircu.devtools.android.databinding.LayoutGroupToolBinding import com.maximbircu.devtools.android.presentation.list.DevToolsListLayout import com.maximbircu.devtools.android.presentation.tool.DevToolLayout import com.maximbircu.devtools.common.core.DevTool import com.maximbircu.devtools.common.presentation.tool.DevToolView import com.maximbircu.devtools.common.presentation.tools.group.GroupTool import com.maximbircu.devtools.common.presentation.tools.group.GroupToolPresenter import com.maximbircu.devtools.common.presentation.tools.group.GroupToolView class GroupToolLayout(context: Context) : DevToolLayout<GroupTool>(context), GroupToolView { private val presenter: GroupToolPresenter = GroupToolPresenter.create(this) private val groupToolBinding = LayoutGroupToolBinding.bind(this) internal val devToolsViewsContainer: DevToolsListLayout get() = groupToolBinding.devToolsViewsContainer override val devToolsViews: List<DevToolView> get() = devToolsViewsContainer.devToolViews override val layoutRes: Int get() = R.layout.layout_group_tool override fun onBind(tool: GroupTool) = presenter.onToolBind(tool) override fun showTools(tools: List<DevTool<*>>) { devToolsViewsContainer.showDevTools(tools) } override fun showToolContextMenu() { val popup = PopupMenu(context, binding.headerContainer.menuButton) popup.menuInflater.inflate(R.menu.group_tool_context_menu, popup.menu) popup.setOnMenuItemClickListener(GroupToolContextMenuClickListener(presenter)) popup.show() } @SuppressLint("NotifyDataSetChanged") override fun refreshToolData() { devToolsViewsContainer.adapter?.notifyDataSetChanged() } }
9
Kotlin
3
15
14a484b169c709b22739e556ab799e263f60f168
1,953
devtools-library
Apache License 2.0
kotlin/PlanesAndroid/app/src/main/java/com/planes/multiplayer_engine/commobj/BasisCommObj.kt
xxxcucus
141,627,030
false
null
package com.planes.multiplayer_engine.commobj import androidx.fragment.app.FragmentActivity import com.planes.android.MainActivity import com.planes.android.MultiplayerRoundInterface import com.planes.android.Tools import com.planes.multiplayer_engine.MultiplayerRoundJava import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import okhttp3.Headers import retrofit2.Response import java.util.concurrent.TimeUnit /* Basis class for communicating with the game server via Retrofit - withLoadingAnimation: show a loader animation from start of the request until receiving of the response - createObservable: function creating the Retrofit observable - errorStrg: error string displayed in case of an known error - unknownError: error string displayed in case of an unknown error - shouldBeLoggedIn: should an user be logged in when this request is made - shouldBeConnectedToGame: should an user be connected to game when sending this request - errorStrgNotLoggedIn: error message shown when no user is logged in and it should be - errorStrgNotConnected: error message shown when no user is connected to a game and it should be - withCredentials: provide credentials for credentials validation - username: username - password: <PASSWORD> - userPasswordValidation: function used for user password validation - doWhenSuccess: function performed when the request was successfull - checkAuthorization: verify the received "Authorization" header - saveCredentials: save the used credentials (user, password, token) - finalizeRequestSuccessful: function to end request when the request was successfull - finalizeRequestError: function to end request when the request failed - activity: the Fragment Activity from which the request is made */ open class BasisCommObj<A>(withLoadingAnimation: Boolean, createObservable: () -> Observable<Response<A>>, errorStrg: String, unknownError: String, shouldBeLoggedIn: Boolean, shouldBeConnectedToGame: Boolean, errorStrgNotLoggedIn: String, errorStrgNotConnected: String, withCredentials: Boolean, username: String, password: String, userPasswordValidation: (String, String) -> String, doWhenSuccess: (A) -> String, checkAuthorization: Boolean, saveCredentials: (String, String, String, A?) -> Unit, finalizeRequestSuccessful: () -> Unit, finalizeRequestError: () -> Unit, activity: FragmentActivity) { private lateinit var m_RetrofitSubscription: Disposable protected var m_PlaneRound: MultiplayerRoundInterface = MultiplayerRoundJava() private lateinit var m_Observable: Observable<Response<A>> protected var m_RequestError: Boolean = false protected var m_RequestErrorString: String = "" private var m_GenericErrorString: String private var m_UnknownErrorString: String private var m_WithLoadingAnimation: Boolean private var m_ErrorStringNotConnected: String protected var m_ErrorStringNotLoggedIn: String private var m_ShouldBeLoggedIn: Boolean private var m_ShouldBeConnectedToGame: Boolean protected var m_CreateObservable: () -> Observable<Response<A>> protected var m_HideLoadingLambda: () -> Unit protected var m_ShowLoadingLambda: () -> Unit protected var m_IsActive = true //Can I create another request (user clicks fast one time after the other) private var m_WithCredentials: Boolean protected var m_UserName: String protected var m_Password: String private var m_CheckAuthorization: Boolean protected var m_UserPasswordValidation: (String, String) -> String protected var m_SaveCredentials: (String, String, String, A?) -> Unit protected var m_FinalizeRequestSuccessful: () -> Unit protected var m_FinalizeRequestError: () -> Unit protected var m_DoWhenSuccess: (A) -> String protected var m_MainActivity: FragmentActivity init { (m_PlaneRound as MultiplayerRoundJava).createPlanesRound() m_HideLoadingLambda = ::hideLoading m_ShowLoadingLambda = ::showLoading m_WithLoadingAnimation = withLoadingAnimation m_GenericErrorString = errorStrg m_UnknownErrorString = unknownError m_ErrorStringNotConnected = errorStrgNotConnected m_ErrorStringNotLoggedIn = errorStrgNotLoggedIn m_ShouldBeLoggedIn = shouldBeLoggedIn m_ShouldBeConnectedToGame = shouldBeConnectedToGame m_CreateObservable = createObservable m_WithCredentials = withCredentials m_UserName = username m_Password = <PASSWORD> m_CheckAuthorization = checkAuthorization m_UserPasswordValidation = userPasswordValidation m_SaveCredentials = saveCredentials m_FinalizeRequestSuccessful = finalizeRequestSuccessful m_FinalizeRequestError = finalizeRequestError m_DoWhenSuccess = doWhenSuccess m_MainActivity = activity } open fun makeRequest() { m_RequestError = false m_RequestErrorString = "" if (m_ShouldBeLoggedIn) { if (!userLoggedIn()) { finalizeRequest() return } } if (m_ShouldBeConnectedToGame) { if (!connectedToGame()) { finalizeRequest() return } } if (m_WithCredentials) { if (!userPasswordValidation()) { finalizeRequest() return } } m_Observable = m_CreateObservable() sendRequest() } open fun finishedRequest(code: Int, jsonErrorString: String?, headrs: Headers, body: A?) { if (m_CheckAuthorization) finishedRequestAuthorization(jsonErrorString, headrs, body) else finishedRequestBody(jsonErrorString, body) } private fun finishedRequestBody(jsonErrorString: String?, body: A?) { if (body != null) { val errorStrg = m_DoWhenSuccess(body) if (errorStrg.isNotEmpty()) { m_RequestError = true m_RequestErrorString = errorStrg } } else { m_RequestErrorString = Tools.parseJsonError(jsonErrorString, m_GenericErrorString, m_UnknownErrorString) m_RequestError = true } finalizeRequest() } private fun finishedRequestAuthorization(jsonErrorString: String?, headrs: Headers, body: A?) { if (headrs["Authorization"] != null) { val authorizationHeader = headrs["Authorization"] if (authorizationHeader != null) m_SaveCredentials(m_UserName, m_Password, authorizationHeader, body) } else { m_RequestErrorString = Tools.parseJsonError(jsonErrorString, m_GenericErrorString, m_UnknownErrorString) m_RequestError = true } finalizeRequest() } private fun setRequestError(errorMsg: String) { m_RequestError = true m_RequestErrorString = errorMsg finalizeRequest() } open fun finalizeRequest() { m_IsActive = false if (m_RequestError) { (m_MainActivity as MainActivity).onWarning(m_RequestErrorString) m_FinalizeRequestError() } else { m_FinalizeRequestSuccessful() } } fun disposeSubscription() { if (this::m_RetrofitSubscription.isInitialized) { m_RetrofitSubscription.dispose() m_IsActive = false } } fun isActive(): Boolean { return m_IsActive } private fun sendRequest() { if (m_WithLoadingAnimation) { m_RetrofitSubscription = m_Observable .delay (1500, TimeUnit.MILLISECONDS ) //TODO: to remove this .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { doOnSubscribe() } .doOnTerminate { doOnTerminate() } .doOnComplete { doOnTerminate() } .subscribe({data -> finishedRequest(data.code(), data.errorBody()?.string(), data.headers(), data.body())} , {error -> error.localizedMessage?.let { setRequestError(it) } }) } else { m_RetrofitSubscription = m_Observable .delay (1500, TimeUnit.MILLISECONDS ) //TODO: to remove this .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({data -> finishedRequest(data.code(), data.errorBody()?.string(), data.headers(), data.body())} , {error -> error.localizedMessage?.let { setRequestError(it) } }) } } private fun userLoggedIn(): Boolean { if (!m_PlaneRound.isUserLoggedIn()) { m_RequestError = true m_RequestErrorString = m_ErrorStringNotLoggedIn return false } return true } private fun connectedToGame(): Boolean { if (!m_PlaneRound.isUserConnectedToGame()) { m_RequestError = true m_RequestErrorString = m_ErrorStringNotConnected return false } return true } private fun userPasswordValidation(): Boolean { val error = m_UserPasswordValidation(m_UserName, m_Password) if (error.isNotEmpty()) { m_RequestError = true m_RequestErrorString = error return false } return true } private fun doOnSubscribe() { m_ShowLoadingLambda() } private fun doOnTerminate() { m_HideLoadingLambda() } fun showLoading() { (m_MainActivity as MainActivity).startProgressDialog() } fun hideLoading() { (m_MainActivity as MainActivity).stopProgressDialog() } }
16
null
9
35
68d5e14566ea2bfe06df933ab80eb0182df5dad0
9,916
planes
MIT License
dd-sdk-android/src/main/kotlin/com/datadog/android/rum/webview/RumWebChromeClient.kt
DataDog
219,536,756
false
null
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.rum.webview import android.util.Log import android.webkit.ConsoleMessage import android.webkit.WebChromeClient import android.webkit.WebViewClient import com.datadog.android.log.Logger import com.datadog.android.rum.GlobalRum import com.datadog.android.rum.RumErrorSource /** * A [WebViewClient] propagating all relevant events to Datadog. * * Any console message will be forwarded to an internal [Logger], and errors * will be sent to the [GlobalRum] monitor as RUM Errors. * * This class is deprecated and you should use the new * [com.datadog.android.webview.DatadogEventBridge] to track your WebViews: * * ```kotlin * val configuration = Configuration.Builder().setWebViewTrackingHosts(listOf(<YOUR_HOSTS>)) * Datadog.initialize(this, credentials, configuration, trackingConsent) * * // By default, link navigation will be delegated to a third party app. * // If you want all navigation to happen inside of the webview, uncomment the following line. * * // webView.webViewClient = WebViewClient() * webView.settings.javaScriptEnabled = true * webView.addJavascriptInterface(DatadogEventBridge(), "DatadogEventBridge") * ``` * [See more](https://developer.android.com/guide/webapps/webview#HandlingNavigation) */ @Deprecated("You should use the DatadogEventBridge JavaScript interface instead.") open class RumWebChromeClient internal constructor(private val logger: Logger) : WebChromeClient() { constructor() : this( Logger.Builder() .setLoggerName(LOGGER_NAME) .setNetworkInfoEnabled(true) .build() ) // region WebChromeClient override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean { if (consoleMessage != null) { val message = consoleMessage.message() val level = consoleMessage.messageLevel().toLogLevel() val attributes = mapOf<String, Any>( SOURCE_ID to consoleMessage.sourceId(), SOURCE_LINE to consoleMessage.lineNumber() ) if (level == Log.ERROR) { GlobalRum.get().addError( message, RumErrorSource.WEBVIEW, null, attributes ) } else { logger.log(level, message, null, attributes) } } return false } // endregion // region Internal private fun ConsoleMessage.MessageLevel.toLogLevel(): Int { return when (this) { ConsoleMessage.MessageLevel.LOG -> Log.VERBOSE ConsoleMessage.MessageLevel.DEBUG -> Log.DEBUG ConsoleMessage.MessageLevel.TIP -> Log.INFO ConsoleMessage.MessageLevel.WARNING -> Log.WARN ConsoleMessage.MessageLevel.ERROR -> Log.ERROR } } // endregion companion object { internal const val LOGGER_NAME = "WebChromeClient" internal const val SOURCE_ID = "source.id" internal const val SOURCE_LINE = "source.line" } }
33
Kotlin
39
86
bcf0d12fd978df4e28848b007d5fcce9cb97df1c
3,329
dd-sdk-android
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/animations/DocumentTimelineOptions.kt
karakum-team
393,199,102
false
{"Kotlin": 6912722}
// Automatically generated - do not modify! package web.animations import js.objects.JsPlainObject import web.time.DOMHighResTimeStamp @JsPlainObject sealed external interface DocumentTimelineOptions { var originTime: DOMHighResTimeStamp? }
0
Kotlin
7
31
79f2034ed9610e4416dfde5b70a0ff06f88210b5
248
types-kotlin
Apache License 2.0
waltid-verifiable-credentials/src/jsMain/kotlin/id/walt/credentials/verification/policies/RevocationPolicy.js.kt
walt-id
701,058,624
false
{"Kotlin": 2223984, "Vue": 327750, "TypeScript": 95586, "JavaScript": 20560, "Dockerfile": 7261, "Python": 3118, "Shell": 1958, "CSS": 404, "TSQL": 301}
package id.walt.credentials.verification.policies import kotlinx.serialization.json.JsonElement import love.forte.plugin.suspendtrans.annotation.JsPromise //@JsPromise //@JsExport.Ignore actual class RevocationPolicy: RevocationPolicyMp() { override suspend fun verify(data: JsonElement, args: Any?, context: Map<String, Any>): Result<Any> { TODO("Not yet implemented") } }
39
Kotlin
36
103
68251649e992ff46f9838606ef13004d72a2548f
392
waltid-identity
Apache License 2.0
includeBuild/kmp/src/main/kotlin/io/matthewnelson/kotlin/components/kmp/util/ProjectExt.kt
05nelsonm
381,628,235
false
null
/* * Copyright (c) 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package io.matthewnelson.kotlin.components.kmp.util import com.vanniktech.maven.publish.SonatypeHost import dev.petuska.npm.publish.dsl.NpmAccess import dev.petuska.npm.publish.dsl.NpmPublication import dev.petuska.npm.publish.dsl.NpmPublishExtension import io.matthewnelson.kotlin.components.kmp.publish.kmpPublishRootProjectConfiguration import org.gradle.api.Project import org.gradle.api.plugins.ExtraPropertiesExtension import org.gradle.kotlin.dsl.* @JvmOverloads @Suppress("unused") @Throws(ExtraPropertiesExtension.UnknownPropertyException::class) fun Project.includeStagingRepoIfTrue( include: Boolean, sonatypeHost: SonatypeHost = SonatypeHost.S01, ): Boolean { if (!include) return include repositories { maven("${sonatypeHost.rootUrl}/content/groups/staging") { credentials { rootProject.propertyExt { username = get("mavenCentralUsername").toString() password = get("mavenCentralPassword").toString() } } } } return include } @JvmOverloads @Suppress("unused") fun Project.includeSnapshotsRepoIfTrue( include: Boolean, sonatypeHost: SonatypeHost = SonatypeHost.S01, ): Boolean { if (!include) return include repositories { maven("${sonatypeHost.rootUrl}/content/repositories/snapshots/") } return include } /* Why the value is marked internal is beyond me... */ val SonatypeHost.rootUrl: String get() { return when (this) { SonatypeHost.DEFAULT -> "https://oss.sonatype.org" SonatypeHost.S01 -> "https://s01.oss.sonatype.org" } } fun Project.configureYarn( block: org.jetbrains.kotlin.gradle.targets.js.yarn.YarnPlugin.( rootYarn: org.jetbrains.kotlin.gradle.targets.js.yarn.YarnRootExtension, rootNodeJs: org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension, ) -> Unit ) { check(this.rootProject == this) { "This method can only be called from the the root project's build.gradle(.kts) file" } rootProject.plugins.withType<org.jetbrains.kotlin.gradle.targets.js.yarn.YarnPlugin>() { block.invoke( this, rootProject.the<org.jetbrains.kotlin.gradle.targets.js.yarn.YarnRootExtension>(), rootProject.the<org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension>() ) } } fun Project.npmPublish(block: NpmPublication.() -> Unit) { check(rootProject != this) { "This method can not be called from the root project's build.gradle(.kts) file" } check(plugins.hasPlugin("dev.petuska.npm.publish")) { "Plugin 'dev.petuska.npm.publish' must be applied" } extensions.configure<NpmPublishExtension> { publications { publication(project.name) { main = "index.js" access = NpmAccess.PUBLIC version = kmpPublishRootProjectConfiguration?.versionName readme = file("README.md") packageJson { homepage = "https://github.com/05nelsonm/${rootProject.name}" license = "Apache 2.0" repository { type = "git" url = "git+https://github.com/05nelsonm/${rootProject.name}.git" } author { name = "<NAME>" } bugs { url = "https://github.com/05nelsonm/${rootProject.name}/issues" } } repositories { val port = rootProject.findProperty("NPMJS_VERDACCIO_PORT") as? String val token = rootProject.findProperty("NPMJS_VERDACCIO_AUTH_TOKEN") as? String if (port != null && token != null) { repository("verdaccio") { registry = uri("http://localhost:$port") authToken = token } } repository("npmjs") { registry = uri("https://registry.npmjs.org") authToken = rootProject.findProperty("NPMJS_AUTH_TOKEN") as? String } } block.invoke(this) } } } }
1
Kotlin
1
2
6286792f4bb5547c5527b8eaaf9d2c48fae694ae
5,005
kotlin-components
Apache License 2.0
shared/src/commonMain/kotlin/com/findmypast/kmmsample/base/NanoRedux.kt
amatsehor-fmp
413,705,848
true
{"Kotlin": 42940, "Swift": 7133}
package com.findmypast.kmmsample.base import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow interface State interface Action interface Effect interface Store<S : State, A : Action, E : Effect> { val state: StateFlow<S> val sideEffect: Flow<E> fun dispatch(action: A) }
0
Kotlin
0
0
f12001ea42a6a47c3769beb5b1d5c764a004930d
306
kmm-basic-sample
Apache License 2.0
videochatguru/src/main/java/co/netguru/videochatguru/constraints/OfferAnswerConstraints.kt
netguru
98,288,528
false
null
package co.netguru.videochatguru.constraints /** * Constraint keys for CreateOffer / CreateAnswer defined in W3C specification. * * @see <a href="https://chromium.googlesource.com/external/webrtc/+/e33c5d918a213202321bde751226c4949644fe5e/webrtc/api/mediaconstraintsinterface.cc"> * Available constraints in media constraints interface implementation</a> */ enum class OfferAnswerConstraints(override val constraintString: String) : WebRtcConstraint<Boolean> { OFFER_TO_RECEIVE_AUDIO("OfferToReceiveAudio"), OFFER_TO_RECEIVE_VIDEO("OfferToReceiveVideo"), /** * Many codec's and systems are capable of detecting "silence" and changing their behavior in this * case by doing things such as not transmitting any media. In many cases, such as when dealing * with emergency calling or sounds other than spoken voice, it is desirable to be able to turn * off this behavior. This option allows the application to provide information about whether it * wishes this type of processing enabled or disabled. */ VOICE_ACTIVITY_DETECTION("VoiceActivityDetection"), /** * Tries to restart connection after it was in failed or disconnected state */ ICE_RESTART("IceRestart"), /** * Google specific constraint for BUNDLE enable/disable. */ GOOG_USE_RTP_MUX("googUseRtpMUX") }
4
Kotlin
112
300
e5790fec71db013aac00dac2faf15d87fc46b80a
1,353
videochatguru-android
Apache License 2.0
app/src/main/java/com/amapi/extensibility/demo/commands/InMemoryCommandRepository.kt
googlesamples
410,016,944
false
{"Kotlin": 13234}
/* Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.amapi.extensibility.demo.commands import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.android.managementapi.commands.model.Command object InMemoryCommandRepository { private val commandLiveData: MutableLiveData<Command> = MutableLiveData() fun onCommandStatusChanged(command: Command?) { commandLiveData.postValue(command) } fun getCommandLiveData(): LiveData<Command> { return commandLiveData } }
0
Kotlin
5
8
1b14bf7db33a8d760504b13f9c182bb55ee08af4
1,066
amapi
Apache License 2.0
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/types/boosts/BoostId.kt
InsanusMokrassar
163,152,024
false
{"Kotlin": 3243076, "Shell": 373}
package dev.inmo.tgbotapi.types.boosts import kotlinx.serialization.Serializable import kotlin.jvm.JvmInline @Serializable @JvmInline value class BoostId( val string: String )
13
Kotlin
29
358
482c375327b7087699a4cb8bb06cb09869f07630
182
ktgbotapi
Apache License 2.0
kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/backend/gl/CompiledComputeShader.kt
kool-engine
81,503,047
false
{"Kotlin": 5929566, "C++": 3256, "CMake": 1870, "HTML": 1464, "JavaScript": 597}
package de.fabmax.kool.pipeline.backend.gl import de.fabmax.kool.pipeline.ComputePipeline import de.fabmax.kool.pipeline.ComputeRenderPass import de.fabmax.kool.pipeline.PipelineBackend class CompiledComputeShader(val pipeline: ComputePipeline, program: GlProgram, backend: RenderBackendGl) : CompiledShader(pipeline, program, backend), PipelineBackend { private val users = mutableSetOf<ComputeRenderPass.Task>() fun bindComputePass(task: ComputeRenderPass.Task): Boolean { users += task pipeline.update(task.pass) return bindUniforms(task.pass, null, null) } override fun removeUser(user: Any) { (user as? ComputeRenderPass.Task)?.let { users.remove(it) } if (users.isEmpty()) { release() } } override fun release() { if (!isReleased) { backend.shaderMgr.removeComputeShader(this) super.release() } } }
12
Kotlin
20
303
8d05acd3e72ff2fc115d0939bf021a5f421469a5
945
kool
Apache License 2.0
sample/android/src/test/java/co/nimblehq/kmm/template/ui/screens/BaseScreenTest.kt
nimblehq
662,848,235
false
{"Kotlin": 26074, "Shell": 9344, "Ruby": 3299}
package co.nimblehq.kmm.template.ui.screens import co.nimblehq.kmm.template.test.CoroutineTestRule import kotlinx.coroutines.test.StandardTestDispatcher abstract class BaseScreenTest { protected val coroutinesRule = CoroutineTestRule() protected fun setStandardTestDispatcher() { coroutinesRule.testDispatcher = StandardTestDispatcher() } protected fun advanceUntilIdle() { coroutinesRule.testDispatcher.scheduler.advanceUntilIdle() } }
5
Kotlin
0
2
b450d4feb1d87b9bb154ad84360c77483faccde6
478
kmm-templates
MIT License
graphql-multiplatform-plugin/src/main/kotlin/xyz/mcxross/graphql/plugin/gradle/tasks/AbstractGenerateClientTask.kt
mcxross
785,636,958
false
{"Kotlin": 220816}
/* * Copyright 2023 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xyz.mcxross.graphql.plugin.gradle.tasks import java.io.File import javax.inject.Inject import org.gradle.api.DefaultTask import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Classpath import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.options.Option import org.gradle.workers.ClassLoaderWorkerSpec import org.gradle.workers.WorkQueue import org.gradle.workers.WorkerExecutor import xyz.mcxross.graphql.plugin.gradle.actions.GenerateClientAction import xyz.mcxross.graphql.plugin.gradle.config.GraphQLParserOptions import xyz.mcxross.graphql.plugin.gradle.config.GraphQLScalar import xyz.mcxross.graphql.plugin.gradle.config.GraphQLSerializer /** * Generate GraphQL Kotlin client and corresponding data classes based on the provided GraphQL * queries. */ abstract class AbstractGenerateClientTask : DefaultTask() { @get:Classpath val pluginClasspath: ConfigurableFileCollection = project.objects.fileCollection() /** * GraphQL schema file that will be used to generate client code. * * **Required Property** */ @InputFile val schemaFile: RegularFileProperty = project.objects.fileProperty() /** * Target package name for generated code. * * **Required Property** **Command line property is**: `packageName`. */ @Input @Option(option = "packageName", description = "target package name to use for generated classes") val packageName: Property<String> = project.objects.property(String::class.java) /** * Boolean flag indicating whether selection of deprecated fields is allowed or not. * * **Default value is:** `false`. **Command line property is**: `allowDeprecatedFields`. */ @Input @Optional @Option( option = "allowDeprecatedFields", description = "boolean flag indicating whether selection of deprecated fields is allowed or not", ) val allowDeprecatedFields: Property<Boolean> = project.objects.property(Boolean::class.java) /** * List of custom GraphQL scalar converters. * * ```kotlin * customScalars.add(GraphQLScalar("UUID", "java.util.UUID", "com.expediagroup.graphql.examples.client.UUIDScalarConverter")) * ) */ @Input @Optional val customScalars: ListProperty<GraphQLScalar> = project.objects.listProperty(GraphQLScalar::class.java) /** * Directory containing GraphQL queries. Defaults to `src/main/resources` when generating main * sources and `src/test/resources` when generating test client. * * Instead of specifying a directory you can also specify list of query file by using `queryFiles` * property instead. */ @InputDirectory @Optional val queryFileDirectory: DirectoryProperty = project.objects.directoryProperty() /** * List of query files to be processed. Instead of a list of files to be processed you can also * specify [queryFileDirectory] directory containing all the files. If this property is specified * it will take precedence over the corresponding directory property. */ @InputFiles @Optional val queryFiles: ConfigurableFileCollection = project.objects.fileCollection() @Input @Optional @Option( option = "serializer", description = "JSON serializer that will be used to generate the data classes.", ) val serializer: Property<GraphQLSerializer> = project.objects.property(GraphQLSerializer::class.java) @Input @Optional @Option( option = "useOptionalInputWrapper", description = "Opt-in flag to wrap nullable arguments in OptionalInput that supports both null and undefined.", ) val useOptionalInputWrapper: Property<Boolean> = project.objects.property(Boolean::class.java) @Input @Optional val parserOptions: Property<GraphQLParserOptions> = project.objects.property(GraphQLParserOptions::class.java) @OutputDirectory val outputDirectory: DirectoryProperty = project.objects.directoryProperty() @Inject abstract fun getWorkerExecutor(): WorkerExecutor init { group = "GraphQL" description = "Generate HTTP client from the specified GraphQL queries." allowDeprecatedFields.convention(false) customScalars.convention(emptyList()) serializer.convention(GraphQLSerializer.JACKSON) useOptionalInputWrapper.convention(false) parserOptions.convention(GraphQLParserOptions()) } @Suppress("EXPERIMENTAL_API_USAGE") @TaskAction fun generateGraphQLClientAction() { logger.debug("generating GraphQL client") val graphQLSchemaPath = when { schemaFile.isPresent -> schemaFile.get().asFile.path else -> throw RuntimeException("schema not available") } val targetPackage = packageName.orNull ?: throw RuntimeException("package not specified") val targetQueryFiles: List<File> = when { queryFiles.files.isNotEmpty() -> queryFiles.files.toList() queryFileDirectory.isPresent -> { queryFileDirectory.asFile.orNull ?.walkBottomUp() ?.filter { file -> file.extension == "graphql" } ?.toList() ?: throw RuntimeException("exception while looking up the query files") } else -> throw RuntimeException("no query files found") } if (targetQueryFiles.isEmpty()) { throw RuntimeException("no query files specified") } val targetDirectory = outputDirectory.get().asFile if (!targetDirectory.isDirectory && !targetDirectory.mkdirs()) { throw RuntimeException("failed to generate generated source directory = $targetDirectory") } logConfiguration(graphQLSchemaPath, targetQueryFiles) val workQueue: WorkQueue = getWorkerExecutor().classLoaderIsolation { workerSpec: ClassLoaderWorkerSpec -> workerSpec.classpath.from(pluginClasspath) logger.debug("worker classpath: \n${workerSpec.classpath.files.joinToString("\n")}") } workQueue.submit(GenerateClientAction::class.java) { parameters -> parameters.packageName.set(targetPackage) parameters.allowDeprecated.set(allowDeprecatedFields) parameters.customScalars.set(customScalars) parameters.serializer.set(serializer) parameters.schemaPath.set(graphQLSchemaPath) parameters.queryFiles.set(targetQueryFiles) parameters.targetDirectory.set(targetDirectory) parameters.useOptionalInputWrapper.set(useOptionalInputWrapper) parameters.parserOptions.set(parserOptions) } workQueue.await() logger.debug("successfully generated GraphQL HTTP client") } private fun logConfiguration(schemaPath: String, queryFiles: List<File>) { logger.debug("GraphQL Client generator configuration:") logger.debug(" schema file = $schemaPath") logger.debug(" queries") queryFiles.forEach { logger.debug(" - ${it.name}") } logger.debug(" packageName = $packageName") logger.debug(" allowDeprecatedFields = $allowDeprecatedFields") logger.debug(" parserOptions = $parserOptions") logger.debug(" converters") customScalars.get().forEach { (customScalar, type, converter) -> logger.debug(" - custom scalar = $customScalar") logger.debug(" |- type = $type") logger.debug(" |- converter = $converter") } logger.debug("") logger.debug("-- end GraphQL Client generator configuration --") } }
0
Kotlin
0
0
02c6db99ebda23ea16411765a6d273d616e81cc3
8,310
graphql-multiplatform
Apache License 2.0
graphql-multiplatform-plugin/src/main/kotlin/xyz/mcxross/graphql/plugin/gradle/tasks/AbstractGenerateClientTask.kt
mcxross
785,636,958
false
{"Kotlin": 220816}
/* * Copyright 2023 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xyz.mcxross.graphql.plugin.gradle.tasks import java.io.File import javax.inject.Inject import org.gradle.api.DefaultTask import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Classpath import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.options.Option import org.gradle.workers.ClassLoaderWorkerSpec import org.gradle.workers.WorkQueue import org.gradle.workers.WorkerExecutor import xyz.mcxross.graphql.plugin.gradle.actions.GenerateClientAction import xyz.mcxross.graphql.plugin.gradle.config.GraphQLParserOptions import xyz.mcxross.graphql.plugin.gradle.config.GraphQLScalar import xyz.mcxross.graphql.plugin.gradle.config.GraphQLSerializer /** * Generate GraphQL Kotlin client and corresponding data classes based on the provided GraphQL * queries. */ abstract class AbstractGenerateClientTask : DefaultTask() { @get:Classpath val pluginClasspath: ConfigurableFileCollection = project.objects.fileCollection() /** * GraphQL schema file that will be used to generate client code. * * **Required Property** */ @InputFile val schemaFile: RegularFileProperty = project.objects.fileProperty() /** * Target package name for generated code. * * **Required Property** **Command line property is**: `packageName`. */ @Input @Option(option = "packageName", description = "target package name to use for generated classes") val packageName: Property<String> = project.objects.property(String::class.java) /** * Boolean flag indicating whether selection of deprecated fields is allowed or not. * * **Default value is:** `false`. **Command line property is**: `allowDeprecatedFields`. */ @Input @Optional @Option( option = "allowDeprecatedFields", description = "boolean flag indicating whether selection of deprecated fields is allowed or not", ) val allowDeprecatedFields: Property<Boolean> = project.objects.property(Boolean::class.java) /** * List of custom GraphQL scalar converters. * * ```kotlin * customScalars.add(GraphQLScalar("UUID", "java.util.UUID", "com.expediagroup.graphql.examples.client.UUIDScalarConverter")) * ) */ @Input @Optional val customScalars: ListProperty<GraphQLScalar> = project.objects.listProperty(GraphQLScalar::class.java) /** * Directory containing GraphQL queries. Defaults to `src/main/resources` when generating main * sources and `src/test/resources` when generating test client. * * Instead of specifying a directory you can also specify list of query file by using `queryFiles` * property instead. */ @InputDirectory @Optional val queryFileDirectory: DirectoryProperty = project.objects.directoryProperty() /** * List of query files to be processed. Instead of a list of files to be processed you can also * specify [queryFileDirectory] directory containing all the files. If this property is specified * it will take precedence over the corresponding directory property. */ @InputFiles @Optional val queryFiles: ConfigurableFileCollection = project.objects.fileCollection() @Input @Optional @Option( option = "serializer", description = "JSON serializer that will be used to generate the data classes.", ) val serializer: Property<GraphQLSerializer> = project.objects.property(GraphQLSerializer::class.java) @Input @Optional @Option( option = "useOptionalInputWrapper", description = "Opt-in flag to wrap nullable arguments in OptionalInput that supports both null and undefined.", ) val useOptionalInputWrapper: Property<Boolean> = project.objects.property(Boolean::class.java) @Input @Optional val parserOptions: Property<GraphQLParserOptions> = project.objects.property(GraphQLParserOptions::class.java) @OutputDirectory val outputDirectory: DirectoryProperty = project.objects.directoryProperty() @Inject abstract fun getWorkerExecutor(): WorkerExecutor init { group = "GraphQL" description = "Generate HTTP client from the specified GraphQL queries." allowDeprecatedFields.convention(false) customScalars.convention(emptyList()) serializer.convention(GraphQLSerializer.JACKSON) useOptionalInputWrapper.convention(false) parserOptions.convention(GraphQLParserOptions()) } @Suppress("EXPERIMENTAL_API_USAGE") @TaskAction fun generateGraphQLClientAction() { logger.debug("generating GraphQL client") val graphQLSchemaPath = when { schemaFile.isPresent -> schemaFile.get().asFile.path else -> throw RuntimeException("schema not available") } val targetPackage = packageName.orNull ?: throw RuntimeException("package not specified") val targetQueryFiles: List<File> = when { queryFiles.files.isNotEmpty() -> queryFiles.files.toList() queryFileDirectory.isPresent -> { queryFileDirectory.asFile.orNull ?.walkBottomUp() ?.filter { file -> file.extension == "graphql" } ?.toList() ?: throw RuntimeException("exception while looking up the query files") } else -> throw RuntimeException("no query files found") } if (targetQueryFiles.isEmpty()) { throw RuntimeException("no query files specified") } val targetDirectory = outputDirectory.get().asFile if (!targetDirectory.isDirectory && !targetDirectory.mkdirs()) { throw RuntimeException("failed to generate generated source directory = $targetDirectory") } logConfiguration(graphQLSchemaPath, targetQueryFiles) val workQueue: WorkQueue = getWorkerExecutor().classLoaderIsolation { workerSpec: ClassLoaderWorkerSpec -> workerSpec.classpath.from(pluginClasspath) logger.debug("worker classpath: \n${workerSpec.classpath.files.joinToString("\n")}") } workQueue.submit(GenerateClientAction::class.java) { parameters -> parameters.packageName.set(targetPackage) parameters.allowDeprecated.set(allowDeprecatedFields) parameters.customScalars.set(customScalars) parameters.serializer.set(serializer) parameters.schemaPath.set(graphQLSchemaPath) parameters.queryFiles.set(targetQueryFiles) parameters.targetDirectory.set(targetDirectory) parameters.useOptionalInputWrapper.set(useOptionalInputWrapper) parameters.parserOptions.set(parserOptions) } workQueue.await() logger.debug("successfully generated GraphQL HTTP client") } private fun logConfiguration(schemaPath: String, queryFiles: List<File>) { logger.debug("GraphQL Client generator configuration:") logger.debug(" schema file = $schemaPath") logger.debug(" queries") queryFiles.forEach { logger.debug(" - ${it.name}") } logger.debug(" packageName = $packageName") logger.debug(" allowDeprecatedFields = $allowDeprecatedFields") logger.debug(" parserOptions = $parserOptions") logger.debug(" converters") customScalars.get().forEach { (customScalar, type, converter) -> logger.debug(" - custom scalar = $customScalar") logger.debug(" |- type = $type") logger.debug(" |- converter = $converter") } logger.debug("") logger.debug("-- end GraphQL Client generator configuration --") } }
0
Kotlin
0
0
02c6db99ebda23ea16411765a6d273d616e81cc3
8,310
graphql-multiplatform
Apache License 2.0
app/src/main/java/com/shivamkumarjha/supaflix/ui/videoplayer/ProgressIndicator.kt
ShivamKumarJha
353,360,246
false
null
package com.shivamkumarjha.supaflix.ui.videoplayer import androidx.compose.foundation.background import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp @Composable fun ProgressIndicator( modifier: Modifier = Modifier ) { val controller = LocalVideoPlayerController.current val videoPlayerUiState by controller.collect() with(videoPlayerUiState) { SeekBar( progress = currentPosition, max = duration, enabled = controlsVisible && controlsEnabled, onSeek = { controller.previewSeekTo(it) }, onSeekStopped = { controller.seekTo(it) }, secondaryProgress = secondaryProgress, seekerPopup = { PlayerSurface( modifier = Modifier .height(48.dp) .width(48.dp * videoSize.first / videoSize.second) .background(Color.DarkGray) ) { controller.previewPlayerViewAvailable(it) } }, modifier = modifier ) } }
0
Kotlin
1
9
f027c8ae631b032b621ef2f33c8370b8919b7043
1,395
supaflix
MIT License
app/src/main/java/com/example/myapplication/reactingLists/removeCarrello.kt
AlessandraPastore
366,678,690
false
null
package com.example.myapplication.reactingLists import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Delete import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.myapplication.R import com.example.myapplication.ShowEmpty import com.example.myapplication.database.Ingrediente import com.example.myapplication.database.RicetteViewModel /* Composable che gestisce la lista degli ingredienti nel Carrello */ @Composable fun RemoveCarrello(model: RicetteViewModel) { // Lista degli ingredienti val ingredientList by model.listaCarrello.observeAsState() // Se la lista è vuota, mostro messaggio e immagine, altrimenti mostro la lista if(ingredientList != null) { if(ingredientList!!.isEmpty()) ShowEmpty(stringResource(R.string.carrello)) else ShowList(model, ingredientList!!) } } // Lista degli ingredienti nel carrello @Composable fun ShowList(model: RicetteViewModel, ingredientList: List<Ingrediente>) { // Funzione che istanzia la lista di ingredienti LazyColumn( modifier = Modifier.fillMaxWidth() ) { itemsIndexed(items = ingredientList, itemContent = { _, ingredient -> // Mostra il nome dell'ingrediente e il pulsante elimina Card( elevation = 5.dp, shape = RoundedCornerShape(4.dp), modifier = Modifier .fillParentMaxWidth() .padding(start = 10.dp, top = 5.dp, bottom = 5.dp, end = 10.dp) ) { Row( modifier = Modifier.fillParentMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( ingredient.ingrediente, style = TextStyle( fontSize = 20.sp, textAlign = TextAlign.Center ), modifier = Modifier.padding(16.dp) ) IconButton( onClick = { model.updateCarrello(ingredient.ingrediente, false) } ) { Icon(Icons.Rounded.Delete, "") } } } }) // Box trasparente che permette lo scroll degli item fino a sopra la BottomBar, rendendoli tutti visibili item { Box( modifier = Modifier .background(Color.Transparent) .height(100.dp) .fillMaxWidth() ) {} } } }
0
Kotlin
2
3
611b464414244f481713bc2cee0145d066b72a26
3,759
ComposeApplication
MIT License
app/src/main/java/info/guardianproject/notepadbot/MainActivity.kt
Theaninova
357,319,804
true
{"Java": 103885, "Kotlin": 95898}
package info.guardianproject.notepadbot import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.updatePadding import androidx.fragment.app.* import androidx.navigation.ui.onNavDestinationSelected import androidx.transition.Transition import com.google.android.material.transition.MaterialSharedAxis import info.guardianproject.notepadbot.cacheword.CacheWordActivityHandler import info.guardianproject.notepadbot.cacheword.CacheWordSettings import info.guardianproject.notepadbot.cacheword.ICacheWordSubscriber import info.guardianproject.notepadbot.cacheword.PRNGFixes import info.guardianproject.notepadbot.databinding.MainActivityBinding import info.guardianproject.notepadbot.fragments.LockScreenFragment import info.guardianproject.notepadbot.fragments.NotesFragment import info.guardianproject.notepadbot.fragments.SettingsFragment class MainActivity : AppCompatActivity(), ICacheWordSubscriber { private lateinit var _binding: MainActivityBinding val binding get() = _binding private var _cacheWord: CacheWordActivityHandler? = null val cacheWord get() = _cacheWord!! override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = MainActivityBinding.inflate(layoutInflater) setContentView(binding.root) _cacheWord = CacheWordActivityHandler(this, CacheWordSettings(applicationContext)) // Apply the Google PRNG fixes to properly seed SecureRandom PRNGFixes.apply() setSupportActionBar(binding.bottomAppBar) supportFragmentManager.commit { add<LockScreenFragment>(R.id.nav_host_fragment) } binding.bottomAppBar.performHide() binding.bottomAppBar.visibility = View.GONE // setupActionBarWithNavController(this, navController) // get around some weird behavior // navController.navigate(R.id.lockScreenFragment) WindowCompat.setDecorFitsSystemWindows(window, false) ViewCompat.setOnApplyWindowInsetsListener(binding.bottomAppBar) { v, insets -> val systemBarInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.updatePadding(bottom = systemBarInsets.bottom) insets } /*navController.addOnDestinationChangedListener { controller, destination, _ -> when (destination.id) { R.id.lockScreenFragment, R.id.setupFragment -> { binding.bottomAppBar.performHide() if (!cacheWord.isLocked) cacheWord.manuallyLock() } else -> { binding.bottomAppBar.visibility = View.VISIBLE binding.bottomAppBar.performShow() } } when (destination.id) { R.id.notesFragment -> binding.fab.show() else -> binding.fab.hide() } }*/ } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) binding.bottomAppBar.performHide() binding.fab.hide() } /*private fun findNavController(): NavController { val navHostFragment: NavHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment return NavHostFragment.findNavController(navHostFragment) }*/ override fun onOptionsItemSelected(item: MenuItem) = when(item.itemId) { R.id.lockScreenFragment -> true.also { cacheWord.manuallyLock() } else -> super.onOptionsItemSelected(item) } override fun onSupportNavigateUp(): Boolean { return /*findNavController().navigateUp() || */super.onSupportNavigateUp() } override fun onBackPressed() { // Yeah. I really hate that solution, but it seems to be pretty reliable /*when (findNavController().currentBackStackEntry?.destination?.id) { R.id.lockScreenFragment, R.id.setupFragment -> finish() else -> super.onBackPressed() }*/ super.onBackPressed() } override fun onCacheWordUninitialized() { // findNavController().navigate(R.id.setupFragment) } override fun onCacheWordLocked() = lock() override fun onCacheWordOpened() = unlock() fun lock() { val previousFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) if (previousFragment is LockScreenFragment) return supportFragmentManager.commit { val nextFragment = LockScreenFragment() previousFragment!!.exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) nextFragment.enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) replace(R.id.nav_host_fragment, nextFragment) } } fun unlock() { supportFragmentManager.commit { val previousFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) val nextFragment = NotesFragment() previousFragment!!.exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) nextFragment.enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) replace(R.id.nav_host_fragment, nextFragment) } } fun lockScreenToSettings() { supportFragmentManager.commit { val previousFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) val nextFragment = SettingsFragment() previousFragment!!.exitTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true) nextFragment.enterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true) nextFragment.returnTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false) previousFragment.reenterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false) replace(R.id.nav_host_fragment, nextFragment) addToBackStack(null) } } override fun onPause() { super.onPause() cacheWord.onPause() } override fun onResume() { super.onResume() cacheWord.onResume() } }
0
Java
0
0
445fdde8fd02f7a7d15d73186544d590186a2b71
6,378
notecipher
Apache License 2.0
src/pt/vizer/src/eu/kanade/tachiyomi/animeextension/pt/vizer/interceptor/WebViewResolver.kt
Kohi-den
817,607,446
false
{"Kotlin": 4095278}
package eu.kanade.tachiyomi.animeextension.pt.vizer.interceptor import android.annotation.SuppressLint import android.app.Application import android.os.Handler import android.os.Looper import android.util.Log import android.webkit.WebResourceRequest import android.webkit.WebResourceResponse import android.webkit.WebView import android.webkit.WebViewClient import okhttp3.Headers import uy.kohesive.injekt.injectLazy import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit class WebViewResolver(private val globalHeaders: Headers) { private val context: Application by injectLazy() private val handler by lazy { Handler(Looper.getMainLooper()) } private val tag by lazy { javaClass.simpleName } @SuppressLint("SetJavaScriptEnabled") fun getUrl(origRequestUrl: String, baseUrl: String): String? { val latch = CountDownLatch(1) var webView: WebView? = null var result: String? = null handler.post { val webview = WebView(context) webView = webview with(webview.settings) { javaScriptEnabled = true domStorageEnabled = true databaseEnabled = true useWideViewPort = false loadWithOverviewMode = false userAgentString = globalHeaders["User-Agent"] } webview.webViewClient = object : WebViewClient() { override fun shouldInterceptRequest( view: WebView, request: WebResourceRequest, ): WebResourceResponse? { val url = request.url.toString() Log.d(tag, "Checking url $url") if (VIDEO_REGEX.containsMatchIn(url)) { result = url latch.countDown() } return super.shouldInterceptRequest(view, request) } override fun onPageFinished(view: WebView?, url: String?) { Log.d(tag, "onPageFinished $url") super.onPageFinished(view, url) view?.evaluateJavascript("document.body.innerHTML += '<iframe src=\"" + origRequestUrl + "\" scrolling=\"no\" frameborder=\"0\" allowfullscreen=\"\" webkitallowfullscreen=\"\" mozallowfullscreen=\"\"></iframe>'") {} } } webView?.loadUrl(baseUrl) } latch.await(TIMEOUT_SEC, TimeUnit.SECONDS) handler.post { webView?.stopLoading() webView?.destroy() webView = null } return result } companion object { const val TIMEOUT_SEC: Long = 25 private val VIDEO_REGEX by lazy { Regex("//(mixdrop|streamtape|warezcdn)|/video/") } } }
99
Kotlin
39
169
992d85f0e1423a81d237b167026fb92dccfd28f5
2,841
extensions-source
Apache License 2.0
im-access/src/main/kotlin/com/qingzhu/imaccess/domain/value/UnRead.kt
nedphae
322,789,778
false
{"Kotlin": 744301, "ANTLR": 281490, "Java": 48298, "Dockerfile": 375}
package com.qingzhu.imaccess.domain.value data class UnRead( val unReadCount: Int, val totalCount: Int )
1
Kotlin
18
42
217b4658508763133e1a5b6a96763a14e9f6f4ad
113
contact-center
Apache License 2.0
advent2018/src/main/kotlin/com/github/rnelson/adventofcode/days/Day05.kt
rnelson
47,218,334
false
null
package com.github.rnelson.adventofcode.days import com.github.rnelson.adventofcode.Day class Day05: Day() { init { super.setup("05") } override fun solveA(): String { var newInput = input[0] var letterFound = true while (letterFound) { letterFound = false for (c in 'a'..'z') { val oneMix = "${c.uppercaseChar()}$c" val twoMix = "$c${c.uppercaseChar()}" var found = true while (found) { val fOneMix = newInput.indexOf(oneMix) val fTwoMix = newInput.indexOf(twoMix) if (fOneMix != -1) { newInput = newInput.replace(oneMix, "") letterFound = true } else if (fTwoMix != -1) { newInput = newInput.replace(twoMix, "") letterFound = true } else { found = false } } } } return newInput.length.toString() } override fun solveB(): String { val sizes = hashMapOf<Char, Int>() for (skip in 'a'..'z') { var newInput = input[0].replace(skip.toString(), "").replace(skip.toString().uppercase(), "") var letterFound = true while (letterFound) { letterFound = false for (c in 'a'..'z') { val oneMix = "${c.uppercaseChar()}$c" val twoMix = "$c${c.uppercaseChar()}" var found = true while (found) { val fOneMix = newInput.indexOf(oneMix) val fTwoMix = newInput.indexOf(twoMix) if (fOneMix != -1) { newInput = newInput.replace(oneMix, "") letterFound = true } else if (fTwoMix != -1) { newInput = newInput.replace(twoMix, "") letterFound = true } else { found = false } } } } sizes[skip] = newInput.length } return sizes.minByOrNull { it.value }?.value.toString() } }
0
C#
0
1
bd68571eee9a02a586ef3b2623c9d1928473cb34
2,457
adventofcode
MIT License
payment-method-messaging/src/main/java/com/stripe/android/paymentmethodmessaging/view/theme/Color.kt
stripe
6,926,049
false
null
package com.stripe.android.paymentmethodmessaging.view.theme import androidx.compose.ui.graphics.Color internal object Color { val ComponentDivider = Color(0x33787880) }
88
null
644
1,277
174b27b5a70f75a7bc66fdcce3142f1e51d809c8
176
stripe-android
MIT License
api-gateway/src/main/kotlin/org/tsdes/apigateway/Application.kt
BM0B0T
399,238,117
false
null
package org.tsdes.apigateway import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.cloud.client.discovery.EnableDiscoveryClient @EnableDiscoveryClient @SpringBootApplication class Application fun main(args: Array<String>) { SpringApplication.run(Application::class.java, *args) }
0
Kotlin
0
1
55822f3a340d67d1dd3df535f9f64554cc06aac9
378
PG6100-Tasks
Apache License 2.0
lib/src/commonMain/kotlin/fyi/modules/deviceinput/models/DeviceInputOptionalParameters.kt
infinitum-dev
196,228,013
false
{"JavaScript": 16552385, "HTML": 2087149, "Objective-C": 394320, "Kotlin": 187087, "CSS": 11934, "Java": 2533, "Ruby": 720, "Assembly": 24}
package fyi.modules.deviceinput.models import fyi.utils.Args import fyi.utils.OptionalParameters /** * Class that contains information about all the [OptionalParameters] the DeviceInput requests can have. * It also knows how this information should be constructed in the body of the request. * * @property mBuilder Builder responsible for setting the optional parameters. */ data class DeviceInputOptionalParameters private constructor( val mBuilder: Builder ): OptionalParameters { /** * Transform this [OptionalParameters] to a map */ override fun toMap(): MutableMap<String, String> { return Args.createMap( Pair("value", mBuilder.mValue), Pair("data", mBuilder.mData), Pair("action", mBuilder.mAction), Pair("name", mBuilder.mName) ) } /** * Builder class to facilitate the insertion of optional data. * * @property mValue DeviceInput value. * @property mData DeviceInput data. * @property mAction DeviceInput action. * @property mName DeviceInput name. */ class Builder() { var mValue = "" var mData = "" var mAction = "" var mName = "" fun setValue(value: String): Builder { mValue = value return this } fun setData(data: String): Builder { mData = data return this } fun setAction(action: String): Builder { mAction = action return this } fun setName(name: String): Builder { mName = name return this } fun build(): DeviceInputOptionalParameters { return DeviceInputOptionalParameters(this) } } }
0
JavaScript
0
0
f748c127221a6d304d7d306094ea24d3088abc59
1,774
mobile-sdk
MIT License
src/main/kotlin/main/data/persistence/TeamRepository.kt
SevenLakesHSUIL
164,341,141
false
{"HTML": 25830, "Kotlin": 20074, "CSS": 90}
package main.data.persistence import main.data.Division import main.data.Team import org.springframework.data.domain.Sort import org.springframework.data.repository.PagingAndSortingRepository import org.springframework.stereotype.Repository import org.springframework.transaction.annotation.Transactional import java.util.* @Repository @Transactional interface TeamRepository : PagingAndSortingRepository<Team, Int> { fun findByUsername(username: String): Optional<Team> fun findBySchool(school: String): Iterable<Team> fun findByDivision(division: Division): Iterable<Team> fun findByDivision(division: Division, sort: Sort): Iterable<Team> }
0
HTML
0
0
f5c7f13f65173621a3a78990f703a14fd9fbb082
662
UILCompSciWebsite
Apache License 2.0
radar-upload-backend/src/main/java/org/radarbase/upload/dto/LogsDto.kt
khoathanglong
209,331,061
false
null
package org.radarbase.upload.dto data class LogsDto(var url: String? = null, var contents: String? = null)
0
Kotlin
0
0
ebb2ff965d5203195b82a00d3ccc8f31f0d0f688
108
travis-playground
Apache License 2.0
app/src/main/java/br/com/wakim/eslpodclient/ui/podcastlist/view/PodcastListFragment.kt
wakim
52,843,851
false
null
package br.com.wakim.eslpodclient.ui.podcastlist.view import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.app.ShareCompat import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.PopupMenu import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import br.com.wakim.eslpodclient.R import br.com.wakim.eslpodclient.android.widget.BottomSpacingItemDecoration import br.com.wakim.eslpodclient.android.widget.SpacingItemDecoration import br.com.wakim.eslpodclient.dagger.PodcastPlayerComponent import br.com.wakim.eslpodclient.data.model.PodcastItem import br.com.wakim.eslpodclient.ui.podcastlist.adapter.PodcastListAdapter import br.com.wakim.eslpodclient.ui.podcastlist.presenter.PodcastListPresenter import br.com.wakim.eslpodclient.ui.podcastplayer.view.ListPlayerView import br.com.wakim.eslpodclient.ui.view.BaseActivity import br.com.wakim.eslpodclient.ui.view.BasePresenterFragment import br.com.wakim.eslpodclient.util.browseWithCustomTabs import br.com.wakim.eslpodclient.util.extensions.dp import br.com.wakim.eslpodclient.util.extensions.makeVisible import br.com.wakim.eslpodclient.util.extensions.startActivity import butterknife.BindView import java.util.* import javax.inject.Inject open class PodcastListFragment: BasePresenterFragment<PodcastListPresenter>(), PodcastListView { companion object { const val ITEMS_EXTRA = "ITEMS" const val NEXT_PAGE_TOKEN_EXTRA = "NEXT_PAGE_TOKEN" const val DOWNLOAD_PODCAST_EXTRA = "DOWNLOAD_PODCAST" const val USING_CACHE_EXTRA = "USING_CACHE" } override var hasMore: Boolean = false @BindView(R.id.recycler_view) lateinit var recyclerView: RecyclerView @BindView(R.id.swipe_refresh) lateinit var swipeRefresh: SwipeRefreshLayout val bottomSpacingDecoration = BottomSpacingItemDecoration(0) lateinit var adapter: PodcastListAdapter @Inject lateinit var baseActivity: BaseActivity @Inject lateinit var playerView: ListPlayerView @Inject fun injectPresenter(presenter: PodcastListPresenter) { presenter.view = this this.presenter = presenter } open fun inject() = (context.getSystemService(PodcastPlayerComponent::class.java.simpleName) as PodcastPlayerComponent).inject(this) override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater?.inflate(R.layout.fragment_podcastlist, container, false) override fun onActivityCreated(savedInstanceState: Bundle?) { inject() super.onActivityCreated(savedInstanceState) savedInstanceState?.let { val items: ArrayList<PodcastItem> = it.getParcelableArrayList(ITEMS_EXTRA) val token: String? = it.getString(NEXT_PAGE_TOKEN_EXTRA) val downloadPodcast: PodcastItem? = it.getParcelable(DOWNLOAD_PODCAST_EXTRA) val usingCache = it.getBoolean(USING_CACHE_EXTRA) presenter.onRestoreInstanceState(items, token, downloadPodcast, usingCache) } } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) outState?.let { it.putParcelableArrayList(ITEMS_EXTRA, presenter.items) it.putString(NEXT_PAGE_TOKEN_EXTRA, presenter.nextPageToken) it.putParcelable(DOWNLOAD_PODCAST_EXTRA, presenter.downloadPodcastItem) it.putBoolean(USING_CACHE_EXTRA, presenter.usingCache) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) configureAdapter() configureRecyclerView() swipeRefresh.apply { this.setOnRefreshListener { adapter.removeAll() presenter.onRefresh() isRefreshing = false } } super.onViewCreated(view, savedInstanceState) } fun share(podcastItem: PodcastItem) { presenter.share(podcastItem) } fun favorite(podcastItem: PodcastItem) { presenter.favorite(podcastItem) } fun download(podcastItem: PodcastItem) { presenter.download(podcastItem) } fun openWith(podcastItem: PodcastItem) { presenter.openWith(podcastItem) } fun configureAdapter() { adapter = PodcastListAdapter(context) adapter.clickListener = { podcastItem -> showPlayerViewIfNeeded() playerView.play(podcastItem) } adapter.overflowMenuClickListener = { podcastItem, anchor -> showPopupMenuFor(podcastItem, anchor) } } fun configureRecyclerView() { val hSpacing = dp(4) val vSpacing = dp(2) recyclerView.adapter = adapter recyclerView.addItemDecoration(SpacingItemDecoration(hSpacing, vSpacing, hSpacing, vSpacing)) recyclerView.addItemDecoration(bottomSpacingDecoration) recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val linearLayoutManager : LinearLayoutManager = recyclerView?.layoutManager as LinearLayoutManager val totalItemCount = linearLayoutManager.itemCount val lastVisible = linearLayoutManager.findLastVisibleItemPosition() val mustLoadMore = totalItemCount <= (lastVisible + PodcastListActivity.MINIMUM_THRESHOLD) if (mustLoadMore && hasMore && !adapter.loading) { presenter.loadNextPage() } } }) } open fun showPopupMenuFor(podcastItem: PodcastItem, anchor: View) { val popupMenu = PopupMenu(context, anchor) popupMenu.inflate(R.menu.podcast_item_menu) popupMenu.setOnMenuItemClickListener { menu -> when (menu.itemId) { R.id.share -> share(podcastItem) R.id.favorite -> favorite(podcastItem) R.id.download -> download(podcastItem) R.id.open_with -> openWith(podcastItem) } true } popupMenu.show() } fun showPlayerViewIfNeeded() { if (playerView.isVisible()) { return } playerView.makeVisible() bottomSpacingDecoration.bottomSpacing = dp(72) recyclerView.invalidateItemDecorations() } override fun addItems(list: ArrayList<PodcastItem>) { adapter.addAll(list) } override fun setItems(list: ArrayList<PodcastItem>) { adapter.setItems(list) } override fun addItem(podcastItem: PodcastItem) { adapter.add(podcastItem) } override fun share(text: String?) { ShareCompat.IntentBuilder.from(baseActivity) .setText(text) .setType("text/plain") .createChooserIntent() .startActivity(baseActivity) } override fun openUrlOnBrowser(url: String) { baseActivity.browseWithCustomTabs(url) } override fun remove(podcastItem: PodcastItem) { adapter.remove(podcastItem) } override fun setLoading(loading: Boolean) { adapter.loading = loading } override fun showMessage(messageResId: Int): Snackbar = baseActivity.showMessage(messageResId) override fun showMessage(messageResId: Int, action: String, clickListener: (() -> Unit)?) = baseActivity.showMessage(messageResId, action, clickListener) fun isSwipeRefreshEnabled() = if (view == null) false else swipeRefresh.isEnabled fun setSwipeRefreshEnabled(enabled: Boolean) { if (view != null) { swipeRefresh.isEnabled = enabled } } }
0
Kotlin
1
6
a92dad2832f087f97fcbf9b2b7973a31efde551c
8,047
esl-pod-client
Apache License 2.0
Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/forms/KatydidInputNumber.kt
martin-nordberg
131,987,610
false
null
// // (C) Copyright 2017-2019 <NAME> // Apache 2.0 License // package i.katydid.vdom.elements.forms import i.katydid.vdom.builders.KatydidPhrasingContentBuilderImpl import i.katydid.vdom.elements.KatydidHtmlElementImpl import o.katydid.vdom.builders.KatydidAttributesContentBuilder import o.katydid.vdom.types.EDirection //--------------------------------------------------------------------------------------------------------------------- /** * Virtual node for an input type="number" element. */ internal class KatydidInputNumber<Msg> : KatydidHtmlElementImpl<Msg> { constructor( phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>, selector: String?, key: Any?, accesskey: Char?, autocomplete: String?, autofocus: Boolean?, contenteditable: Boolean?, dir: EDirection?, disabled: Boolean?, draggable: Boolean?, form: String?, hidden: Boolean?, lang: String?, list: String?, max: Double?, min: Double?, name: String?, placeholder: String?, readonly: Boolean?, required: Boolean?, spellcheck: Boolean?, step: Double?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, value: Double?, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) : super(selector, key ?: name, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate) { phrasingContent.contentRestrictions.confirmInteractiveContentAllowed() if (min != null && max != null) { require(min <= max) {} } setAttribute("autocomplete", autocomplete) setBooleanAttribute("autofocus", autofocus) setBooleanAttribute("disabled", disabled) setAttribute("form", form) setAttribute("list", list) setNumberAttribute("max", max) setNumberAttribute("min", min) setAttribute("name", name) setAttribute("placeholder", placeholder) setBooleanAttribute("readonly", readonly) setBooleanAttribute("required", required) setNumberAttribute("step", step) setNumberAttribute("value", value) setAttribute("type", "number") phrasingContent.attributesContent(this).defineAttributes() this.freeze() } constructor( phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>, selector: String?, key: Any?, accesskey: Char?, autocomplete: String?, autofocus: Boolean?, contenteditable: Boolean?, dir: EDirection?, disabled: Boolean?, draggable: Boolean?, form: String?, hidden: Boolean?, lang: String?, list: String?, max: Int?, min: Int?, name: String?, placeholder: String?, readonly: Boolean?, required: Boolean?, spellcheck: Boolean?, step: Int?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, value: Int?, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) : super(selector, key ?: name, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate) { phrasingContent.contentRestrictions.confirmInteractiveContentAllowed() if (min != null && max != null) { require(min <= max) {} } setAttribute("autocomplete", autocomplete) setBooleanAttribute("autofocus", autofocus) setBooleanAttribute("disabled", disabled) setAttribute("form", form) setAttribute("list", list) setNumberAttribute("max", max) setNumberAttribute("min", min) setAttribute("name", name) setAttribute("placeholder", placeholder) setBooleanAttribute("readonly", readonly) setBooleanAttribute("required", required) setNumberAttribute("step", step) setNumberAttribute("value", value) setAttribute("type", "number") phrasingContent.attributesContent(this).defineAttributes() this.freeze() } //// override val nodeName = "INPUT" } //---------------------------------------------------------------------------------------------------------------------
1
Kotlin
1
6
8fcb99b2d96a003ff3168aef101eaa610e268bff
4,466
Katydid
Apache License 2.0
discovery-plugin-ui/src/main/kotlin/com/chimerapps/discovery/ui/SessionIconProvider.kt
Chimerapps
189,958,781
false
null
package com.chimerapps.discovery.ui import com.intellij.util.IconUtil import java.util.Base64 import javax.swing.Icon import javax.swing.ImageIcon interface SessionIconProvider { fun iconForString(iconString: String): Icon? } open class DefaultSessionIconProvider : SessionIconProvider { override fun iconForString(iconString: String): Icon? { return when (iconString) { "android" -> IncludedLibIcons.Icons.android "apple" -> IncludedLibIcons.Icons.apple "dart" -> IncludedLibIcons.Icons.dart "flutter" -> IncludedLibIcons.Icons.flutter else -> null } } } open class Base64SessionIconProvider( private val width: Float = 20.0f, private val height: Float = 20.0f, ) : SessionIconProvider { override fun iconForString(iconString: String): Icon? { try { val decoded = Base64.getDecoder().decode(iconString) val icon = ImageIcon(decoded) if (icon.image == null) return null return IconUtil.scale(icon, null, kotlin.math.min(width / icon.iconWidth, height / icon.iconHeight)) } catch (e: Throwable) { return null } } } open class CompoundSessionIconProvider(vararg initialProviders: SessionIconProvider) : SessionIconProvider { private val providers = mutableListOf<SessionIconProvider>().also { it.addAll(initialProviders) } fun addProvider(sessionIconProvider: SessionIconProvider) { providers += sessionIconProvider } override fun iconForString(iconString: String): Icon? { providers.forEach { provider -> provider.iconForString(iconString)?.let { return it } } return null } }
6
null
1
25
fc2e13fdc636ea3a025f75a8ed166fcf3157c06d
1,771
niddler-ui
Apache License 2.0
discovery-plugin-ui/src/main/kotlin/com/chimerapps/discovery/ui/SessionIconProvider.kt
Chimerapps
189,958,781
false
null
package com.chimerapps.discovery.ui import com.intellij.util.IconUtil import java.util.Base64 import javax.swing.Icon import javax.swing.ImageIcon interface SessionIconProvider { fun iconForString(iconString: String): Icon? } open class DefaultSessionIconProvider : SessionIconProvider { override fun iconForString(iconString: String): Icon? { return when (iconString) { "android" -> IncludedLibIcons.Icons.android "apple" -> IncludedLibIcons.Icons.apple "dart" -> IncludedLibIcons.Icons.dart "flutter" -> IncludedLibIcons.Icons.flutter else -> null } } } open class Base64SessionIconProvider( private val width: Float = 20.0f, private val height: Float = 20.0f, ) : SessionIconProvider { override fun iconForString(iconString: String): Icon? { try { val decoded = Base64.getDecoder().decode(iconString) val icon = ImageIcon(decoded) if (icon.image == null) return null return IconUtil.scale(icon, null, kotlin.math.min(width / icon.iconWidth, height / icon.iconHeight)) } catch (e: Throwable) { return null } } } open class CompoundSessionIconProvider(vararg initialProviders: SessionIconProvider) : SessionIconProvider { private val providers = mutableListOf<SessionIconProvider>().also { it.addAll(initialProviders) } fun addProvider(sessionIconProvider: SessionIconProvider) { providers += sessionIconProvider } override fun iconForString(iconString: String): Icon? { providers.forEach { provider -> provider.iconForString(iconString)?.let { return it } } return null } }
6
null
1
25
fc2e13fdc636ea3a025f75a8ed166fcf3157c06d
1,771
niddler-ui
Apache License 2.0
shared/java/top/fpsmaster/features/manager/ModuleManager.kt
FPSMasterTeam
816,161,662
false
{"Java": 620089, "Kotlin": 396547, "GLSL": 2647}
package top.fpsmaster.features.manager import net.minecraft.client.Minecraft import net.minecraft.client.gui.GuiScreen import org.lwjgl.input.Keyboard import top.fpsmaster.event.EventDispatcher.registerListener import top.fpsmaster.event.Subscribe import top.fpsmaster.event.events.* import top.fpsmaster.modules.logger.Logger.warn import top.fpsmaster.features.impl.interfaces.* import top.fpsmaster.features.impl.optimizes.* import top.fpsmaster.features.impl.render.* import top.fpsmaster.features.impl.utility.* import top.fpsmaster.interfaces.ProviderManager import top.fpsmaster.ui.click.MainPanel import top.fpsmaster.utils.Utility import java.util.* class ModuleManager { var modules = LinkedList<Module>() private val mainPanel: GuiScreen = MainPanel(true) fun getModule(mod: Class<*>): Module { for (module in modules) { if (module.javaClass == mod) { return module } } warn("Missing module:" + mod.name) return Module("missing module", "mission", Category.Utility) } @Subscribe fun onKey(e: EventKey) { if (e.key == ClickGui.keyBind.value) if (Minecraft.getMinecraft().currentScreen == null) Minecraft.getMinecraft() .displayGuiScreen(mainPanel) for (module in modules) { if (e.key == module.key) { module.toggle() } } } fun init() { // register listener registerListener(this) // add mods modules.add(ClickGui()) modules.add(BetterScreen()) modules.add(Sprint()) modules.add(Performance()) modules.add(MotionBlur()) modules.add(SmoothZoom()) modules.add(FullBright()) modules.add(ItemPhysics()) modules.add(MinimizedBobbing()) modules.add(MoreParticles()) modules.add(FPSDisplay()) modules.add(IRC()) modules.add(ArmorDisplay()) modules.add(BetterChat()) modules.add(ComboDisplay()) modules.add(CPSDisplay()) modules.add(PotionDisplay()) modules.add(ReachDisplay()) modules.add(Scoreboard()) modules.add(MusicOverlay()) modules.add(OldAnimations()) modules.add(HitColor()) modules.add(BlockOverlay()) modules.add(DragonWings()) modules.add(FireModifier()) modules.add(FreeLook()) modules.add(LyricsDisplay()) modules.add(SkinChanger()) modules.add(TimeChanger()) modules.add(TNTTimer()) modules.add(Hitboxes()) modules.add(LevelTag()) modules.add(Keystrokes()) modules.add(Crosshair()) modules.add(CustomFOV()) // modules.add(TabOverlay()) modules.add(InventoryDisplay()) modules.add(PlayerDisplay()) modules.add(TargetDisplay()) modules.add(NoHurtCam()) modules.add(NameProtect()) // modules.add(ChatBot()) // modules.add(Translator()) modules.add(RawInput()) modules.add(FixedInventory()) modules.add(NoHitDelay()) modules.add(PingDisplay()) modules.add(CoordsDisplay()) modules.add(ModsList()) modules.add(ClientCommand()) modules.add(MiniMap()) modules.add(DirectionDisplay()) if (ProviderManager.constants.getVersion() == "1.12.2") { modules.add(HideIndicator()) } } }
14
Java
34
97
34a00cc1834e80badd0df6f5d17ae027163d0ce9
3,441
FPSMaster
MIT License
linea/src/commonMain/kotlin/compose/icons/lineaicons/ecommerce/Diamond.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.lineaicons.ecommerce 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 compose.icons.lineaicons.EcommerceGroup public val EcommerceGroup.Diamond: ImageVector get() { if (_diamond != null) { return _diamond!! } _diamond = Builder(name = "Diamond", defaultWidth = 64.0.dp, defaultHeight = 64.0.dp, viewportWidth = 64.0f, viewportHeight = 64.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(29.0f, 6.0f) lineToRelative(17.0f, 0.0f) lineToRelative(17.0f, 21.0f) lineToRelative(-31.0f, 31.0f) lineToRelative(-31.0f, -31.0f) lineToRelative(17.0f, -21.0f) lineToRelative(14.0f, 0.0f) lineToRelative(0.0f, 52.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(32.0f, 57.0f) lineToRelative(-14.0f, -30.0f) lineToRelative(6.0f, -21.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(32.0f, 57.0f) lineToRelative(14.0f, -30.0f) lineToRelative(-6.0f, -21.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(1.0f, 27.0f) lineTo(63.0f, 27.0f) } } .build() return _diamond!! } private var _diamond: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,872
compose-icons
MIT License
kotlin/src/main/java/io/github/caoshen/androidadvance/kotlin/coroutine/FlowSample.kt
caoshen
290,115,293
false
{"Kotlin": 259354, "Java": 87268, "C++": 8150, "Groovy": 7542, "C": 4543, "CMake": 1798, "AIDL": 872, "Makefile": 693, "Shell": 658}
package io.github.caoshen.androidadvance.kotlin.coroutine import kotlinx.coroutines.* import kotlinx.coroutines.channels.produce import kotlinx.coroutines.flow.* import java.lang.IllegalStateException fun main() { // flowEmit() // flowOfFun() // flow2list() // onStartFun() // onStartFun2() // onCompleteFun() // cancelOnCompleteFun() // flowFirst() // flowSingle() // flowFold() // flowReduce() // flowCatch() // flowCatchDownStream() // flowTryCatch() // flowOn() // flowOnIO() // flowWithContext() // flowWithContextAll() // flowLaunchIn() flowCold() } fun flowEmit() = runBlocking { flow { emit(1) emit(2) emit(3) emit(4) emit(5) } .filter { it > 2 } .map { it * 2 } .take(2) .collect { // 6 8 println(it) } } fun flowFirst() = runBlocking { val first = flow { emit(1) emit(2) emit(3) emit(4) emit(5) } .filter { it > 2 } .map { it * 2 } .take(2) .first() // 6 println(first) } fun flowSingle() = runBlocking { val single = flow { emit(3) } .filter { it > 2 } .map { it * 2 } .take(2) .single() // 6 println(single) } fun flowFold() = runBlocking { val fold = flow { emit(1) emit(2) emit(3) emit(4) emit(5) }.filter { it > 2 }.map { it * 2 }.take(2) .fold(0) { acc, value -> acc + value } // 14 println(fold) } fun flowReduce() = runBlocking { val reduce = flow { emit(1) emit(2) emit(3) emit(4) emit(5) }.filter { it > 2 }.map { it * 2 }.take(2) .reduce { acc, value -> acc + value } // 14 println(reduce) } fun flowOfFun() = runBlocking { flowOf(1, 2, 3, 4, 5) .filter { it > 2 } .map { it * 2 } .take(2) .collect { // 6 8 println(it) } listOf(1, 2, 3, 4, 5) .filter { it > 2 } .map { it * 2 } .take(2) .forEach { // 6 8 println(it) } } fun flow2list() = runBlocking { flowOf(1, 2, 3, 4, 5) // flow to list .toList() .filter { it > 2 } .map { it * 2 } .take(2) .forEach { println(it) } listOf(1, 2, 3, 4, 5) // list as flow .asFlow() .filter { it > 2 } .map { it * 2 } .take(2) .collect { println(it) } } // flow lifecycle fun onStartFun() = runBlocking { flowOf(1, 2, 3, 4, 5) .filter { println("filter: $it") it > 2 } .map { println("map: $it") it * 2 } .take(2) .onStart { println("onStart") } .collect { println("collect: $it") } } fun onStartFun2() = runBlocking { flowOf(1, 2, 3, 4, 5) .take(2) .filter { println("filter: $it") it > 2 } .map { println("map: $it") it * 2 } .onStart { println("onStart") } .collect { println("collect: $it") } } fun onCompleteFun() = runBlocking { flowOf(1, 2, 3, 4, 5) .onCompletion { println("onCompletion") } .filter { println("filter: $it") it > 2 } .take(2) .collect { println("collect: $it") } } fun cancelOnCompleteFun() = runBlocking { launch { flow { emit(1) emit(2) emit(3) } // collect: 1 //collect: 2 //cancel //onCompletion first: kotlinx.coroutines.JobCancellationException .onCompletion { println("onCompletion first: $it") } .collect { println("collect: $it") if (it == 2) { // cancel flow cancel() println("cancel") } } } delay(1000) flowOf(4, 5, 6) // collect: 4 // onCompletion second: java.lang.IllegalStateException .onCompletion { println("onCompletion second: $it") } .collect { println("collect: $it") throw IllegalStateException() } } fun flowCatch() = runBlocking { val flow = flow { emit(1) emit(2) throw IllegalStateException() emit(3) } flow.map { it * 2 }.catch { println("catch: $it") }.collect { println(it) } // 2 // 4 // catch: java.lang.IllegalStateException } fun flowCatchDownStream() = runBlocking { val flow = flow { emit(1) emit(2) emit(3) } flow.map { it * 2 }.catch { println("catch: $it") }.filter { it / 0 > 1 }.collect { println(it) } // Exception in thread "main" java.lang.ArithmeticException: / by zero } fun flowTryCatch() = runBlocking { flowOf(4, 5, 6) .onCompletion { println("onCompletion second: $it") } .collect { try { println("collect: $it") throw IllegalStateException() } catch (e: Exception) { println("catch $e") } } // collect: 4 // catch java.lang.IllegalStateException // collect: 5 // catch java.lang.IllegalStateException // collect: 6 // catch java.lang.IllegalStateException // onCompletion second: null } fun flowOn() = runBlocking { val flow = flow { logX("Start") emit(1) logX("Emit: 1") emit(2) logX("Emit: 2") emit(3) logX("Emit: 3") } flow.filter { logX("Filter: $it") it > 2 } .flowOn(Dispatchers.IO) .collect { logX("Collect: $it") } // ================================ // Start // Thread:DefaultDispatcher-worker-1, time:1666096501866 // ================================ // ================================ // Filter: 1 // Thread:DefaultDispatcher-worker-1, time:1666096501917 // ================================ // ================================ // Emit: 1 // Thread:DefaultDispatcher-worker-1, time:1666096501917 // ================================ // ================================ // Filter: 2 // Thread:DefaultDispatcher-worker-1, time:1666096501917 // ================================ // ================================ // Emit: 2 // Thread:DefaultDispatcher-worker-1, time:1666096501917 // ================================ // ================================ // Filter: 3 // Thread:DefaultDispatcher-worker-1, time:1666096501917 // ================================ // ================================ // Emit: 3 // Thread:DefaultDispatcher-worker-1, time:1666096501917 // ================================ // ================================ // Collect: 3 // Thread:main, time:1666096501917 // ================================ } fun flowOnIO() = runBlocking { val flow = flow { logX("Start") emit(1) logX("Emit: 1") } flow.flowOn(Dispatchers.IO) .filter { logX("Filter: $it") it > 0 } .collect { logX("Collect: $it") } // ================================ // Start // Thread:DefaultDispatcher-worker-1, time:1666165816908 // ================================ // ================================ // Emit: 1 // Thread:DefaultDispatcher-worker-1, time:1666165816942 // ================================ // ================================ // Filter: 1 // Thread:main, time:1666165816944 // ================================ // ================================ // Collect: 1 // Thread:main, time:1666165816944 // ================================ } fun flowWithContext() = runBlocking { val flow = flow { logX("Start") emit(1) logX("Emit: 1") } flow.filter { logX("Filter: $it") it > 0 } .collect { // 不建议 withContext(Dispatchers.IO) { logX("Collect: $it") } } // ================================ // Start // Thread:main, time:1666167319244 // ================================ // ================================ // Filter: 1 // Thread:main, time:1666167319297 // ================================ // ================================ // Collect: 1 // Thread:DefaultDispatcher-worker-2, time:1666167319311 // ================================ // ================================ // Emit: 1 // Thread:main, time:1666167319312 // ================================ } fun flowWithContextAll() = runBlocking { val flow = flow { logX("Start") emit(1) logX("Emit: 1") } // 不建议 withContext(Dispatchers.IO) { flow.filter { logX("Filter: $it") it > 0 }.collect { logX("Collect: $it") } } // ================================ // Start // Thread:DefaultDispatcher-worker-1, time:1666167769589 // ================================ // ================================ // Filter: 1 // Thread:DefaultDispatcher-worker-1, time:1666167769645 // ================================ // ================================ // Collect: 1 // Thread:DefaultDispatcher-worker-1, time:1666167769645 // ================================ // ================================ // Emit: 1 // Thread:DefaultDispatcher-worker-1, time:1666167769645 // ================================ } fun flowLaunchIn() = runBlocking { val flow = flow { logX("Start") emit(1) logX("Emit: 1") } val scope = CoroutineScope(mySingleDispatcher) flow.flowOn(Dispatchers.IO) .filter { logX("Filter: $it") it > 0 }.onEach { logX("Collect: $it") }.launchIn(scope) delay(100L) // ================================ // Start // Thread:DefaultDispatcher-worker-1, time:1666168824669 // ================================ // ================================ // Emit: 1 // Thread:DefaultDispatcher-worker-1, time:1666168824704 // ================================ // ================================ // Filter: 1 // Thread:mySingleThread, time:1666168824706 // ================================ // ================================ // Collect: 1 // Thread:mySingleThread, time:1666168824706 // ================================ } fun flowCold() = runBlocking { val flow = flow { (1..3).forEach { println("Before send $it") emit(it) println("Send $it") } } val channel = produce<Int>(capacity = 0) { (1..3).forEach { println("Before send $it") send(it) println("Send $it") } } println("end") // end // Before send 1 }
0
Kotlin
0
2
ffbab9c08d2446b24d45282489f218580eb7ecfa
11,740
AndroidAdvance
MIT License
app/src/main/java/com/teamsixers/vmail/ui/BaseActivity.kt
cyrilwongmy
368,865,227
false
null
package com.teamsixers.vmail.ui import android.Manifest import android.content.Context import android.media.MediaPlayer import android.os.Bundle import android.speech.tts.TextToSpeech import android.speech.tts.UtteranceProgressListener import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.iflytek.cloud.* import com.iflytek.cloud.util.ResourceUtil import com.permissionx.guolindev.PermissionX import com.teamsixers.vmail.R import com.teamsixers.vmail.ui.voiceSupport.AsrSupport import com.teamsixers.vmail.ui.voiceSupport.PassiveListeningSupport import com.teamsixers.vmail.ui.voiceSupport.TextToSpeechSupport import com.teamsixers.vmail.utils.JsonParser import org.json.JSONException import org.json.JSONObject import java.util.* /** * All activities that needs TextToSpeech, Auto Speech Recognition, and * voice wakeup support in the VMail should inherit this class. * * Subclass should override idleState, and assign the IdleState instance */ abstract class BaseActivity : AppCompatActivity(), InitListener, AsrSupport, PassiveListeningSupport, TextToSpeechSupport { companion object { /** * TAG is used for logger */ val TAG: String = this::class.java.simpleName } /** * MediaPlayer for starting ASR notification. */ lateinit var mStartAsrMediaPlayer: MediaPlayer /** * MediaPlayer for end ASR notification. */ lateinit var mEndAsrMediaPlayer: MediaPlayer /** * Voice wakuper instacne */ override lateinit var mIvw: VoiceWakeuper /** * Auto Speech Recognition instance. */ override lateinit var mAsr: SpeechRecognizer /** * The idle state for every activity. * When no task is performed in the activity, * the activity should change to this state. * * idleState of each activity can be different. */ open lateinit var idleState: State /** * Current state of current activity. */ open lateinit var state: State /** * Temporary storage for recognition result to convert * result to string. */ override val mAsrResults: HashMap<Int, String> = LinkedHashMap() /** * WakeuperListener is used for registering funtions when * wakuper state is changed. */ override var mWakeUperListener: WakeuperListener = object : WakeuperListener { /** * When wakuper is wake up, start auto speech recognition. */ override fun onResult(result: WakeuperResult) { Log.d(TAG, "Wakuper onResult Function start") try { val text = result.resultString val jsonObject = JSONObject(text) val buffer = StringBuffer().apply { append("[RAW] $text") append("\n") append("[Operation type]" + jsonObject.optString("sst")) append("\n") append("wakeup id" + jsonObject.optString("id")) append("\n") append("[Score]" + jsonObject.optString("score")) append("\n") append("[Front End]" + jsonObject.optString("bos")) append("\n") append("[End point]" + jsonObject.optString("eos")) } wakeUpResultString = buffer.toString() // stop TTS if (::textToSpeechEngine.isInitialized) { textToSpeechEngine.stop() } if (::mAsr.isInitialized) { mAsr.stopListening() } startActiveListening(this@BaseActivity) } catch (e: JSONException) { wakeUpResultString = "Voice wakeup fails parsing" e.printStackTrace() } Log.d(TAG, "ResultString: $wakeUpResultString") } /** * When wakuper is on the error state, print error message. */ override fun onError(error: SpeechError) { Log.d(TAG, "ErrorCode: ${error.errorCode}") Log.d(TAG, "ErrorDesc: ${error.errorDescription}") } /** * Nothing performed when begin of speech. */ override fun onBeginOfSpeech() {} /** * Response to different events. */ override fun onEvent(eventType: Int, isLast: Int, arg2: Int, obj: Bundle) { when (eventType) { SpeechEvent.EVENT_RECORD_DATA -> { val audio = obj.getByteArray(SpeechEvent.KEY_EVENT_RECORD_DATA) Log.i("LoginActivity", "ivw audio length: " + audio!!.size) } } } /** * Perform nothing on volume change. */ override fun onVolumeChanged(volume: Int) {} } /** * The wake up string. */ override var wakeUpResultString: String = "" /** * Text to speech Engine. */ override lateinit var textToSpeechEngine: TextToSpeech /** * BaseActivity onCreate state will initialize * ASR, wakuper, and requests permissions. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Initialize ASR recognition singleton mAsr = SpeechRecognizer.createRecognizer(this, mInitListener) setAsrParameter() // Initialize Wakeuper singleton mIvw = VoiceWakeuper.createWakeuper(this, null) mStartAsrMediaPlayer = MediaPlayer.create(this, R.raw.notifysound) mEndAsrMediaPlayer = MediaPlayer.create(this, R.raw.endasrsound) mStartAsrMediaPlayer.setOnCompletionListener { Log.d("BaseActivity", "on complete playing notfiy sound...") super.startActiveListening(this) } PermissionX.init(this) .permissions(Manifest.permission.RECORD_AUDIO) .request { allGranted, grantedList, deniedList -> if (allGranted) { } else { Toast.makeText(this, "These permissions are denied: $deniedList", Toast.LENGTH_LONG).show() } } } /** * Change to auto speech recognition listening state. * Start listening to user input voice for recognition. */ override fun startActiveListening(context: Context) { if (::textToSpeechEngine.isInitialized) { textToSpeechEngine.stop() textToSpeechEngine.shutdown() } mStartAsrMediaPlayer.start() } /** * Wrap up Text to speech function in TextToSpeechSupport. * BaseActivity should stop auto speech recognition listening state * to avoid recording the voice-to-text sound during voice recognition * * Method should be called from activity. * * @sample textToSpeech("Hello from VMail") * * @author <NAME> * * @since 2.0 */ override fun textToSpeech(inputText: String) { // Before starting TTS, make sure stop ASR. mAsr.stopListening() mAsr.cancel() super.textToSpeech(inputText, utteranceProgressListener) } /** * Start TTS, end TTS, and TTS error will execute the corresponding function. * The tasks to be completed in these three corresponding states should be implemented * onTTSStart, onTTSDone, and onTTSError functions to complete. * Specifically, what to do should be implemented by subclass acitvities. * * @author Mingyan(<NAME> * * @since 2.0 */ private val utteranceProgressListener = object: UtteranceProgressListener() { override fun onStart(utteranceId: String?) { onTTSStart() } override fun onDone(utteranceId: String?) { onTTSDone() } override fun onError(utteranceId: String?) { onTTSError() } } /** * When text to speech starts, the method will be called. * @since 2.0 * * @author <NAME> */ abstract fun onTTSStart() /** * When text to speech finishes, the method will be called. * @since 2.0 * * @author Mingyan(Cyril) Wang */ abstract fun onTTSDone() /** * When text to speech encounters an error, the method will be called. * @since 2.0 * * @author Mingyan(Cyril) Wang */ abstract fun onTTSError() /** * on initialize ASR listener. * * @since 2.0 * * @author Mingyan(<NAME> */ override fun onInit(p0: Int) { } /** * Wake up needs local resources given by IFLYTEK corresponding to hotword * * @since 2.0 * * @author <NAME> */ override fun getResource(): String? { val resPath = ResourceUtil.generateResourcePath(this, ResourceUtil.RESOURCE_TYPE.assets, "ivw/" + getString(R.string.app_id) + ".jet") Log.d("LoginActivity", "resPath: $resPath") return resPath } /** * activity will change to idleState when onResume state * * @since 2.0 * * @author <NAME> */ override fun onResume() { super.onResume() if (idleState != null) { state = idleState } else { throw RuntimeException("idleState variable should be assigned value.") } startPassiveListening() } /** * onPause activity should stop ASR, TTS, Wakeuper. * * @since 2.0 * * @author <NAME> */ override fun onPause() { super.onPause() Log.d("BaseActivity", "onPause is called") // stop wakeuper if (mIvw != null) { mIvw.stopListening() mIvw.cancel() } // stop textToSpeech if (::textToSpeechEngine.isInitialized) { textToSpeechEngine.stop() textToSpeechEngine.shutdown() } // stop ASR (voice recognition) if (mAsr != null) { // stop listening firstly. mAsr.stopListening() // cancel current ASR conversation, // discarding results that have not returned yet. mAsr.cancel() } } /** * onDestroy activity should free ASR resources. * * @since 2.0 * * @author <NAME> */ override fun onDestroy() { super.onDestroy() // release connection to voice recognition when exits current activity. if (null != mAsr) { // 退出时释放连接 mAsr.cancel() mAsr.destroy() } } /** * Initialize ASR initialized listener. * * @since 2.0 * * @author <NAME> */ override val mInitListener = InitListener { code -> Log.d(TAG, "SpeechRecognizer init() code = $code") if (code == ErrorCode.SUCCESS) { Log.d(TAG, "SpeechRecognizer init() success!") } else { Log.e(TAG, "Initialization failure, error code:$code, click https://www.xfyun.cn/document/error-code to look for solution.") } } /** * Initialize ASR listener. */ override val mRecogListener: RecognizerListener = object : RecognizerListener { override fun onVolumeChanged(p0: Int, p1: ByteArray?) { } override fun onBeginOfSpeech() { } /** * Play notification sound on end of speech recording. * * stopListening() function will not call this function. * * @since 2.0 * * @author <NAME> * */ override fun onEndOfSpeech() { mEndAsrMediaPlayer.start() } /** * When get recognition and parse json to a result string, * this method will be called. * This method will call onAsrSuccess() * * @since 2.0 * * @author <NAME> */ override fun onResult(asrResult: RecognizerResult, isLast: Boolean) { if (!isLast) { JsonParser.getResultString(mAsrResults, asrResult) for (key in mAsrResults.keys) { val recognitionResult: String = if (mAsrResults[key] == null) { "" } else { mAsrResults[key].toString() } Log.d(TAG, "recognitionResult: $recognitionResult") onAsrSuccess(recognitionResult) } } } override fun onError(speechError: SpeechError) { onAsrError(speechError) } override fun onEvent(p0: Int, p1: Int, p2: Int, p3: Bundle?) { } } }
0
Kotlin
0
1
5424a29c5678f33c9c599a84b9b81b3aee086aff
12,889
VMaiL
MIT License
app/src/main/java/com/hamzaazman/kotlinfreetoplay/domain/datastore/DataStoreRepository.kt
hamzaazman
646,586,066
false
null
package com.hamzaazman.kotlinfreetoplay.domain.datastore interface DataStoreRepository { suspend fun putString(key: String, value: String) suspend fun getString(key: String): String? }
0
Kotlin
0
9
d484dee71ca7eba00a09a072b6a831032b363aa4
193
KotlinFreeToGame
MIT License
kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/v2/SpringPluginInitializer.kt
bpowell
289,352,460
false
{"Gradle": 40, "CODEOWNERS": 1, "Shell": 3, "INI": 2, "Markdown": 8, "Ignore List": 1, "Batchfile": 1, "YAML": 15, "EditorConfig": 1, "Text": 2, "Java": 268, "Kotlin": 201, "Groovy": 30, "Java Properties": 3, "JavaScript": 1, "Protocol Buffer": 1, "HTML": 1, "XML": 6}
/* * Copyright 2020 Netflix, 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 com.netflix.spinnaker.kork.plugins.v2 import com.netflix.spinnaker.kork.plugins.api.ExtensionConfiguration import com.netflix.spinnaker.kork.plugins.api.PluginComponent import com.netflix.spinnaker.kork.plugins.api.PluginConfiguration import com.netflix.spinnaker.kork.plugins.api.internal.SpinnakerExtensionPoint import org.pf4j.Plugin import org.pf4j.PluginWrapper import org.slf4j.LoggerFactory import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.context.annotation.ClassPathBeanDefinitionScanner import org.springframework.context.support.GenericApplicationContext import org.springframework.core.io.DefaultResourceLoader import org.springframework.core.type.filter.AnnotationTypeFilter import org.springframework.core.type.filter.AssignableTypeFilter /** * Initializes the given [plugin]'s [pluginApplicationContext] after being connected to the service's * own [ApplicationContext]. */ class SpringPluginInitializer( private val plugin: Plugin, private val pluginWrapper: PluginWrapper, private val pluginApplicationContext: GenericApplicationContext, private val beanPromoter: BeanPromoter ) : ApplicationContextAware { private val log by lazy { LoggerFactory.getLogger(javaClass) } override fun setApplicationContext(applicationContext: ApplicationContext) { log.info("Initializing '${pluginWrapper.pluginId}'") // For every bean created in the plugin ApplicationContext, we'll need to post-process to evaluate // which ones need to be promoted to the service ApplicationContext for autowiring into core functionality. pluginApplicationContext .beanFactory .addBeanPostProcessor(ExtensionPromotionBeanPostProcessor( pluginWrapper, pluginApplicationContext, beanPromoter )) pluginApplicationContext.classLoader = pluginWrapper.pluginClassLoader pluginApplicationContext.setResourceLoader(DefaultResourceLoader(pluginWrapper.pluginClassLoader)) pluginApplicationContext.scanForComponents() pluginApplicationContext.refresh() } private fun GenericApplicationContext.scanForComponents() { val scanner = ClassPathBeanDefinitionScanner(this, false, environment) .apply { addIncludeFilter(AnnotationTypeFilter(PluginComponent::class.java)) addIncludeFilter(AssignableTypeFilter(SpinnakerExtensionPoint::class.java)) // TODO(rz): We'll need FactoryBeans for these types of components in order for them to be // created correctly. addIncludeFilter(AnnotationTypeFilter(PluginConfiguration::class.java)) addIncludeFilter(AnnotationTypeFilter(ExtensionConfiguration::class.java)) } scanner.scan(plugin.javaClass.`package`.name) } }
1
null
1
1
a0545f4f6e50ca2e403ad4b7571320776e8085e1
3,394
kork
Apache License 2.0
collect_app/src/androidTest/java/org/odk/collect/android/support/CollectHelpers.kt
pompel123
589,582,628
true
{"Java Properties": 6, "Gradle": 34, "Shell": 3, "YAML": 3, "INI": 30, "Markdown": 21, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 32, "XML": 529, "Kotlin": 556, "Java": 779, "Text": 2, "JSON": 4, "JavaScript": 1, "Proguard": 3, "Gradle Kotlin DSL": 4}
package org.odk.collect.android.support import androidx.test.core.app.ApplicationProvider import org.odk.collect.android.application.Collect import org.odk.collect.android.injection.config.AppDependencyComponent import org.odk.collect.android.injection.config.AppDependencyModule import org.odk.collect.android.injection.config.DaggerAppDependencyComponent object CollectHelpers { fun overrideAppDependencyModule(appDependencyModule: AppDependencyModule): AppDependencyComponent { val application = ApplicationProvider.getApplicationContext<Collect>() val testComponent = DaggerAppDependencyComponent.builder() .application(application) .appDependencyModule(appDependencyModule) .build() application.component = testComponent return testComponent } }
0
null
0
1
83d5b82a51de96d0483d433a5475e3ff043bf0b6
829
collect
Apache License 2.0
app/src/test/kotlin/com/k0d4black/theforce/utils/SampleData.kt
serdaroz
239,109,936
true
{"Kotlin": 95834}
package com.k0d4black.theforce.utils import com.k0d4black.theforce.domain.models.StarWarsCharacter import com.k0d4black.theforce.domain.models.StarWarsCharacterFilm import com.k0d4black.theforce.domain.models.StarWarsCharacterPlanet import com.k0d4black.theforce.domain.models.StarWarsCharacterSpecies object SampleData { val speciesDomainModel = listOf( StarWarsCharacterSpecies( name = "name", language = "language" ) ) val characterFilms = listOf( StarWarsCharacterFilm( title = "title", openingCrawl = "opening crawl" ) ) val planetDomainModel = StarWarsCharacterPlanet( name = "name", population = "100000" ) val searchResults = listOf( StarWarsCharacter( "Darth Vader", "12BBY", "123", "https://swapi.co/api/species/2/" ) ) }
0
null
0
2
0378e8f49ac431941b68db5c1db10183a61d7c13
945
Clean-MVVM-ArchComponents-
Apache License 2.0
src/main/kotlin/adventofcode2020/Day02PasswordPhilosophy.kt
n81ur3
484,801,748
false
null
package adventofcode2020 class Day02PasswordPhilosophy data class PasswordEntry(val line: String) { val lowerLimit: Int val upperLimit: Int val character: Char val entry: String init { val parts = line.split(" ") require(parts.size == 3) lowerLimit = parts[0].split("-")[0].toInt() upperLimit = parts[0].split("-")[1].toInt() character = parts[1].split(":")[0][0] entry = parts[2] } fun isValid(): Boolean { val characterCount = entry.filter { it == character }.count() return characterCount in lowerLimit..upperLimit } fun isValidPartTwo(): Boolean = (entry[lowerLimit - 1] == character) xor (entry[upperLimit - 1] == character) override fun toString(): String { return "PasswordEntry(lowerLimit=$lowerLimit, upperLimit=$upperLimit, character=$character, entry='$entry')" } }
0
Kotlin
0
0
4f9a42592fc92d1ddf8271db6db5d30f365c352e
898
kotlin-coding-challenges
MIT License
core/src/main/java/com/ocean/core/framework/network/dispose/Process.kt
zhangxianjie-c
498,578,100
false
{"Kotlin": 52822}
package com.ocean.core.framework.network.dispose import androidx.lifecycle.* import com.ocean.core.framework.network.dispose.extend.RequestManager import com.ocean.core.framework.network.dispose.extend.ResponseManager import com.ocean.core.framework.network.dispose.pack.Response import com.ocean.core.framework.network.dispose.pack.Result import com.ocean.core.framework.network.exception.Error import com.ocean.core.framework.network.exception.NetWorkException import com.ocean.core.framework.network.getJSONFields import kotlinx.coroutines.* /** Created by Zebra-RD张先杰 on 2022年7月12日10:22:01 Description:对请求和响应最主要的处理 */ //这一步是把请求和响应的处理封装一下 fun request(data: MutableLiveData<Result>, request: suspend () -> Response) { //对request网络请求进行封装 val requestManager = RequestManager(request) //对response返回类型的设置进行封装 val responseManager = ResponseManager(data) //使用协程来进行线程控制 GlobalScope.launch(Dispatchers.IO) { //把请求和响应的处理逻辑单独封装起来 execute(requestManager, responseManager) } } //这一步是有真正执行请求的方法 private suspend fun execute( requestManager: RequestManager, responseManager: ResponseManager, ) { responseManager.isReturn = false //若请求时间超过500毫秒,回调 GlobalScope.launch(Dispatchers.IO) { delay(500) withContext(Dispatchers.Main){ if (!responseManager.isReturn){ responseManager.onLoading() } } } //进行网络请求 requestManager.request(onSuccess = { //没拦截到异常时回调该函数体 //若errcode = 0 ,则让Response走onSuccess() 并返回data与message if (this.isSuccess())responseManager.onSuccess(this.data.toString(), this.message) //否则的话 走onError() 并返回接口中的message else responseManager.onError(NetWorkException(this.errcode,this.message.toString())) }, onError = { //拦截到异常了就会回调该函数体 this.printStackTrace() if (this is TimeoutCancellationException) { responseManager.onTimeOut() } else { responseManager.onError(NetWorkException.transitionException(this)) } }) //把请求的状态置为请求中,这样设置加载动画什么的不需要在掺在业务逻辑中了,而是在网络请求的响应中 } fun MutableLiveData<Result>.response( lifecycleOwner: LifecycleOwner, loading: (() -> Unit)? = null, timeOut: (() -> Unit)? = null, error: ((exception: NetWorkException) -> Unit)? = null, success: ((data: String, m: String) -> Unit)? = null, ) { val observer = Observer<Result> { if (it != null) { it.apply { when (status) { Result.Loading -> { loading?.invoke() } Result.Success -> { success?.invoke(response, it.message) } Result.Failure -> { error?.invoke(exception) } Result.TimeOut -> { timeOut?.invoke() } } } } else { error?.invoke(NetWorkException(Error.RESULT_NULL,null)) } } this.observe(lifecycleOwner, observer) val eventObserver = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_DESTROY) { this.removeObserver(observer) } } lifecycleOwner.lifecycle.addObserver(eventObserver) } /** * 转换数据格式 把String转换成Response * 没办法 官方的转换器没办法定制转换 */ suspend fun transition(request: suspend () -> String): Response { val dataString = request.invoke() return Response().apply { errcode = dataString.getJSONFields("errcode").toInt() message = dataString.getJSONFields("message") data = dataString.getJSONFields("data") } }
0
Kotlin
0
1
4cd7d1022918727f6a7133f6644938ea48c32773
3,723
sdk-ocean-core
Apache License 2.0
app/src/main/java/app/airsignal/weather/firebase/admob/AdMobListener.kt
tekken5953
611,614,821
false
{"Kotlin": 399092, "Java": 2271}
package app.airsignal.weather.firebase.admob import app.airsignal.weather.firebase.db.RDBLogcat.writeAdError import com.google.android.gms.ads.AdListener import com.google.android.gms.ads.LoadAdError import com.orhanobut.logger.Logger open class AdMobListener : AdListener() { override fun onAdFailedToLoad(p0: LoadAdError) { super.onAdFailedToLoad(p0) Logger.t("TAG_AD").e("Fail to load Admob :" + " response : ${p0.responseInfo}" + " code : ${p0.code}" + " msg : ${p0.message}" + " cause : ${p0.cause}") writeAdError(p0.code.toString(), " response : ${p0.responseInfo}" + " msg : ${p0.message}" + " cause : ${p0.cause}" ) } override fun onAdLoaded() { super.onAdLoaded() Logger.t("TAG_AD").i("Success to load Admob") } }
0
Kotlin
0
1
1fec24a292730a9e48fcbd83936fb728ec937f02
905
AS_Cloud_App
Open Market License
korma/src/commonMain/kotlin/com/soywiz/korma/geom/triangle/Triangle.kt
dmitrykolesnikovich
419,672,054
true
{"Kotlin": 811832, "Shell": 1701, "Batchfile": 1527}
package com.soywiz.korma.geom.triangle import com.soywiz.korma.geom.* import kotlin.math.* val Triangle.center get() = Point((p0.x + p1.x + p2.x) / 3, (p0.y + p1.y + p2.y) / 3) interface Triangle { val p0: IPoint val p1: IPoint val p2: IPoint data class Base(override val p0: IPoint, override val p1: IPoint, override val p2: IPoint) : Triangle companion object { private const val EPSILON: Double = 1e-12 fun area(p1: IPoint, p2: IPoint, p3: IPoint): Double = area(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y) fun area(ax: Double, ay: Double, bx: Double, by: Double, cx: Double, cy: Double): Double { val a = bx - ax val b = by - ay val c = cx - ax val d = cy - ay return abs(a * d - c * b) / 2f } fun getNotCommonVertexIndex(t1: Triangle, t2: Triangle): Int { var sum = 0 var index: Int = -1 if (!t2.containsPoint(t1.point(0))) { index = 0 sum++ } if (!t2.containsPoint(t1.point(1))) { index = 1 sum++ } if (!t2.containsPoint(t1.point(2))) { index = 2 sum++ } if (sum != 1) throw Error("Triangles are not contiguous") return index } fun getNotCommonVertex(t1: Triangle, t2: Triangle): IPoint = t1.point(getNotCommonVertexIndex(t1, t2)) fun getUniquePointsFromTriangles(triangles: List<Triangle>) = triangles.flatMap { listOf(it.p0, it.p1, it.p2) }.distinct() fun insideIncircle(pa: IPoint, pb: IPoint, pc: IPoint, pd: IPoint): Boolean { val adx = pa.x - pd.x val ady = pa.y - pd.y val bdx = pb.x - pd.x val bdy = pb.y - pd.y val adxbdy = adx * bdy val bdxady = bdx * ady val oabd = adxbdy - bdxady if (oabd <= 0) return false val cdx = pc.x - pd.x val cdy = pc.y - pd.y val cdxady = cdx * ady val adxcdy = adx * cdy val ocad = cdxady - adxcdy if (ocad <= 0) return false val bdxcdy = bdx * cdy val cdxbdy = cdx * bdy val alift = adx * adx + ady * ady val blift = bdx * bdx + bdy * bdy val clift = cdx * cdx + cdy * cdy val det = alift * (bdxcdy - cdxbdy) + blift * ocad + clift * oabd return det > 0 } fun inScanArea(pa: IPoint, pb: IPoint, pc: IPoint, pd: IPoint): Boolean { val pdx = pd.x val pdy = pd.y val adx = pa.x - pdx val ady = pa.y - pdy val bdx = pb.x - pdx val bdy = pb.y - pdy val adxbdy = adx * bdy val bdxady = bdx * ady val oabd = adxbdy - bdxady if (oabd <= EPSILON) return false val cdx = pc.x - pdx val cdy = pc.y - pdy val cdxady = cdx * ady val adxcdy = adx * cdy val ocad = cdxady - adxcdy if (ocad <= EPSILON) return false return true } } } fun Triangle.point(index: Int) = when (index) { 0 -> p0 1 -> p1 2 -> p2 else -> error("Invalid triangle point index $index") } /** * Test if this Triangle contains the Point2d object given as parameter as its vertices. * * @return <code>True</code> if the Point2d objects are of the Triangle's vertices, * <code>false</code> otherwise. */ fun Triangle.containsPoint(point: IPoint): Boolean = (point == p0) || (point == p1) || (point == p2) /** * Test if this Triangle contains the Edge object given as parameters as its bounding edges. * @return <code>True</code> if the Edge objects are of the Triangle's bounding * edges, <code>false</code> otherwise. */ // In a triangle to check if contains and edge is enough to check if it contains the two vertices. fun Triangle.containsEdge(edge: Edge): Boolean = containsEdgePoints(edge.p, edge.q) // In a triangle to check if contains and edge is enough to check if it contains the two vertices. fun Triangle.containsEdgePoints(p1: IPoint, p2: IPoint): Boolean = containsPoint(p1) && containsPoint(p2) private fun _product(p1x: Double, p1y: Double, p2x: Double, p2y: Double, p3x: Double, p3y: Double): Double = (p1x - p3x) * (p2y - p3y) - (p1y - p3y) * (p2x - p3x) private fun _product(p1: IPoint, p2: IPoint, p3: IPoint): Double = _product(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y) fun Triangle.pointInsideTriangle(x: Double, y: Double): Boolean { val sign0 = _product(p0.x, p0.y, p1.x, p1.y, p2.x, p2.y) val sign1 = _product(p0.x, p0.y, p1.x, p1.y, x, y) val sign2 = _product(p1.x, p1.y, p2.x, p2.y, x, y) val sign3 = _product(p2.x, p2.y, p0.x, p0.y, x, y) return if (sign0 >= 0) (sign1 >= 0) && (sign2 >= 0) && (sign3 >= 0) else (sign1 <= 0) && (sign2 <= 0) && (sign3 <= 0) } fun Triangle.pointInsideTriangle(pp: IPoint): Boolean = pointInsideTriangle(pp.x, pp.y) // Optimized? fun Triangle.getPointIndexOffsetNoThrow(p: IPoint, offset: Int = 0, notFound: Int = Int.MIN_VALUE): Int { var no: Int = offset for (n in 0 until 3) { while (no < 0) no += 3 while (no > 2) no -= 3 if (p == (this.point(n))) return no no++ } return notFound } fun Triangle.getPointIndexOffset(p: IPoint, offset: Int = 0): Int { val v = getPointIndexOffsetNoThrow(p, offset, Int.MIN_VALUE) if (v == Int.MIN_VALUE) throw Error("Point2d not in triangle") return v } fun Triangle.pointCW(p: IPoint): IPoint = this.point(getPointIndexOffset(p, -1)) fun Triangle.pointCCW(p: IPoint): IPoint = this.point(getPointIndexOffset(p, +1)) fun Triangle.oppositePoint(t: Triangle, p: IPoint): IPoint = this.pointCW(t.pointCW(p)) fun Triangle(p0: IPoint, p1: IPoint, p2: IPoint, fixOrientation: Boolean = false, checkOrientation: Boolean = true): Triangle { @Suppress("NAME_SHADOWING") var p1 = p1 @Suppress("NAME_SHADOWING") var p2 = p2 if (fixOrientation) { if (Orientation.orient2d(p0, p1, p2) == Orientation.CLOCK_WISE) { val pt = p2 p2 = p1 p1 = pt //println("Fixed orientation"); } } if (checkOrientation && Orientation.orient2d(p2, p1, p0) != Orientation.CLOCK_WISE) throw(Error("Triangle must defined with Orientation.CW")) return Triangle.Base(p0, p1, p2) } val Triangle.area: Double get() = Triangle.area(p0, p1, p2) /** Alias for getPointIndexOffset */ fun Triangle.index(p: IPoint): Int = this.getPointIndexOffsetNoThrow(p, 0, -1) fun Triangle.edgeIndex(p1: IPoint, p2: IPoint): Int { when (p1) { this.point(0) -> { if (p2 == this.point(1)) return 2 if (p2 == this.point(2)) return 1 } this.point(1) -> { if (p2 == this.point(2)) return 0 if (p2 == this.point(0)) return 2 } this.point(2) -> { if (p2 == this.point(0)) return 1 if (p2 == this.point(1)) return 0 } } return -1 } class TriangleList(val points: PointArrayList, val indices: ShortArray, val numTriangles: Int = indices.size / 3) : Iterable<Triangle> { val numIndices get() = numTriangles * 3 val pointCount get() = points.size val size get() = numTriangles @PublishedApi internal val tempTriangle: MutableTriangle = MutableTriangle() class MutableTriangle : Triangle { override val p0 = Point() override val p1 = Point() override val p2 = Point() override fun toString(): String = "Triangle($p0, $p1, $p2)" } fun getTriangle(index: Int, out: MutableTriangle = MutableTriangle()): MutableTriangle { points.getPoint(indices[index * 3 + 0].toInt() and 0xFFFF, out.p0) points.getPoint(indices[index * 3 + 1].toInt() and 0xFFFF, out.p1) points.getPoint(indices[index * 3 + 2].toInt() and 0xFFFF, out.p2) return out } fun getTriangles(): List<Triangle> = (0 until numTriangles).map { getTriangle(it) } fun toTriangleList(): List<Triangle> = (0 until numTriangles).map { getTriangle(it) } override fun toString(): String = "TriangleList[$numTriangles](${getTriangles()})" inline fun fastForEach(block: (MutableTriangle) -> Unit) { for (n in 0 until numTriangles) block(getTriangle(n, tempTriangle)) } inline fun <T> map(block: (MutableTriangle) -> T): List<T> { return arrayListOf<T>().also { out -> fastForEach { out += block(it) } } } override fun iterator(): Iterator<Triangle> = toTriangleList().iterator() }
0
Kotlin
0
0
ac8a318c48d775bbf3e8a659f217b879dc030566
8,735
korma
Boost Software License 1.0
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/caches/project/ModuleTestSourceInfo.kt
koxudaxi
196,571,905
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.caches.project import com.intellij.openapi.module.Module import org.jetbrains.annotations.ApiStatus @Deprecated("Use 'org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleTestSourceInfo' instead") @ApiStatus.ScheduledForRemoval interface ModuleTestSourceInfo { val module: Module }
1
null
1
1
641c9567cc039e31dd60adbe4011f1b80a168b59
454
intellij-community
Apache License 2.0
ub-app/src/main/kotlin/dev/cherryd/unibot/data/MessagesRepository.kt
Tema-man
744,223,241
false
{"Kotlin": 84357, "Dockerfile": 620}
package dev.cherryd.unibot.data import dev.cherryd.unibot.core.Post import io.github.oshai.kotlinlogging.KotlinLogging class MessagesRepository( private val database: Database ) { private val logger = KotlinLogging.logger {} fun savePosting(post: Post) { logger.debug { "Saving posting: ${post}" } database.execute( """ INSERT INTO messages (chat_id, user_id, message) VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET message = excluded.message """.trimIndent() ) { setString(1, post.chat.id) setString(2, post.sender.id) setString(3, post.extra.text) executeUpdate() logger.info { "Posting saved" } } } fun getRandomPosting(): String { logger.debug { "Getting random posting" } val posting = database.execute( """ SELECT message FROM messages ORDER BY RANDOM() LIMIT 1 """.trimIndent() ) { executeQuery().use { resultSet -> if (!resultSet.next()) return@execute "" resultSet.getString("message") } } ?: "" logger.debug { "Selected random posting: $posting" } return posting } }
0
Kotlin
0
0
ed73c31609bdde5588ab4c47492e7c048ecc7da9
1,291
unibot
MIT License